diff --git a/.gitignore b/.gitignore index 6858b0c8e..aeb771d9e 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ /jme3-desktop/build/ /jme3-android-native/build/ /jme3-android/build/ +/jme3-android-examples/build/ /jme3-blender/build/ /jme3-effects/build/ /jme3-bullet/build/ diff --git a/.travis.yml b/.travis.yml index 25aedbbe0..71c3b576f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,12 +1,41 @@ language: java -# jdk: -# - oraclejdk8 +sudo: false +env: + - GRADLE_USER_HOME=gradle-cache + +cache: + directories: + - gradle-cache + - netbeans branches: only: - master -before_install: +notifications: + slack: + on_success: change + on_failure: always + rooms: + secure: "PWEk4+VL986c3gAjWp12nqyifvxCjBqKoESG9d7zWh1uiTLadTHhZJRMdsye36FCpz/c/Jt7zCRO/5y7FaubQptnRrkrRfjp5f99MJRzQVXnUAM+y385qVkXKRKd/PLpM7XPm4AvjvxHCyvzX2wamRvul/TekaXKB9Ti5FCN87s=" + +install: + - ./gradlew assemble + +script: + - ./gradlew check + - ./gradlew createZipDistribution + +deploy: + provider: releases + api_key: + secure: "KbFiMt0a8FxUKvCJUYwikLYaqqGMn1p6k4OsXnGqwptQZEUIayabNLHeaD2kTNT3e6AY1ETwQLff/lB2LttmIo4g5NWW63g1K3A/HwgnhJwETengiProZ/Udl+ugPeDL/+ar43HUhFq4knBnzFKnEcHAThTPVqH/RMDvZf1UUYI=" + file: build/distributions/jME3.1.0_snapshot-github_2015-06-20.zip + skip_cleanup: true + on: + tags: true + +# before_install: # required libs for android build tools # sudo apt-get update # sudo apt-get install -qq p7zip-full diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ebecab28b..82ffeb4e8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -16,13 +16,6 @@ When you're ready to submit your code, just make a [pull request](https://help.g - When committing, always be sure to run an update before you commit. If there is a conflict between the latest revision and your patch after the update, then it is your responsibility to track down the update that caused the conflict and determine the issue (and fix it). In the case where the breaking commit has no thread linked (and one cannot be found in the forum), then the contributor should contact an administrator and wait for feedback before committing. - If your code is committed and it introduces new functionality, please edit the wiki accordingly. We can easily roll back to previous revisions, so just do your best; point us to it and we’ll see if it sticks! -**Note to Eclipse users:** The Eclipse [git client does not support https](http://hub.jmonkeyengine.org/forum/topic/problem-cloning-the-new-git-repository/#post-265594). The current workaround is to use the command line to clone the repository. -To import the local repository as a project follow these steps: - -1. Add a line 'apply plugin: eclipse' to your common.gradle file in the main project directory. -2. Navigate to the project directory in command line and execute command 'gradle eclipse'. This will load all the dependancies for eclipse. -3. In Eclipse, add the repository as an existing Java Project. - p.s. We will try hold ourselves to a [certain standard](http://www.defmacro.org/2013/04/03/issue-etiquette.html) when it comes to GitHub etiquette. If at any point we fail to uphold this standard, let us know. #### Core Contributors diff --git a/README.md b/README.md index 69d2207bd..29161ffa4 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,9 @@ -jMonkeyEngine +jMonkeyEngine ============= -jMonkeyEngine is a 3D game engine for adventurous Java developers. It’s open source, cross platform and cutting edge. And it is all beautifully documented. The 3.0 branch is the latest stable version of the jMonkeyEngine 3 SDK, a complete game development suite. We'll be frequently submitting stable 3.0.x updates until the major 3.1 version arrives in Q4 2014. +[![Build Status](https://travis-ci.org/jMonkeyEngine/jmonkeyengine.svg?branch=master)](https://travis-ci.org/jMonkeyEngine/jmonkeyengine) + +jMonkeyEngine is a 3D game engine for adventurous Java developers. It’s open source, cross platform and cutting edge. And it is all beautifully documented. The 3.0 branch is the latest stable version of the jMonkeyEngine 3 SDK, a complete game development suite. We'll be frequently submitting stable 3.0.x updates until the major 3.1 version arrives. The engine is used by several commercial game studios and computer-science courses. Here's a taste: diff --git a/build.gradle b/build.gradle index adb31217b..8e6790230 100644 --- a/build.gradle +++ b/build.gradle @@ -1,14 +1,23 @@ import org.gradle.api.artifacts.* -apply plugin: 'base' // To add "clean" task to the root project. -//apply plugin: 'java-library-distribution' +buildscript { + repositories { + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.1.0' + } +} + +apply plugin: 'base' // This is applied to all sub projects subprojects { - // Don't add to native builds - // if(!project.name.endsWith('native')){ - apply from: rootProject.file('common.gradle') - // } + if(!project.name.equals('jme3-android-examples')) { + apply from: rootProject.file('common.gradle') + } else { + apply from: rootProject.file('common-android-app.gradle') + } } task run(dependsOn: ':jme3-examples:run') { @@ -166,11 +175,11 @@ ext { // } //} -allprojects { - tasks.withType(JavaExec) { - enableAssertions = true // false by default - } - tasks.withType(Test) { - enableAssertions = true // true by default - } -} \ No newline at end of file +//allprojects { +// tasks.withType(JavaExec) { +// enableAssertions = true // false by default +// } +// tasks.withType(Test) { +// enableAssertions = true // true by default +// } +//} \ No newline at end of file diff --git a/common-android-app.gradle b/common-android-app.gradle new file mode 100644 index 000000000..0ec48fbd7 --- /dev/null +++ b/common-android-app.gradle @@ -0,0 +1,13 @@ +apply plugin: 'com.android.application' + +group = 'com.jme3' +version = jmeVersion + '-' + jmeVersionTag + +sourceCompatibility = '1.6' + +repositories { + mavenCentral() + maven { + url "http://nifty-gui.sourceforge.net/nifty-maven-repo" + } +} \ No newline at end of file diff --git a/common.gradle b/common.gradle index 9d65f7338..6af4c664f 100644 --- a/common.gradle +++ b/common.gradle @@ -4,16 +4,17 @@ apply plugin: 'java' apply plugin: 'maven' +apply plugin: 'maven-publish' -String mavenGroupId = 'com.jme3' -String mavenVersion = jmeVersion + '-' + jmeVersionTag //'-SNAPSHOT' +group = 'com.jme3' +version = jmeVersion + '-' + jmeVersionTag sourceCompatibility = '1.6' [compileJava, compileTestJava]*.options*.encoding = 'UTF-8' repositories { mavenCentral() - maven{ + maven { url "http://nifty-gui.sourceforge.net/nifty-maven-repo" } } @@ -23,11 +24,6 @@ dependencies { testCompile group: 'junit', name: 'junit', version: '4.10' } -String mavenArtifactId = name - -group = mavenGroupId -version = mavenVersion - javadoc { failOnError = false options.memberLevel = org.gradle.external.javadoc.JavadocMemberLevel.PROTECTED @@ -60,11 +56,40 @@ artifacts { } } -configure(install.repositories.mavenInstaller) { - pom.project { - groupId = mavenGroupId - artifactId = mavenArtifactId - version = mavenVersion +publishing { + publications { + maven(MavenPublication) { + from components.java + artifact sourcesJar + artifact javadocJar + + pom.withXml { + asNode().children().last() + { + resolveStrategy = Closure.DELEGATE_FIRST + name POM_NAME + description POM_DESCRIPTION + url POM_URL + scm { + url POM_SCM_URL + connection POM_SCM_CONNECTION + developerConnection POM_SCM_DEVELOPER_CONNECTION + } + licenses { + license { + name POM_LICENSE_NAME + url POM_LICENSE_URL + distribution POM_LICENSE_DISTRIBUTION + } + } + } + } + } + } + + repositories { + maven { + url "${rootProject.buildDir}/repo" // change to point to your repo, e.g. http://my.org/repo + } } } diff --git a/gradle.properties b/gradle.properties index 00429d65a..a00139bdf 100644 --- a/gradle.properties +++ b/gradle.properties @@ -11,6 +11,7 @@ buildJavaDoc = true # specify if SDK and Native libraries get built buildSdkProject = true buildNativeProjects = false +buildAndroidExamples = false # Path to android NDK for building native libraries #ndkPath=/Users/normenhansen/Documents/Code-Import/android-ndk-r7 @@ -23,3 +24,14 @@ bulletZipFile = bullet.zip # Path for downloading NetBeans Base netbeansUrl = http://download.netbeans.org/netbeans/8.0.2/final/zip/netbeans-8.0.2-201411181905-javase.zip + +# POM settings +POM_NAME=jMonkeyEngine +POM_DESCRIPTION=jMonkeyEngine is a 3D game engine for adventurous Java developers +POM_URL=http://jmonkeyengine.org +POM_SCM_URL=https://github.com/jMonkeyEngine/jmonkeyengine +POM_SCM_CONNECTION=scm:git:git://github.com/jMonkeyEngine/jmonkeyengine.git +POM_SCM_DEVELOPER_CONNECTION=scm:git:git@github.com:jMonkeyEngine/jmonkeyengine.git +POM_LICENSE_NAME=New BSD (3-clause) License +POM_LICENSE_URL=http://opensource.org/licenses/BSD-3-Clause +POM_LICENSE_DISTRIBUTION=repo diff --git a/jme3-android-examples/build.gradle b/jme3-android-examples/build.gradle new file mode 100644 index 000000000..f1ee38739 --- /dev/null +++ b/jme3-android-examples/build.gradle @@ -0,0 +1,40 @@ +dependencies { + compile project(':jme3-core') + compile project(':jme3-android') + compile project(':jme3-effects') + compile project(':jme3-bullet') + compile project(':jme3-bullet-native-android') + compile project(':jme3-networking') + compile project(':jme3-niftygui') + compile project(':jme3-plugins') + compile project(':jme3-terrain') + compile project(':jme3-testdata') +} + +android { + compileSdkVersion 10 + buildToolsVersion "22.0.1" + + lintOptions { + // Fix nifty gui referencing "java.awt" package. + disable 'InvalidPackage' + } + + defaultConfig { + applicationId "com.jme3.android" + minSdkVersion 10 // Android 2.3 GINGERBREAD + targetSdkVersion 22 // Android 5.1 LOLLIPOP + versionCode 1 + versionName "1.0" // TODO: from settings.gradle + } + + buildTypes { + release { + minifyEnabled false + } + debug { + applicationIdSuffix ".debug" + debuggable true + } + } +} \ No newline at end of file diff --git a/jme3-android-examples/src/main/AndroidManifest.xml b/jme3-android-examples/src/main/AndroidManifest.xml new file mode 100644 index 000000000..ee80b6b28 --- /dev/null +++ b/jme3-android-examples/src/main/AndroidManifest.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jme3-android-examples/src/main/java/jme3test/android/TestChooserAndroid.java b/jme3-android-examples/src/main/java/jme3test/android/TestChooserAndroid.java new file mode 100644 index 000000000..e704bc85a --- /dev/null +++ b/jme3-android-examples/src/main/java/jme3test/android/TestChooserAndroid.java @@ -0,0 +1,12 @@ +package jme3test.android; + +import android.content.pm.ActivityInfo; +import android.app.*; +import android.os.Bundle; + +public class TestChooserAndroid extends Activity { + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + } +} \ No newline at end of file diff --git a/jme3-android-examples/src/main/res/values/strings.xml b/jme3-android-examples/src/main/res/values/strings.xml new file mode 100644 index 000000000..b184fa936 --- /dev/null +++ b/jme3-android-examples/src/main/res/values/strings.xml @@ -0,0 +1,6 @@ + + + JMEAndroidTest + About + Quit + \ No newline at end of file diff --git a/jme3-android/src/main/java/com/jme3/app/AndroidHarness.java b/jme3-android/src/main/java/com/jme3/app/AndroidHarness.java index 1d2835bc3..b103e92df 100644 --- a/jme3-android/src/main/java/com/jme3/app/AndroidHarness.java +++ b/jme3-android/src/main/java/com/jme3/app/AndroidHarness.java @@ -1,586 +1,580 @@ -package com.jme3.app; - -import android.app.Activity; -import android.app.AlertDialog; -import android.content.DialogInterface; -import android.content.pm.ActivityInfo; -import android.graphics.drawable.Drawable; -import android.graphics.drawable.NinePatchDrawable; -import android.opengl.GLSurfaceView; -import android.os.Bundle; -import android.util.Log; -import android.view.*; -import android.view.ViewGroup.LayoutParams; -import android.widget.FrameLayout; -import android.widget.ImageView; -import android.widget.TextView; -import com.jme3.audio.AudioRenderer; -import com.jme3.input.JoyInput; -import com.jme3.input.TouchInput; -import com.jme3.input.android.AndroidSensorJoyInput; -import com.jme3.input.controls.TouchListener; -import com.jme3.input.controls.TouchTrigger; -import com.jme3.input.event.TouchEvent; -import com.jme3.system.AppSettings; -import com.jme3.system.SystemListener; -import com.jme3.system.android.JmeAndroidSystem; -import com.jme3.system.android.OGLESContext; -import com.jme3.util.AndroidLogHandler; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.LogManager; -import java.util.logging.Logger; - -/** - * AndroidHarness wraps a jme application object and runs it on - * Android - * - * @author Kirill - * @author larynx - */ -public class AndroidHarness extends Activity implements TouchListener, DialogInterface.OnClickListener, SystemListener { - - protected final static Logger logger = Logger.getLogger(AndroidHarness.class.getName()); - /** - * The application class to start - */ - protected String appClass = "jme3test.android.Test"; - /** - * The jme3 application object - */ - protected Application app = null; - - /** - * Sets the desired RGB size for the surfaceview. 16 = RGB565, 24 = RGB888. - * (default = 24) - */ - protected int eglBitsPerPixel = 24; - - /** - * Sets the desired number of Alpha bits for the surfaceview. This affects - * how the surfaceview is able to display Android views that are located - * under the surfaceview jME uses to render the scenegraph. - * 0 = Opaque surfaceview background (fastest) - * 1->7 = Transparent surfaceview background - * 8 or higher = Translucent surfaceview background - * (default = 0) - */ - protected int eglAlphaBits = 0; - - /** - * The number of depth bits specifies the precision of the depth buffer. - * (default = 16) - */ - protected int eglDepthBits = 16; - - /** - * Sets the number of samples to use for multisampling.
- * Leave 0 (default) to disable multisampling.
- * Set to 2 or 4 to enable multisampling. - */ - protected int eglSamples = 0; - - /** - * Set the number of stencil bits. - * (default = 0) - */ - protected int eglStencilBits = 0; - - /** - * Set the desired frame rate. If frameRate > 0, the application - * will be capped at the desired frame rate. - * (default = -1, no frame rate cap) - */ - protected int frameRate = -1; - - /** - * Sets the type of Audio Renderer to be used. - *

- * Android MediaPlayer / SoundPool can be used on all - * supported Android platform versions (2.2+)
- * OpenAL Soft uses an OpenSL backend and is only supported on Android - * versions 2.3+. - *

- * Only use ANDROID_ static strings found in AppSettings - * - */ - protected String audioRendererType = AppSettings.ANDROID_OPENAL_SOFT; - - /** - * If true Android Sensors are used as simulated Joysticks. Users can use the - * Android sensor feedback through the RawInputListener or by registering - * JoyAxisTriggers. - */ - protected boolean joystickEventsEnabled = false; - /** - * If true KeyEvents are generated from TouchEvents - */ - protected boolean keyEventsEnabled = true; - /** - * If true MouseEvents are generated from TouchEvents - */ - protected boolean mouseEventsEnabled = true; - /** - * Flip X axis - */ - protected boolean mouseEventsInvertX = false; - /** - * Flip Y axis - */ - protected boolean mouseEventsInvertY = false; - /** - * if true finish this activity when the jme app is stopped - */ - protected boolean finishOnAppStop = true; - /** - * set to false if you don't want the harness to handle the exit hook - */ - protected boolean handleExitHook = true; - /** - * Title of the exit dialog, default is "Do you want to exit?" - */ - protected String exitDialogTitle = "Do you want to exit?"; - /** - * Message of the exit dialog, default is "Use your home key to bring this - * app into the background or exit to terminate it." - */ - protected String exitDialogMessage = "Use your home key to bring this app into the background or exit to terminate it."; - /** - * Set the screen window mode. If screenFullSize is true, then the - * notification bar and title bar are removed and the screen covers the - * entire display. If screenFullSize is false, then the notification bar - * remains visible if screenShowTitle is true while screenFullScreen is - * false, then the title bar is also displayed under the notification bar. - */ - protected boolean screenFullScreen = true; - /** - * if screenShowTitle is true while screenFullScreen is false, then the - * title bar is also displayed under the notification bar - */ - protected boolean screenShowTitle = true; - /** - * Splash Screen picture Resource ID. If a Splash Screen is desired, set - * splashPicID to the value of the Resource ID (i.e. R.drawable.picname). If - * splashPicID = 0, then no splash screen will be displayed. - */ - protected int splashPicID = 0; - - /** - * No longer used - Use the android:screenOrientation declaration in - * the AndroidManifest.xml file. - */ - @Deprecated - protected int screenOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR; - - protected OGLESContext ctx; - protected GLSurfaceView view = null; - protected boolean isGLThreadPaused = true; - protected ImageView splashImageView = null; - protected FrameLayout frameLayout = null; - final private String ESCAPE_EVENT = "TouchEscape"; - private boolean firstDrawFrame = true; - private boolean inConfigChange = false; - - private class DataObject { - protected Application app = null; - } - - @Override - public Object onRetainNonConfigurationInstance() { - logger.log(Level.FINE, "onRetainNonConfigurationInstance"); - final DataObject data = new DataObject(); - data.app = this.app; - inConfigChange = true; - return data; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - initializeLogHandler(); - - logger.fine("onCreate"); - super.onCreate(savedInstanceState); - - if (screenFullScreen) { - requestWindowFeature(Window.FEATURE_NO_TITLE); - getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, - WindowManager.LayoutParams.FLAG_FULLSCREEN); - } else { - if (!screenShowTitle) { - requestWindowFeature(Window.FEATURE_NO_TITLE); - } - } - - final DataObject data = (DataObject) getLastNonConfigurationInstance(); - if (data != null) { - logger.log(Level.FINE, "Using Retained App"); - this.app = data.app; - } else { - // Discover the screen reolution - //TODO try to find a better way to get a hand on the resolution - WindowManager wind = this.getWindowManager(); - Display disp = wind.getDefaultDisplay(); - Log.d("AndroidHarness", "Resolution from Window, width:" + disp.getWidth() + ", height: " + disp.getHeight()); - - // Create Settings - logger.log(Level.FINE, "Creating settings"); - AppSettings settings = new AppSettings(true); - settings.setEmulateMouse(mouseEventsEnabled); - settings.setEmulateMouseFlipAxis(mouseEventsInvertX, mouseEventsInvertY); - settings.setUseJoysticks(joystickEventsEnabled); - settings.setEmulateKeyboard(keyEventsEnabled); - - settings.setBitsPerPixel(eglBitsPerPixel); - settings.setAlphaBits(eglAlphaBits); - settings.setDepthBits(eglDepthBits); - settings.setSamples(eglSamples); - settings.setStencilBits(eglStencilBits); - - settings.setResolution(disp.getWidth(), disp.getHeight()); - settings.setAudioRenderer(audioRendererType); - - settings.setFrameRate(frameRate); - - // Create application instance - try { - if (app == null) { - @SuppressWarnings("unchecked") - Class clazz = (Class) Class.forName(appClass); - app = clazz.newInstance(); - } - - app.setSettings(settings); - app.start(); - } catch (Exception ex) { - handleError("Class " + appClass + " init failed", ex); - setContentView(new TextView(this)); - } - } - - ctx = (OGLESContext) app.getContext(); - view = ctx.createView(this); - // store the glSurfaceView in JmeAndroidSystem for future use - JmeAndroidSystem.setView(view); - // AndroidHarness wraps the app as a SystemListener. - ctx.setSystemListener(this); - layoutDisplay(); - } - - @Override - protected void onRestart() { - logger.fine("onRestart"); - super.onRestart(); - if (app != null) { - app.restart(); - } - } - - @Override - protected void onStart() { - logger.fine("onStart"); - super.onStart(); - } - - @Override - protected void onResume() { - logger.fine("onResume"); - super.onResume(); - - gainFocus(); - } - - @Override - protected void onPause() { - logger.fine("onPause"); - loseFocus(); - - super.onPause(); - } - - @Override - protected void onStop() { - logger.fine("onStop"); - super.onStop(); - } - - @Override - protected void onDestroy() { - logger.fine("onDestroy"); - final DataObject data = (DataObject) getLastNonConfigurationInstance(); - if (data != null || inConfigChange) { - logger.fine("In Config Change, not stopping app."); - } else { - if (app != null) { - app.stop(!isGLThreadPaused); - } - } - setContentView(new TextView(this)); - ctx = null; - app = null; - view = null; - JmeAndroidSystem.setView(null); - - super.onDestroy(); - } - - public Application getJmeApplication() { - return app; - } - - /** - * Called when an error has occurred. By default, will show an error message - * to the user and print the exception/error to the log. - */ - @Override - public void handleError(final String errorMsg, final Throwable t) { - String stackTrace = ""; - String title = "Error"; - - if (t != null) { - // Convert exception to string - StringWriter sw = new StringWriter(100); - t.printStackTrace(new PrintWriter(sw)); - stackTrace = sw.toString(); - title = t.toString(); - } - - final String finalTitle = title; - final String finalMsg = (errorMsg != null ? errorMsg : "Uncaught Exception") - + "\n" + stackTrace; - - logger.log(Level.SEVERE, finalMsg); - - runOnUiThread(new Runnable() { - @Override - public void run() { - AlertDialog dialog = new AlertDialog.Builder(AndroidHarness.this) // .setIcon(R.drawable.alert_dialog_icon) - .setTitle(finalTitle).setPositiveButton("Kill", AndroidHarness.this).setMessage(finalMsg).create(); - dialog.show(); - } - }); - } - - /** - * Called by the android alert dialog, terminate the activity and OpenGL - * rendering - * - * @param dialog - * @param whichButton - */ - public void onClick(DialogInterface dialog, int whichButton) { - if (whichButton != -2) { - if (app != null) { - app.stop(true); - } - app = null; - this.finish(); - } - } - - /** - * Gets called by the InputManager on all touch/drag/scale events - */ - @Override - public void onTouch(String name, TouchEvent evt, float tpf) { - if (name.equals(ESCAPE_EVENT)) { - switch (evt.getType()) { - case KEY_UP: - runOnUiThread(new Runnable() { - @Override - public void run() { - AlertDialog dialog = new AlertDialog.Builder(AndroidHarness.this) // .setIcon(R.drawable.alert_dialog_icon) - .setTitle(exitDialogTitle).setPositiveButton("Yes", AndroidHarness.this).setNegativeButton("No", AndroidHarness.this).setMessage(exitDialogMessage).create(); - dialog.show(); - } - }); - break; - default: - break; - } - } - } - - public void layoutDisplay() { - logger.log(Level.FINE, "Splash Screen Picture Resource ID: {0}", splashPicID); - if (view == null) { - logger.log(Level.FINE, "view is null!"); - } - if (splashPicID != 0) { - FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams( - LayoutParams.MATCH_PARENT, - LayoutParams.MATCH_PARENT, - Gravity.CENTER); - - frameLayout = new FrameLayout(this); - splashImageView = new ImageView(this); - - Drawable drawable = this.getResources().getDrawable(splashPicID); - if (drawable instanceof NinePatchDrawable) { - splashImageView.setBackgroundDrawable(drawable); - } else { - splashImageView.setImageResource(splashPicID); - } - - if (view.getParent() != null) { - ((ViewGroup) view.getParent()).removeView(view); - } - frameLayout.addView(view); - - if (splashImageView.getParent() != null) { - ((ViewGroup) splashImageView.getParent()).removeView(splashImageView); - } - frameLayout.addView(splashImageView, lp); - - setContentView(frameLayout); - logger.log(Level.FINE, "Splash Screen Created"); - } else { - logger.log(Level.FINE, "Splash Screen Skipped."); - setContentView(view); - } - } - - public void removeSplashScreen() { - logger.log(Level.FINE, "Splash Screen Picture Resource ID: {0}", splashPicID); - if (splashPicID != 0) { - if (frameLayout != null) { - if (splashImageView != null) { - this.runOnUiThread(new Runnable() { - @Override - public void run() { - splashImageView.setVisibility(View.INVISIBLE); - frameLayout.removeView(splashImageView); - } - }); - } else { - logger.log(Level.FINE, "splashImageView is null"); - } - } else { - logger.log(Level.FINE, "frameLayout is null"); - } - } - } - - /** - * Removes the standard Android log handler due to an issue with not logging - * entries lower than INFO level and adds a handler that produces - * JME formatted log messages. - */ - protected void initializeLogHandler() { - Logger log = LogManager.getLogManager().getLogger(""); - for (Handler handler : log.getHandlers()) { - if (log.getLevel() != null && log.getLevel().intValue() <= Level.FINE.intValue()) { - Log.v("AndroidHarness", "Removing Handler class: " + handler.getClass().getName()); - } - log.removeHandler(handler); - } - Handler handler = new AndroidLogHandler(); - log.addHandler(handler); - handler.setLevel(Level.ALL); - } - - public void initialize() { - app.initialize(); - if (handleExitHook) { - // remove existing mapping from SimpleApplication that stops the app - // when the esc key is pressed (esc key = android back key) so that - // AndroidHarness can produce the exit app dialog box. - if (app.getInputManager().hasMapping(SimpleApplication.INPUT_MAPPING_EXIT)) { - app.getInputManager().deleteMapping(SimpleApplication.INPUT_MAPPING_EXIT); - } - - app.getInputManager().addMapping(ESCAPE_EVENT, new TouchTrigger(TouchInput.KEYCODE_BACK)); - app.getInputManager().addListener(this, new String[]{ESCAPE_EVENT}); - } - } - - public void reshape(int width, int height) { - app.reshape(width, height); - } - - public void update() { - app.update(); - // call to remove the splash screen, if present. - // call after app.update() to make sure no gap between - // splash screen going away and app display being shown. - if (firstDrawFrame) { - removeSplashScreen(); - firstDrawFrame = false; - } - } - - public void requestClose(boolean esc) { - app.requestClose(esc); - } - - public void destroy() { - if (app != null) { - app.destroy(); - } - if (finishOnAppStop) { - finish(); - } - } - - public void gainFocus() { - logger.fine("gainFocus"); - if (view != null) { - view.onResume(); - } - - if (app != null) { - //resume the audio - AudioRenderer audioRenderer = app.getAudioRenderer(); - if (audioRenderer != null) { - audioRenderer.resumeAll(); - } - //resume the sensors (aka joysticks) - if (app.getContext() != null) { - JoyInput joyInput = app.getContext().getJoyInput(); - if (joyInput != null) { - if (joyInput instanceof AndroidSensorJoyInput) { - AndroidSensorJoyInput androidJoyInput = (AndroidSensorJoyInput) joyInput; - androidJoyInput.resumeSensors(); - } - } - } - } - - isGLThreadPaused = false; - - if (app != null) { - app.gainFocus(); - } - } - - public void loseFocus() { - logger.fine("loseFocus"); - if (app != null) { - app.loseFocus(); - } - - if (view != null) { - view.onPause(); - } - - if (app != null) { - //pause the audio - AudioRenderer audioRenderer = app.getAudioRenderer(); - if (audioRenderer != null) { - audioRenderer.pauseAll(); - } - //pause the sensors (aka joysticks) - if (app.getContext() != null) { - JoyInput joyInput = app.getContext().getJoyInput(); - if (joyInput != null) { - if (joyInput instanceof AndroidSensorJoyInput) { - AndroidSensorJoyInput androidJoyInput = (AndroidSensorJoyInput) joyInput; - androidJoyInput.pauseSensors(); - } - } - } - } - isGLThreadPaused = true; - } -} +package com.jme3.app; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.DialogInterface; +import android.content.pm.ActivityInfo; +import android.graphics.drawable.Drawable; +import android.graphics.drawable.NinePatchDrawable; +import android.opengl.GLSurfaceView; +import android.os.Bundle; +import android.util.Log; +import android.view.*; +import android.view.ViewGroup.LayoutParams; +import android.widget.FrameLayout; +import android.widget.ImageView; +import android.widget.TextView; +import com.jme3.audio.AudioRenderer; +import com.jme3.input.JoyInput; +import com.jme3.input.TouchInput; +import com.jme3.input.android.AndroidSensorJoyInput; +import com.jme3.input.controls.TouchListener; +import com.jme3.input.controls.TouchTrigger; +import com.jme3.input.event.TouchEvent; +import com.jme3.system.AppSettings; +import com.jme3.system.SystemListener; +import com.jme3.system.android.JmeAndroidSystem; +import com.jme3.system.android.OGLESContext; +import com.jme3.util.AndroidLogHandler; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogManager; +import java.util.logging.Logger; + +/** + * AndroidHarness wraps a jme application object and runs it on + * Android + * + * @author Kirill + * @author larynx + */ +public class AndroidHarness extends Activity implements TouchListener, DialogInterface.OnClickListener, SystemListener { + + protected final static Logger logger = Logger.getLogger(AndroidHarness.class.getName()); + /** + * The application class to start + */ + protected String appClass = "jme3test.android.Test"; + /** + * The jme3 application object + */ + protected Application app = null; + + /** + * Sets the desired RGB size for the surfaceview. 16 = RGB565, 24 = RGB888. + * (default = 24) + */ + protected int eglBitsPerPixel = 24; + + /** + * Sets the desired number of Alpha bits for the surfaceview. This affects + * how the surfaceview is able to display Android views that are located + * under the surfaceview jME uses to render the scenegraph. + * 0 = Opaque surfaceview background (fastest) + * 1->7 = Transparent surfaceview background + * 8 or higher = Translucent surfaceview background + * (default = 0) + */ + protected int eglAlphaBits = 0; + + /** + * The number of depth bits specifies the precision of the depth buffer. + * (default = 16) + */ + protected int eglDepthBits = 16; + + /** + * Sets the number of samples to use for multisampling.
+ * Leave 0 (default) to disable multisampling.
+ * Set to 2 or 4 to enable multisampling. + */ + protected int eglSamples = 0; + + /** + * Set the number of stencil bits. + * (default = 0) + */ + protected int eglStencilBits = 0; + + /** + * Set the desired frame rate. If frameRate > 0, the application + * will be capped at the desired frame rate. + * (default = -1, no frame rate cap) + */ + protected int frameRate = -1; + + /** + * Sets the type of Audio Renderer to be used. + *

+ * Android MediaPlayer / SoundPool can be used on all + * supported Android platform versions (2.2+)
+ * OpenAL Soft uses an OpenSL backend and is only supported on Android + * versions 2.3+. + *

+ * Only use ANDROID_ static strings found in AppSettings + * + */ + protected String audioRendererType = AppSettings.ANDROID_OPENAL_SOFT; + + /** + * If true Android Sensors are used as simulated Joysticks. Users can use the + * Android sensor feedback through the RawInputListener or by registering + * JoyAxisTriggers. + */ + protected boolean joystickEventsEnabled = false; + /** + * If true KeyEvents are generated from TouchEvents + */ + protected boolean keyEventsEnabled = true; + /** + * If true MouseEvents are generated from TouchEvents + */ + protected boolean mouseEventsEnabled = true; + /** + * Flip X axis + */ + protected boolean mouseEventsInvertX = false; + /** + * Flip Y axis + */ + protected boolean mouseEventsInvertY = false; + /** + * if true finish this activity when the jme app is stopped + */ + protected boolean finishOnAppStop = true; + /** + * set to false if you don't want the harness to handle the exit hook + */ + protected boolean handleExitHook = true; + /** + * Title of the exit dialog, default is "Do you want to exit?" + */ + protected String exitDialogTitle = "Do you want to exit?"; + /** + * Message of the exit dialog, default is "Use your home key to bring this + * app into the background or exit to terminate it." + */ + protected String exitDialogMessage = "Use your home key to bring this app into the background or exit to terminate it."; + /** + * Set the screen window mode. If screenFullSize is true, then the + * notification bar and title bar are removed and the screen covers the + * entire display. If screenFullSize is false, then the notification bar + * remains visible if screenShowTitle is true while screenFullScreen is + * false, then the title bar is also displayed under the notification bar. + */ + protected boolean screenFullScreen = true; + /** + * if screenShowTitle is true while screenFullScreen is false, then the + * title bar is also displayed under the notification bar + */ + protected boolean screenShowTitle = true; + /** + * Splash Screen picture Resource ID. If a Splash Screen is desired, set + * splashPicID to the value of the Resource ID (i.e. R.drawable.picname). If + * splashPicID = 0, then no splash screen will be displayed. + */ + protected int splashPicID = 0; + + + protected OGLESContext ctx; + protected GLSurfaceView view = null; + protected boolean isGLThreadPaused = true; + protected ImageView splashImageView = null; + protected FrameLayout frameLayout = null; + final private String ESCAPE_EVENT = "TouchEscape"; + private boolean firstDrawFrame = true; + private boolean inConfigChange = false; + + private class DataObject { + protected Application app = null; + } + + @Override + public Object onRetainNonConfigurationInstance() { + logger.log(Level.FINE, "onRetainNonConfigurationInstance"); + final DataObject data = new DataObject(); + data.app = this.app; + inConfigChange = true; + return data; + } + + @Override + public void onCreate(Bundle savedInstanceState) { + initializeLogHandler(); + + logger.fine("onCreate"); + super.onCreate(savedInstanceState); + + if (screenFullScreen) { + requestWindowFeature(Window.FEATURE_NO_TITLE); + getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, + WindowManager.LayoutParams.FLAG_FULLSCREEN); + } else { + if (!screenShowTitle) { + requestWindowFeature(Window.FEATURE_NO_TITLE); + } + } + + final DataObject data = (DataObject) getLastNonConfigurationInstance(); + if (data != null) { + logger.log(Level.FINE, "Using Retained App"); + this.app = data.app; + } else { + // Discover the screen reolution + //TODO try to find a better way to get a hand on the resolution + WindowManager wind = this.getWindowManager(); + Display disp = wind.getDefaultDisplay(); + Log.d("AndroidHarness", "Resolution from Window, width:" + disp.getWidth() + ", height: " + disp.getHeight()); + + // Create Settings + logger.log(Level.FINE, "Creating settings"); + AppSettings settings = new AppSettings(true); + settings.setEmulateMouse(mouseEventsEnabled); + settings.setEmulateMouseFlipAxis(mouseEventsInvertX, mouseEventsInvertY); + settings.setUseJoysticks(joystickEventsEnabled); + settings.setEmulateKeyboard(keyEventsEnabled); + + settings.setBitsPerPixel(eglBitsPerPixel); + settings.setAlphaBits(eglAlphaBits); + settings.setDepthBits(eglDepthBits); + settings.setSamples(eglSamples); + settings.setStencilBits(eglStencilBits); + + settings.setResolution(disp.getWidth(), disp.getHeight()); + settings.setAudioRenderer(audioRendererType); + + settings.setFrameRate(frameRate); + + // Create application instance + try { + if (app == null) { + @SuppressWarnings("unchecked") + Class clazz = (Class) Class.forName(appClass); + app = clazz.newInstance(); + } + + app.setSettings(settings); + app.start(); + } catch (Exception ex) { + handleError("Class " + appClass + " init failed", ex); + setContentView(new TextView(this)); + } + } + + ctx = (OGLESContext) app.getContext(); + view = ctx.createView(this); + // store the glSurfaceView in JmeAndroidSystem for future use + JmeAndroidSystem.setView(view); + // AndroidHarness wraps the app as a SystemListener. + ctx.setSystemListener(this); + layoutDisplay(); + } + + @Override + protected void onRestart() { + logger.fine("onRestart"); + super.onRestart(); + if (app != null) { + app.restart(); + } + } + + @Override + protected void onStart() { + logger.fine("onStart"); + super.onStart(); + } + + @Override + protected void onResume() { + logger.fine("onResume"); + super.onResume(); + + gainFocus(); + } + + @Override + protected void onPause() { + logger.fine("onPause"); + loseFocus(); + + super.onPause(); + } + + @Override + protected void onStop() { + logger.fine("onStop"); + super.onStop(); + } + + @Override + protected void onDestroy() { + logger.fine("onDestroy"); + final DataObject data = (DataObject) getLastNonConfigurationInstance(); + if (data != null || inConfigChange) { + logger.fine("In Config Change, not stopping app."); + } else { + if (app != null) { + app.stop(!isGLThreadPaused); + } + } + setContentView(new TextView(this)); + ctx = null; + app = null; + view = null; + JmeAndroidSystem.setView(null); + + super.onDestroy(); + } + + public Application getJmeApplication() { + return app; + } + + /** + * Called when an error has occurred. By default, will show an error message + * to the user and print the exception/error to the log. + */ + @Override + public void handleError(final String errorMsg, final Throwable t) { + String stackTrace = ""; + String title = "Error"; + + if (t != null) { + // Convert exception to string + StringWriter sw = new StringWriter(100); + t.printStackTrace(new PrintWriter(sw)); + stackTrace = sw.toString(); + title = t.toString(); + } + + final String finalTitle = title; + final String finalMsg = (errorMsg != null ? errorMsg : "Uncaught Exception") + + "\n" + stackTrace; + + logger.log(Level.SEVERE, finalMsg); + + runOnUiThread(new Runnable() { + @Override + public void run() { + AlertDialog dialog = new AlertDialog.Builder(AndroidHarness.this) // .setIcon(R.drawable.alert_dialog_icon) + .setTitle(finalTitle).setPositiveButton("Kill", AndroidHarness.this).setMessage(finalMsg).create(); + dialog.show(); + } + }); + } + + /** + * Called by the android alert dialog, terminate the activity and OpenGL + * rendering + * + * @param dialog + * @param whichButton + */ + public void onClick(DialogInterface dialog, int whichButton) { + if (whichButton != -2) { + if (app != null) { + app.stop(true); + } + app = null; + this.finish(); + } + } + + /** + * Gets called by the InputManager on all touch/drag/scale events + */ + @Override + public void onTouch(String name, TouchEvent evt, float tpf) { + if (name.equals(ESCAPE_EVENT)) { + switch (evt.getType()) { + case KEY_UP: + runOnUiThread(new Runnable() { + @Override + public void run() { + AlertDialog dialog = new AlertDialog.Builder(AndroidHarness.this) // .setIcon(R.drawable.alert_dialog_icon) + .setTitle(exitDialogTitle).setPositiveButton("Yes", AndroidHarness.this).setNegativeButton("No", AndroidHarness.this).setMessage(exitDialogMessage).create(); + dialog.show(); + } + }); + break; + default: + break; + } + } + } + + public void layoutDisplay() { + logger.log(Level.FINE, "Splash Screen Picture Resource ID: {0}", splashPicID); + if (view == null) { + logger.log(Level.FINE, "view is null!"); + } + if (splashPicID != 0) { + FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams( + LayoutParams.MATCH_PARENT, + LayoutParams.MATCH_PARENT, + Gravity.CENTER); + + frameLayout = new FrameLayout(this); + splashImageView = new ImageView(this); + + Drawable drawable = this.getResources().getDrawable(splashPicID); + if (drawable instanceof NinePatchDrawable) { + splashImageView.setBackgroundDrawable(drawable); + } else { + splashImageView.setImageResource(splashPicID); + } + + if (view.getParent() != null) { + ((ViewGroup) view.getParent()).removeView(view); + } + frameLayout.addView(view); + + if (splashImageView.getParent() != null) { + ((ViewGroup) splashImageView.getParent()).removeView(splashImageView); + } + frameLayout.addView(splashImageView, lp); + + setContentView(frameLayout); + logger.log(Level.FINE, "Splash Screen Created"); + } else { + logger.log(Level.FINE, "Splash Screen Skipped."); + setContentView(view); + } + } + + public void removeSplashScreen() { + logger.log(Level.FINE, "Splash Screen Picture Resource ID: {0}", splashPicID); + if (splashPicID != 0) { + if (frameLayout != null) { + if (splashImageView != null) { + this.runOnUiThread(new Runnable() { + @Override + public void run() { + splashImageView.setVisibility(View.INVISIBLE); + frameLayout.removeView(splashImageView); + } + }); + } else { + logger.log(Level.FINE, "splashImageView is null"); + } + } else { + logger.log(Level.FINE, "frameLayout is null"); + } + } + } + + /** + * Removes the standard Android log handler due to an issue with not logging + * entries lower than INFO level and adds a handler that produces + * JME formatted log messages. + */ + protected void initializeLogHandler() { + Logger log = LogManager.getLogManager().getLogger(""); + for (Handler handler : log.getHandlers()) { + if (log.getLevel() != null && log.getLevel().intValue() <= Level.FINE.intValue()) { + Log.v("AndroidHarness", "Removing Handler class: " + handler.getClass().getName()); + } + log.removeHandler(handler); + } + Handler handler = new AndroidLogHandler(); + log.addHandler(handler); + handler.setLevel(Level.ALL); + } + + public void initialize() { + app.initialize(); + if (handleExitHook) { + // remove existing mapping from SimpleApplication that stops the app + // when the esc key is pressed (esc key = android back key) so that + // AndroidHarness can produce the exit app dialog box. + if (app.getInputManager().hasMapping(SimpleApplication.INPUT_MAPPING_EXIT)) { + app.getInputManager().deleteMapping(SimpleApplication.INPUT_MAPPING_EXIT); + } + + app.getInputManager().addMapping(ESCAPE_EVENT, new TouchTrigger(TouchInput.KEYCODE_BACK)); + app.getInputManager().addListener(this, new String[]{ESCAPE_EVENT}); + } + } + + public void reshape(int width, int height) { + app.reshape(width, height); + } + + public void update() { + app.update(); + // call to remove the splash screen, if present. + // call after app.update() to make sure no gap between + // splash screen going away and app display being shown. + if (firstDrawFrame) { + removeSplashScreen(); + firstDrawFrame = false; + } + } + + public void requestClose(boolean esc) { + app.requestClose(esc); + } + + public void destroy() { + if (app != null) { + app.destroy(); + } + if (finishOnAppStop) { + finish(); + } + } + + public void gainFocus() { + logger.fine("gainFocus"); + if (view != null) { + view.onResume(); + } + + if (app != null) { + //resume the audio + AudioRenderer audioRenderer = app.getAudioRenderer(); + if (audioRenderer != null) { + audioRenderer.resumeAll(); + } + //resume the sensors (aka joysticks) + if (app.getContext() != null) { + JoyInput joyInput = app.getContext().getJoyInput(); + if (joyInput != null) { + if (joyInput instanceof AndroidSensorJoyInput) { + AndroidSensorJoyInput androidJoyInput = (AndroidSensorJoyInput) joyInput; + androidJoyInput.resumeSensors(); + } + } + } + } + + isGLThreadPaused = false; + + if (app != null) { + app.gainFocus(); + } + } + + public void loseFocus() { + logger.fine("loseFocus"); + if (app != null) { + app.loseFocus(); + } + + if (view != null) { + view.onPause(); + } + + if (app != null) { + //pause the audio + AudioRenderer audioRenderer = app.getAudioRenderer(); + if (audioRenderer != null) { + audioRenderer.pauseAll(); + } + //pause the sensors (aka joysticks) + if (app.getContext() != null) { + JoyInput joyInput = app.getContext().getJoyInput(); + if (joyInput != null) { + if (joyInput instanceof AndroidSensorJoyInput) { + AndroidSensorJoyInput androidJoyInput = (AndroidSensorJoyInput) joyInput; + androidJoyInput.pauseSensors(); + } + } + } + } + isGLThreadPaused = true; + } +} diff --git a/jme3-android/src/main/java/com/jme3/app/AndroidHarnessFragment.java b/jme3-android/src/main/java/com/jme3/app/AndroidHarnessFragment.java index 1b205d6dd..5673c8609 100644 --- a/jme3-android/src/main/java/com/jme3/app/AndroidHarnessFragment.java +++ b/jme3-android/src/main/java/com/jme3/app/AndroidHarnessFragment.java @@ -195,19 +195,6 @@ public class AndroidHarnessFragment extends Fragment implements */ protected String exitDialogMessage = "Use your home key to bring this app into the background or exit to terminate it."; - /** - * Set the screen window mode. If screenFullSize is true, then the - * notification bar and title bar are removed and the screen covers the - * entire display. If screenFullSize is false, then the notification bar - * remains visible if screenShowTitle is true while screenFullScreen is - * false, then the title bar is also displayed under the notification bar. - */ - protected boolean screenFullScreen = true; - /** - * if screenShowTitle is true while screenFullScreen is false, then the - * title bar is also displayed under the notification bar - */ - protected boolean screenShowTitle = true; /** * Splash Screen picture Resource ID. If a Splash Screen is desired, set * splashPicID to the value of the Resource ID (i.e. R.drawable.picname). If diff --git a/jme3-android/src/main/java/com/jme3/app/state/VideoRecorderAppState.java b/jme3-android/src/main/java/com/jme3/app/state/VideoRecorderAppState.java index c915164b3..a388ad612 100644 --- a/jme3-android/src/main/java/com/jme3/app/state/VideoRecorderAppState.java +++ b/jme3-android/src/main/java/com/jme3/app/state/VideoRecorderAppState.java @@ -74,7 +74,7 @@ public class VideoRecorderAppState extends AbstractAppState { public Thread newThread(Runnable r) { Thread th = new Thread(r); - th.setName("jME Video Processing Thread"); + th.setName("jME3 Video Processor"); th.setDaemon(true); return th; } diff --git a/jme3-android/src/main/java/com/jme3/audio/android/AndroidMediaPlayerAudioRenderer.java b/jme3-android/src/main/java/com/jme3/audio/android/AndroidMediaPlayerAudioRenderer.java index 7ed04658e..394cc257b 100644 --- a/jme3-android/src/main/java/com/jme3/audio/android/AndroidMediaPlayerAudioRenderer.java +++ b/jme3-android/src/main/java/com/jme3/audio/android/AndroidMediaPlayerAudioRenderer.java @@ -525,4 +525,9 @@ public class AndroidMediaPlayerAudioRenderer implements AudioRenderer, @Override public void deleteFilter(Filter filter) { } + + @Override + public float getSourcePlaybackTime(AudioSource src) { + throw new UnsupportedOperationException("Not supported yet."); + } } diff --git a/jme3-android/src/main/java/com/jme3/input/android/AndroidGestureHandler.java b/jme3-android/src/main/java/com/jme3/input/android/AndroidGestureProcessor.java similarity index 51% rename from jme3-android/src/main/java/com/jme3/input/android/AndroidGestureHandler.java rename to jme3-android/src/main/java/com/jme3/input/android/AndroidGestureProcessor.java index d233836a5..2c0367946 100644 --- a/jme3-android/src/main/java/com/jme3/input/android/AndroidGestureHandler.java +++ b/jme3-android/src/main/java/com/jme3/input/android/AndroidGestureProcessor.java @@ -35,314 +35,240 @@ package com.jme3.input.android; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.ScaleGestureDetector; -import android.view.View; -import com.jme3.input.event.InputEvent; -import com.jme3.input.event.MouseMotionEvent; import com.jme3.input.event.TouchEvent; import java.util.logging.Level; import java.util.logging.Logger; /** * AndroidGestureHandler uses Gesture type listeners to create jME TouchEvents - * for gestures. This class is designed to handle the gestures supported + * for gestures. This class is designed to handle the gestures supported * on Android rev 9 (Android 2.3). Extend this class to add functionality * added by Android after rev 9. - * + * * @author iwgeric */ -public class AndroidGestureHandler implements - GestureDetector.OnGestureListener, +public class AndroidGestureProcessor implements + GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener, ScaleGestureDetector.OnScaleGestureListener { - private static final Logger logger = Logger.getLogger(AndroidGestureHandler.class.getName()); - private AndroidInputHandler androidInput; - private GestureDetector gestureDetector; - private ScaleGestureDetector scaleDetector; + private static final Logger logger = Logger.getLogger(AndroidGestureProcessor.class.getName()); + + private AndroidTouchInput touchInput; float gestureDownX = -1f; float gestureDownY = -1f; float scaleStartX = -1f; float scaleStartY = -1f; - public AndroidGestureHandler(AndroidInputHandler androidInput) { - this.androidInput = androidInput; - } - - public void initialize() { - } - - public void destroy() { - setView(null); - } - - public void setView(View view) { - if (view != null) { - gestureDetector = new GestureDetector(view.getContext(), this); - scaleDetector = new ScaleGestureDetector(view.getContext(), this); - } else { - gestureDetector = null; - scaleDetector = null; - } - } - - public void detectGesture(MotionEvent event) { - if (gestureDetector != null && scaleDetector != null) { - gestureDetector.onTouchEvent(event); - scaleDetector.onTouchEvent(event); - } - } - - private int getPointerIndex(MotionEvent event) { - return (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) - >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; - } - - private int getPointerId(MotionEvent event) { - return event.getPointerId(getPointerIndex(event)); + public AndroidGestureProcessor(AndroidTouchInput touchInput) { + this.touchInput = touchInput; } - - private void processEvent(TouchEvent event) { - // Add the touch event - androidInput.addEvent(event); - if (androidInput.isSimulateMouse()) { - InputEvent mouseEvent = generateMouseEvent(event); - if (mouseEvent != null) { - // Add the mouse event - androidInput.addEvent(mouseEvent); - } - } - } - - // TODO: Ring Buffer for mouse events? - private InputEvent generateMouseEvent(TouchEvent event) { - InputEvent inputEvent = null; - int newX; - int newY; - int newDX; - int newDY; - if (androidInput.isMouseEventsInvertX()) { - newX = (int) (androidInput.invertX(event.getX())); - newDX = (int)event.getDeltaX() * -1; - } else { - newX = (int) event.getX(); - newDX = (int)event.getDeltaX(); - } - int wheel = (int) (event.getScaleSpan()); // might need to scale to match mouse wheel - int dWheel = (int) (event.getDeltaScaleSpan()); // might need to scale to match mouse wheel - - if (androidInput.isMouseEventsInvertY()) { - newY = (int) (androidInput.invertY(event.getY())); - newDY = (int)event.getDeltaY() * -1; - } else { - newY = (int) event.getY(); - newDY = (int)event.getDeltaY(); - } - - switch (event.getType()) { - case SCALE_MOVE: - inputEvent = new MouseMotionEvent(newX, newY, newDX, newDY, wheel, dWheel); - inputEvent.setTime(event.getTime()); - break; - } - - return inputEvent; - } - /* Events from onGestureListener */ - + + @Override public boolean onDown(MotionEvent event) { // start of all GestureListeners. Not really a gesture by itself // so we don't create an event. // However, reset the scaleInProgress here since this is the beginning // of a series of gesture events. -// logger.log(Level.INFO, "onDown pointerId: {0}, action: {1}, x: {2}, y: {3}", -// new Object[]{getPointerId(event), getAction(event), event.getX(), event.getY()}); - gestureDownX = androidInput.getJmeX(event.getX()); - gestureDownY = androidInput.invertY(androidInput.getJmeY(event.getY())); +// logger.log(Level.INFO, "onDown pointerId: {0}, action: {1}, x: {2}, y: {3}", +// new Object[]{touchInput.getPointerId(event), touchInput.getAction(event), event.getX(), event.getY()}); + gestureDownX = touchInput.getJmeX(event.getX()); + gestureDownY = touchInput.invertY(touchInput.getJmeY(event.getY())); return true; } + @Override public boolean onSingleTapUp(MotionEvent event) { // Up of single tap. May be followed by a double tap later. // use onSingleTapConfirmed instead. -// logger.log(Level.INFO, "onSingleTapUp pointerId: {0}, action: {1}, x: {2}, y: {3}", -// new Object[]{getPointerId(event), getAction(event), event.getX(), event.getY()}); +// logger.log(Level.INFO, "onSingleTapUp pointerId: {0}, action: {1}, x: {2}, y: {3}", +// new Object[]{touchInput.getPointerId(event), touchInput.getAction(event), event.getX(), event.getY()}); return true; } + @Override public void onShowPress(MotionEvent event) { -// logger.log(Level.INFO, "onShowPress pointerId: {0}, action: {1}, x: {2}, y: {3}", -// new Object[]{getPointerId(event), getAction(event), event.getX(), event.getY()}); - float jmeX = androidInput.getJmeX(event.getX()); - float jmeY = androidInput.invertY(androidInput.getJmeY(event.getY())); - TouchEvent touchEvent = androidInput.getFreeTouchEvent(); +// logger.log(Level.INFO, "onShowPress pointerId: {0}, action: {1}, x: {2}, y: {3}", +// new Object[]{touchInput.getPointerId(event), touchInput.getAction(event), event.getX(), event.getY()}); + float jmeX = touchInput.getJmeX(event.getX()); + float jmeY = touchInput.invertY(touchInput.getJmeY(event.getY())); + TouchEvent touchEvent = touchInput.getFreeTouchEvent(); touchEvent.set(TouchEvent.Type.SHOWPRESS, jmeX, jmeY, 0, 0); - touchEvent.setPointerId(getPointerId(event)); + touchEvent.setPointerId(touchInput.getPointerId(event)); touchEvent.setTime(event.getEventTime()); touchEvent.setPressure(event.getPressure()); - processEvent(touchEvent); + touchInput.addEvent(touchEvent); } + @Override public void onLongPress(MotionEvent event) { -// logger.log(Level.INFO, "onLongPress pointerId: {0}, action: {1}, x: {2}, y: {3}", -// new Object[]{getPointerId(event), getAction(event), event.getX(), event.getY()}); - float jmeX = androidInput.getJmeX(event.getX()); - float jmeY = androidInput.invertY(androidInput.getJmeY(event.getY())); - TouchEvent touchEvent = androidInput.getFreeTouchEvent(); +// logger.log(Level.INFO, "onLongPress pointerId: {0}, action: {1}, x: {2}, y: {3}", +// new Object[]{touchInput.getPointerId(event), touchInput.getAction(event), event.getX(), event.getY()}); + float jmeX = touchInput.getJmeX(event.getX()); + float jmeY = touchInput.invertY(touchInput.getJmeY(event.getY())); + TouchEvent touchEvent = touchInput.getFreeTouchEvent(); touchEvent.set(TouchEvent.Type.LONGPRESSED, jmeX, jmeY, 0, 0); - touchEvent.setPointerId(getPointerId(event)); + touchEvent.setPointerId(touchInput.getPointerId(event)); touchEvent.setTime(event.getEventTime()); touchEvent.setPressure(event.getPressure()); - processEvent(touchEvent); + touchInput.addEvent(touchEvent); } + @Override public boolean onScroll(MotionEvent startEvent, MotionEvent endEvent, float distX, float distY) { // if not scaleInProgess, send scroll events. This is to avoid sending // scroll events when one of the fingers is lifted just before the other one. // Avoids sending the scroll for that brief period of time. // Return true so that the next event doesn't accumulate the distX and distY values. - // Apparantly, both distX and distY are negative. + // Apparantly, both distX and distY are negative. // Negate distX to get the real value, but leave distY negative to compensate // for the fact that jME has y=0 at bottom where Android has y=0 at top. -// if (!scaleInProgress) { - if (!scaleDetector.isInProgress()) { -// logger.log(Level.INFO, "onScroll pointerId: {0}, startAction: {1}, startX: {2}, startY: {3}, endAction: {4}, endX: {5}, endY: {6}, dx: {7}, dy: {8}", -// new Object[]{getPointerId(startEvent), getAction(startEvent), startEvent.getX(), startEvent.getY(), getAction(endEvent), endEvent.getX(), endEvent.getY(), distX, distY}); + if (!touchInput.getScaleDetector().isInProgress()) { +// logger.log(Level.INFO, "onScroll pointerId: {0}, startAction: {1}, startX: {2}, startY: {3}, endAction: {4}, endX: {5}, endY: {6}, dx: {7}, dy: {8}", +// new Object[]{touchInput.getPointerId(startEvent), touchInput.getAction(startEvent), startEvent.getX(), startEvent.getY(), touchInput.getAction(endEvent), endEvent.getX(), endEvent.getY(), distX, distY}); - float jmeX = androidInput.getJmeX(endEvent.getX()); - float jmeY = androidInput.invertY(androidInput.getJmeY(endEvent.getY())); - TouchEvent touchEvent = androidInput.getFreeTouchEvent(); - touchEvent.set(TouchEvent.Type.SCROLL, jmeX, jmeY, androidInput.getJmeX(-distX), androidInput.getJmeY(distY)); - touchEvent.setPointerId(getPointerId(endEvent)); + float jmeX = touchInput.getJmeX(endEvent.getX()); + float jmeY = touchInput.invertY(touchInput.getJmeY(endEvent.getY())); + TouchEvent touchEvent = touchInput.getFreeTouchEvent(); + touchEvent.set(TouchEvent.Type.SCROLL, jmeX, jmeY, touchInput.getJmeX(-distX), touchInput.getJmeY(distY)); + touchEvent.setPointerId(touchInput.getPointerId(endEvent)); touchEvent.setTime(endEvent.getEventTime()); touchEvent.setPressure(endEvent.getPressure()); - processEvent(touchEvent); + touchInput.addEvent(touchEvent); } return true; } + @Override public boolean onFling(MotionEvent startEvent, MotionEvent endEvent, float velocityX, float velocityY) { // Fling happens only once at the end of the gesture (all fingers up). // Fling returns the velocity of the finger movement in pixels/sec. // Therefore, the dX and dY values are actually velocity instead of distance values // Since this does not track the movement, use the start position and velocity values. - -// logger.log(Level.INFO, "onFling pointerId: {0}, startAction: {1}, startX: {2}, startY: {3}, endAction: {4}, endX: {5}, endY: {6}, velocityX: {7}, velocityY: {8}", -// new Object[]{getPointerId(startEvent), getAction(startEvent), startEvent.getX(), startEvent.getY(), getAction(endEvent), endEvent.getX(), endEvent.getY(), velocityX, velocityY}); - float jmeX = androidInput.getJmeX(startEvent.getX()); - float jmeY = androidInput.invertY(androidInput.getJmeY(startEvent.getY())); - TouchEvent touchEvent = androidInput.getFreeTouchEvent(); +// logger.log(Level.INFO, "onFling pointerId: {0}, startAction: {1}, startX: {2}, startY: {3}, endAction: {4}, endX: {5}, endY: {6}, velocityX: {7}, velocityY: {8}", +// new Object[]{touchInput.getPointerId(startEvent), touchInput.getAction(startEvent), startEvent.getX(), startEvent.getY(), touchInput.getAction(endEvent), endEvent.getX(), endEvent.getY(), velocityX, velocityY}); + + float jmeX = touchInput.getJmeX(startEvent.getX()); + float jmeY = touchInput.invertY(touchInput.getJmeY(startEvent.getY())); + TouchEvent touchEvent = touchInput.getFreeTouchEvent(); touchEvent.set(TouchEvent.Type.FLING, jmeX, jmeY, velocityX, velocityY); - touchEvent.setPointerId(getPointerId(endEvent)); + touchEvent.setPointerId(touchInput.getPointerId(endEvent)); touchEvent.setTime(endEvent.getEventTime()); touchEvent.setPressure(endEvent.getPressure()); - processEvent(touchEvent); + touchInput.addEvent(touchEvent); return true; } /* Events from onDoubleTapListener */ - + + @Override public boolean onSingleTapConfirmed(MotionEvent event) { // Up of single tap when no double tap followed. -// logger.log(Level.INFO, "onSingleTapConfirmed pointerId: {0}, action: {1}, x: {2}, y: {3}", -// new Object[]{getPointerId(event), getAction(event), event.getX(), event.getY()}); - float jmeX = androidInput.getJmeX(event.getX()); - float jmeY = androidInput.invertY(androidInput.getJmeY(event.getY())); - TouchEvent touchEvent = androidInput.getFreeTouchEvent(); +// logger.log(Level.INFO, "onSingleTapConfirmed pointerId: {0}, action: {1}, x: {2}, y: {3}", +// new Object[]{touchInput.getPointerId(event), touchInput.getAction(event), event.getX(), event.getY()}); + float jmeX = touchInput.getJmeX(event.getX()); + float jmeY = touchInput.invertY(touchInput.getJmeY(event.getY())); + TouchEvent touchEvent = touchInput.getFreeTouchEvent(); touchEvent.set(TouchEvent.Type.TAP, jmeX, jmeY, 0, 0); - touchEvent.setPointerId(getPointerId(event)); + touchEvent.setPointerId(touchInput.getPointerId(event)); touchEvent.setTime(event.getEventTime()); touchEvent.setPressure(event.getPressure()); - processEvent(touchEvent); + touchInput.addEvent(touchEvent); return true; } + @Override public boolean onDoubleTap(MotionEvent event) { //The down motion event of the first tap of the double-tap - // We could use this event to fire off a double tap event, or use + // We could use this event to fire off a double tap event, or use // DoubleTapEvent with a check for the UP action -// logger.log(Level.INFO, "onDoubleTap pointerId: {0}, action: {1}, x: {2}, y: {3}", -// new Object[]{getPointerId(event), getAction(event), event.getX(), event.getY()}); - float jmeX = androidInput.getJmeX(event.getX()); - float jmeY = androidInput.invertY(androidInput.getJmeY(event.getY())); - TouchEvent touchEvent = androidInput.getFreeTouchEvent(); +// logger.log(Level.INFO, "onDoubleTap pointerId: {0}, action: {1}, x: {2}, y: {3}", +// new Object[]{touchInput.getPointerId(event), touchInput.getAction(event), event.getX(), event.getY()}); + float jmeX = touchInput.getJmeX(event.getX()); + float jmeY = touchInput.invertY(touchInput.getJmeY(event.getY())); + TouchEvent touchEvent = touchInput.getFreeTouchEvent(); touchEvent.set(TouchEvent.Type.DOUBLETAP, jmeX, jmeY, 0, 0); - touchEvent.setPointerId(getPointerId(event)); + touchEvent.setPointerId(touchInput.getPointerId(event)); touchEvent.setTime(event.getEventTime()); touchEvent.setPressure(event.getPressure()); - processEvent(touchEvent); + touchInput.addEvent(touchEvent); return true; } + @Override public boolean onDoubleTapEvent(MotionEvent event) { //Notified when an event within a double-tap gesture occurs, including the down, move(s), and up events. // this means it will get called multiple times for a single double tap -// logger.log(Level.INFO, "onDoubleTapEvent pointerId: {0}, action: {1}, x: {2}, y: {3}", -// new Object[]{getPointerId(event), getAction(event), event.getX(), event.getY()}); -// if (getAction(event) == MotionEvent.ACTION_UP) { -// TouchEvent touchEvent = touchEventPool.getNextFreeEvent(); -// touchEvent.set(TouchEvent.Type.DOUBLETAP, event.getX(), androidInput.invertY(event.getY()), 0, 0); -// touchEvent.setPointerId(getPointerId(event)); -// touchEvent.setTime(event.getEventTime()); -// touchEvent.setPressure(event.getPressure()); -// processEvent(touchEvent); -// } +// logger.log(Level.INFO, "onDoubleTapEvent pointerId: {0}, action: {1}, x: {2}, y: {3}", +// new Object[]{touchInput.getPointerId(event), touchInput.getAction(event), event.getX(), event.getY()}); + if (touchInput.getAction(event) == MotionEvent.ACTION_UP) { + TouchEvent touchEvent = touchInput.getFreeTouchEvent(); + touchEvent.set(TouchEvent.Type.DOUBLETAP, event.getX(), touchInput.invertY(event.getY()), 0, 0); + touchEvent.setPointerId(touchInput.getPointerId(event)); + touchEvent.setTime(event.getEventTime()); + touchEvent.setPressure(event.getPressure()); + touchInput.addEvent(touchEvent); + } return true; } /* Events from ScaleGestureDetector */ - + + @Override public boolean onScaleBegin(ScaleGestureDetector scaleGestureDetector) { // Scale uses a focusX and focusY instead of x and y. Focus is the middle // of the fingers. Therefore, use the x and y values from the Down event // so that the x and y values don't jump to the middle position. // return true or all gestures for this beginning event will be discarded - logger.log(Level.INFO, "onScaleBegin"); +// logger.log(Level.INFO, "onScaleBegin"); scaleStartX = gestureDownX; scaleStartY = gestureDownY; - TouchEvent touchEvent = androidInput.getFreeTouchEvent(); + TouchEvent touchEvent = touchInput.getFreeTouchEvent(); touchEvent.set(TouchEvent.Type.SCALE_START, scaleStartX, scaleStartY, 0f, 0f); touchEvent.setPointerId(0); touchEvent.setTime(scaleGestureDetector.getEventTime()); touchEvent.setScaleSpan(scaleGestureDetector.getCurrentSpan()); touchEvent.setDeltaScaleSpan(0f); touchEvent.setScaleFactor(scaleGestureDetector.getScaleFactor()); - touchEvent.setScaleSpanInProgress(scaleDetector.isInProgress()); - processEvent(touchEvent); - + touchEvent.setScaleSpanInProgress(touchInput.getScaleDetector().isInProgress()); + touchInput.addEvent(touchEvent); + return true; } + @Override public boolean onScale(ScaleGestureDetector scaleGestureDetector) { // return true or all gestures for this event will be accumulated - logger.log(Level.INFO, "onScale"); +// logger.log(Level.INFO, "onScale"); scaleStartX = gestureDownX; scaleStartY = gestureDownY; - TouchEvent touchEvent = androidInput.getFreeTouchEvent(); + TouchEvent touchEvent = touchInput.getFreeTouchEvent(); touchEvent.set(TouchEvent.Type.SCALE_MOVE, scaleStartX, scaleStartY, 0f, 0f); touchEvent.setPointerId(0); touchEvent.setTime(scaleGestureDetector.getEventTime()); touchEvent.setScaleSpan(scaleGestureDetector.getCurrentSpan()); touchEvent.setDeltaScaleSpan(scaleGestureDetector.getCurrentSpan() - scaleGestureDetector.getPreviousSpan()); touchEvent.setScaleFactor(scaleGestureDetector.getScaleFactor()); - touchEvent.setScaleSpanInProgress(scaleDetector.isInProgress()); - processEvent(touchEvent); + touchEvent.setScaleSpanInProgress(touchInput.getScaleDetector().isInProgress()); + touchInput.addEvent(touchEvent); return true; } + @Override public void onScaleEnd(ScaleGestureDetector scaleGestureDetector) { - logger.log(Level.INFO, "onScaleEnd"); +// logger.log(Level.INFO, "onScaleEnd"); scaleStartX = gestureDownX; scaleStartY = gestureDownY; - TouchEvent touchEvent = androidInput.getFreeTouchEvent(); + TouchEvent touchEvent = touchInput.getFreeTouchEvent(); touchEvent.set(TouchEvent.Type.SCALE_END, scaleStartX, scaleStartY, 0f, 0f); touchEvent.setPointerId(0); touchEvent.setTime(scaleGestureDetector.getEventTime()); touchEvent.setScaleSpan(scaleGestureDetector.getCurrentSpan()); touchEvent.setDeltaScaleSpan(scaleGestureDetector.getCurrentSpan() - scaleGestureDetector.getPreviousSpan()); touchEvent.setScaleFactor(scaleGestureDetector.getScaleFactor()); - touchEvent.setScaleSpanInProgress(scaleDetector.isInProgress()); - processEvent(touchEvent); + touchEvent.setScaleSpanInProgress(touchInput.getScaleDetector().isInProgress()); + touchInput.addEvent(touchEvent); } } diff --git a/jme3-android/src/main/java/com/jme3/input/android/AndroidInput.java b/jme3-android/src/main/java/com/jme3/input/android/AndroidInput.java deleted file mode 100644 index 02fef6b0f..000000000 --- a/jme3-android/src/main/java/com/jme3/input/android/AndroidInput.java +++ /dev/null @@ -1,686 +0,0 @@ -package com.jme3.input.android; - -import android.view.*; -import com.jme3.input.KeyInput; -import com.jme3.input.RawInputListener; -import com.jme3.input.TouchInput; -import com.jme3.input.event.MouseButtonEvent; -import com.jme3.input.event.MouseMotionEvent; -import com.jme3.input.event.TouchEvent; -import com.jme3.input.event.TouchEvent.Type; -import com.jme3.math.Vector2f; -import com.jme3.system.AppSettings; -import com.jme3.util.RingBuffer; -import java.util.HashMap; -import java.util.logging.Logger; - -/** - * AndroidInput is one of the main components that connect jme with android. Is derived from GLSurfaceView and handles all Inputs - * @author larynx - * - */ -public class AndroidInput implements - TouchInput, - View.OnTouchListener, - View.OnKeyListener, - GestureDetector.OnGestureListener, - GestureDetector.OnDoubleTapListener, - ScaleGestureDetector.OnScaleGestureListener { - - final private static int MAX_EVENTS = 1024; - // Custom settings - public boolean mouseEventsEnabled = true; - public boolean mouseEventsInvertX = false; - public boolean mouseEventsInvertY = false; - public boolean keyboardEventsEnabled = false; - public boolean dontSendHistory = false; - // Used to transfer events from android thread to GLThread - final private RingBuffer eventQueue = new RingBuffer(MAX_EVENTS); - final private RingBuffer eventPoolUnConsumed = new RingBuffer(MAX_EVENTS); - final private RingBuffer eventPool = new RingBuffer(MAX_EVENTS); - final private HashMap lastPositions = new HashMap(); - // Internal - private View view; - private ScaleGestureDetector scaledetector; - private boolean scaleInProgress = false; - private GestureDetector detector; - private int lastX; - private int lastY; - private final static Logger logger = Logger.getLogger(AndroidInput.class.getName()); - private boolean isInitialized = false; - private RawInputListener listener = null; - private static final int[] ANDROID_TO_JME = { - 0x0, // unknown - 0x0, // key code soft left - 0x0, // key code soft right - KeyInput.KEY_HOME, - KeyInput.KEY_ESCAPE, // key back - 0x0, // key call - 0x0, // key endcall - KeyInput.KEY_0, - KeyInput.KEY_1, - KeyInput.KEY_2, - KeyInput.KEY_3, - KeyInput.KEY_4, - KeyInput.KEY_5, - KeyInput.KEY_6, - KeyInput.KEY_7, - KeyInput.KEY_8, - KeyInput.KEY_9, - KeyInput.KEY_MULTIPLY, - 0x0, // key pound - KeyInput.KEY_UP, - KeyInput.KEY_DOWN, - KeyInput.KEY_LEFT, - KeyInput.KEY_RIGHT, - KeyInput.KEY_RETURN, // dpad center - 0x0, // volume up - 0x0, // volume down - KeyInput.KEY_POWER, // power (?) - 0x0, // camera - 0x0, // clear - KeyInput.KEY_A, - KeyInput.KEY_B, - KeyInput.KEY_C, - KeyInput.KEY_D, - KeyInput.KEY_E, - KeyInput.KEY_F, - KeyInput.KEY_G, - KeyInput.KEY_H, - KeyInput.KEY_I, - KeyInput.KEY_J, - KeyInput.KEY_K, - KeyInput.KEY_L, - KeyInput.KEY_M, - KeyInput.KEY_N, - KeyInput.KEY_O, - KeyInput.KEY_P, - KeyInput.KEY_Q, - KeyInput.KEY_R, - KeyInput.KEY_S, - KeyInput.KEY_T, - KeyInput.KEY_U, - KeyInput.KEY_V, - KeyInput.KEY_W, - KeyInput.KEY_X, - KeyInput.KEY_Y, - KeyInput.KEY_Z, - KeyInput.KEY_COMMA, - KeyInput.KEY_PERIOD, - KeyInput.KEY_LMENU, - KeyInput.KEY_RMENU, - KeyInput.KEY_LSHIFT, - KeyInput.KEY_RSHIFT, - // 0x0, // fn - // 0x0, // cap (?) - - KeyInput.KEY_TAB, - KeyInput.KEY_SPACE, - 0x0, // sym (?) symbol - 0x0, // explorer - 0x0, // envelope - KeyInput.KEY_RETURN, // newline/enter - KeyInput.KEY_DELETE, - KeyInput.KEY_GRAVE, - KeyInput.KEY_MINUS, - KeyInput.KEY_EQUALS, - KeyInput.KEY_LBRACKET, - KeyInput.KEY_RBRACKET, - KeyInput.KEY_BACKSLASH, - KeyInput.KEY_SEMICOLON, - KeyInput.KEY_APOSTROPHE, - KeyInput.KEY_SLASH, - KeyInput.KEY_AT, // at (@) - KeyInput.KEY_NUMLOCK, //0x0, // num - 0x0, //headset hook - 0x0, //focus - KeyInput.KEY_ADD, - KeyInput.KEY_LMETA, //menu - 0x0,//notification - 0x0,//search - 0x0,//media play/pause - 0x0,//media stop - 0x0,//media next - 0x0,//media previous - 0x0,//media rewind - 0x0,//media fastforward - 0x0,//mute - }; - - public AndroidInput() { - } - - public void setView(View view) { - this.view = view; - if (view != null) { - detector = new GestureDetector(null, this, null, false); - scaledetector = new ScaleGestureDetector(view.getContext(), this); - view.setOnTouchListener(this); - view.setOnKeyListener(this); - } - } - - private TouchEvent getNextFreeTouchEvent() { - return getNextFreeTouchEvent(false); - } - - /** - * Fetches a touch event from the reuse pool - * @param wait if true waits for a reusable event to get available/released - * by an other thread, if false returns a new one if needed. - * - * @return a usable TouchEvent - */ - private TouchEvent getNextFreeTouchEvent(boolean wait) { - TouchEvent evt = null; - synchronized (eventPoolUnConsumed) { - int size = eventPoolUnConsumed.size(); - while (size > 0) { - evt = eventPoolUnConsumed.pop(); - if (!evt.isConsumed()) { - eventPoolUnConsumed.push(evt); - evt = null; - } else { - break; - } - size--; - } - } - - if (evt == null) { - if (eventPool.isEmpty() && wait) { - logger.warning("eventPool buffer underrun"); - boolean isEmpty; - do { - synchronized (eventPool) { - isEmpty = eventPool.isEmpty(); - } - try { - Thread.sleep(50); - } catch (InterruptedException e) { - } - } while (isEmpty); - synchronized (eventPool) { - evt = eventPool.pop(); - } - } else if (eventPool.isEmpty()) { - evt = new TouchEvent(); - logger.warning("eventPool buffer underrun"); - } else { - synchronized (eventPool) { - evt = eventPool.pop(); - } - } - } - return evt; - } - - /** - * onTouch gets called from android thread on touchpad events - */ - public boolean onTouch(View view, MotionEvent event) { - if (view != this.view) { - return false; - } - boolean bWasHandled = false; - TouchEvent touch; - // System.out.println("native : " + event.getAction()); - int action = event.getAction() & MotionEvent.ACTION_MASK; - int pointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) - >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; - int pointerId = event.getPointerId(pointerIndex); - Vector2f lastPos = lastPositions.get(pointerId); - - // final int historySize = event.getHistorySize(); - //final int pointerCount = event.getPointerCount(); - switch (action) { - case MotionEvent.ACTION_POINTER_DOWN: - case MotionEvent.ACTION_DOWN: - touch = getNextFreeTouchEvent(); - touch.set(Type.DOWN, event.getX(pointerIndex), view.getHeight() - event.getY(pointerIndex), 0, 0); - touch.setPointerId(pointerId); - touch.setTime(event.getEventTime()); - touch.setPressure(event.getPressure(pointerIndex)); - processEvent(touch); - - lastPos = new Vector2f(event.getX(pointerIndex), view.getHeight() - event.getY(pointerIndex)); - lastPositions.put(pointerId, lastPos); - - bWasHandled = true; - break; - case MotionEvent.ACTION_POINTER_UP: - case MotionEvent.ACTION_CANCEL: - case MotionEvent.ACTION_UP: - touch = getNextFreeTouchEvent(); - touch.set(Type.UP, event.getX(pointerIndex), view.getHeight() - event.getY(pointerIndex), 0, 0); - touch.setPointerId(pointerId); - touch.setTime(event.getEventTime()); - touch.setPressure(event.getPressure(pointerIndex)); - processEvent(touch); - lastPositions.remove(pointerId); - - bWasHandled = true; - break; - case MotionEvent.ACTION_MOVE: - // Convert all pointers into events - for (int p = 0; p < event.getPointerCount(); p++) { - lastPos = lastPositions.get(event.getPointerId(p)); - if (lastPos == null) { - lastPos = new Vector2f(event.getX(p), view.getHeight() - event.getY(p)); - lastPositions.put(event.getPointerId(p), lastPos); - } - - float dX = event.getX(p) - lastPos.x; - float dY = view.getHeight() - event.getY(p) - lastPos.y; - if (dX != 0 || dY != 0) { - touch = getNextFreeTouchEvent(); - touch.set(Type.MOVE, event.getX(p), view.getHeight() - event.getY(p), dX, dY); - touch.setPointerId(event.getPointerId(p)); - touch.setTime(event.getEventTime()); - touch.setPressure(event.getPressure(p)); - touch.setScaleSpanInProgress(scaleInProgress); - processEvent(touch); - lastPos.set(event.getX(p), view.getHeight() - event.getY(p)); - } - } - bWasHandled = true; - break; - case MotionEvent.ACTION_OUTSIDE: - break; - - } - - // Try to detect gestures - this.detector.onTouchEvent(event); - this.scaledetector.onTouchEvent(event); - - return bWasHandled; - } - - /** - * onKey gets called from android thread on key events - */ - public boolean onKey(View view, int keyCode, KeyEvent event) { - if (view != this.view) { - return false; - } - - if (event.getAction() == KeyEvent.ACTION_DOWN) { - TouchEvent evt; - evt = getNextFreeTouchEvent(); - evt.set(TouchEvent.Type.KEY_DOWN); - evt.setKeyCode(keyCode); - evt.setCharacters(event.getCharacters()); - evt.setTime(event.getEventTime()); - - // Send the event - processEvent(evt); - - // Handle all keys ourself except Volume Up/Down - if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP) || (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) { - return false; - } else { - return true; - } - } else if (event.getAction() == KeyEvent.ACTION_UP) { - TouchEvent evt; - evt = getNextFreeTouchEvent(); - evt.set(TouchEvent.Type.KEY_UP); - evt.setKeyCode(keyCode); - evt.setCharacters(event.getCharacters()); - evt.setTime(event.getEventTime()); - - // Send the event - processEvent(evt); - - // Handle all keys ourself except Volume Up/Down - if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP) || (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) { - return false; - } else { - return true; - } - } else { - return false; - } - } - - public void loadSettings(AppSettings settings) { - mouseEventsEnabled = settings.isEmulateMouse(); - mouseEventsInvertX = settings.isEmulateMouseFlipX(); - mouseEventsInvertY = settings.isEmulateMouseFlipY(); - } - - // ----------------------------------------- - // JME3 Input interface - @Override - public void initialize() { - TouchEvent item; - for (int i = 0; i < MAX_EVENTS; i++) { - item = new TouchEvent(); - eventPool.push(item); - } - isInitialized = true; - } - - @Override - public void destroy() { - isInitialized = false; - - // Clean up queues - while (!eventPool.isEmpty()) { - eventPool.pop(); - } - while (!eventQueue.isEmpty()) { - eventQueue.pop(); - } - - - this.view = null; - } - - @Override - public boolean isInitialized() { - return isInitialized; - } - - @Override - public void setInputListener(RawInputListener listener) { - this.listener = listener; - } - - @Override - public long getInputTimeNanos() { - return System.nanoTime(); - } - // ----------------------------------------- - - private void processEvent(TouchEvent event) { - synchronized (eventQueue) { - //Discarding events when the ring buffer is full to avoid buffer overflow. - if(eventQueue.size()< MAX_EVENTS){ - eventQueue.push(event); - } - - } - } - - // --------------- INSIDE GLThread --------------- - @Override - public void update() { - generateEvents(); - } - - private void generateEvents() { - if (listener != null) { - TouchEvent event; - MouseButtonEvent btn; - MouseMotionEvent mot; - int newX; - int newY; - - while (!eventQueue.isEmpty()) { - synchronized (eventQueue) { - event = eventQueue.pop(); - } - if (event != null) { - listener.onTouchEvent(event); - - if (mouseEventsEnabled) { - if (mouseEventsInvertX) { - newX = view.getWidth() - (int) event.getX(); - } else { - newX = (int) event.getX(); - } - - if (mouseEventsInvertY) { - newY = view.getHeight() - (int) event.getY(); - } else { - newY = (int) event.getY(); - } - - switch (event.getType()) { - case DOWN: - // Handle mouse down event - btn = new MouseButtonEvent(0, true, newX, newY); - btn.setTime(event.getTime()); - listener.onMouseButtonEvent(btn); - // Store current pos - lastX = -1; - lastY = -1; - break; - - case UP: - // Handle mouse up event - btn = new MouseButtonEvent(0, false, newX, newY); - btn.setTime(event.getTime()); - listener.onMouseButtonEvent(btn); - // Store current pos - lastX = -1; - lastY = -1; - break; - - case SCALE_MOVE: - if (lastX != -1 && lastY != -1) { - newX = lastX; - newY = lastY; - } - int wheel = (int) (event.getScaleSpan() / 4f); // scale to match mouse wheel - int dwheel = (int) (event.getDeltaScaleSpan() / 4f); // scale to match mouse wheel - mot = new MouseMotionEvent(newX, newX, 0, 0, wheel, dwheel); - mot.setTime(event.getTime()); - listener.onMouseMotionEvent(mot); - lastX = newX; - lastY = newY; - - break; - - case MOVE: - if (event.isScaleSpanInProgress()) { - break; - } - - int dx; - int dy; - if (lastX != -1) { - dx = newX - lastX; - dy = newY - lastY; - } else { - dx = 0; - dy = 0; - } - - mot = new MouseMotionEvent(newX, newY, dx, dy, (int)event.getScaleSpan(), (int)event.getDeltaScaleSpan()); - mot.setTime(event.getTime()); - listener.onMouseMotionEvent(mot); - lastX = newX; - lastY = newY; - - break; - } - } - } - - if (event.isConsumed() == false) { - synchronized (eventPoolUnConsumed) { - eventPoolUnConsumed.push(event); - } - - } else { - synchronized (eventPool) { - eventPool.push(event); - } - } - } - - } - } - // --------------- ENDOF INSIDE GLThread --------------- - - // --------------- Gesture detected callback events --------------- - public boolean onDown(MotionEvent event) { - return false; - } - - public void onLongPress(MotionEvent event) { - TouchEvent touch = getNextFreeTouchEvent(); - touch.set(Type.LONGPRESSED, event.getX(), view.getHeight() - event.getY(), 0f, 0f); - touch.setPointerId(0); - touch.setTime(event.getEventTime()); - processEvent(touch); - } - - public boolean onFling(MotionEvent event, MotionEvent event2, float vx, float vy) { - TouchEvent touch = getNextFreeTouchEvent(); - touch.set(Type.FLING, event.getX(), view.getHeight() - event.getY(), vx, vy); - touch.setPointerId(0); - touch.setTime(event.getEventTime()); - processEvent(touch); - - return true; - } - - public boolean onSingleTapConfirmed(MotionEvent event) { - //Nothing to do here the tap has already been detected. - return false; - } - - public boolean onDoubleTap(MotionEvent event) { - TouchEvent touch = getNextFreeTouchEvent(); - touch.set(Type.DOUBLETAP, event.getX(), view.getHeight() - event.getY(), 0f, 0f); - touch.setPointerId(0); - touch.setTime(event.getEventTime()); - processEvent(touch); - return true; - } - - public boolean onDoubleTapEvent(MotionEvent event) { - return false; - } - - public boolean onScaleBegin(ScaleGestureDetector scaleGestureDetector) { - scaleInProgress = true; - TouchEvent touch = getNextFreeTouchEvent(); - touch.set(Type.SCALE_START, scaleGestureDetector.getFocusX(), scaleGestureDetector.getFocusY(), 0f, 0f); - touch.setPointerId(0); - touch.setTime(scaleGestureDetector.getEventTime()); - touch.setScaleSpan(scaleGestureDetector.getCurrentSpan()); - touch.setDeltaScaleSpan(scaleGestureDetector.getCurrentSpan() - scaleGestureDetector.getPreviousSpan()); - touch.setScaleFactor(scaleGestureDetector.getScaleFactor()); - touch.setScaleSpanInProgress(scaleInProgress); - processEvent(touch); - // System.out.println("scaleBegin"); - - return true; - } - - public boolean onScale(ScaleGestureDetector scaleGestureDetector) { - TouchEvent touch = getNextFreeTouchEvent(); - touch.set(Type.SCALE_MOVE, scaleGestureDetector.getFocusX(), view.getHeight() - scaleGestureDetector.getFocusY(), 0f, 0f); - touch.setPointerId(0); - touch.setTime(scaleGestureDetector.getEventTime()); - touch.setScaleSpan(scaleGestureDetector.getCurrentSpan()); - touch.setDeltaScaleSpan(scaleGestureDetector.getCurrentSpan() - scaleGestureDetector.getPreviousSpan()); - touch.setScaleFactor(scaleGestureDetector.getScaleFactor()); - touch.setScaleSpanInProgress(scaleInProgress); - processEvent(touch); - // System.out.println("scale"); - - return false; - } - - public void onScaleEnd(ScaleGestureDetector scaleGestureDetector) { - scaleInProgress = false; - TouchEvent touch = getNextFreeTouchEvent(); - touch.set(Type.SCALE_END, scaleGestureDetector.getFocusX(), view.getHeight() - scaleGestureDetector.getFocusY(), 0f, 0f); - touch.setPointerId(0); - touch.setTime(scaleGestureDetector.getEventTime()); - touch.setScaleSpan(scaleGestureDetector.getCurrentSpan()); - touch.setDeltaScaleSpan(scaleGestureDetector.getCurrentSpan() - scaleGestureDetector.getPreviousSpan()); - touch.setScaleFactor(scaleGestureDetector.getScaleFactor()); - touch.setScaleSpanInProgress(scaleInProgress); - processEvent(touch); - } - - public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { - TouchEvent touch = getNextFreeTouchEvent(); - touch.set(Type.SCROLL, e1.getX(), view.getHeight() - e1.getY(), distanceX, distanceY * (-1)); - touch.setPointerId(0); - touch.setTime(e1.getEventTime()); - processEvent(touch); - //System.out.println("scroll " + e1.getPointerCount()); - return false; - } - - public void onShowPress(MotionEvent event) { - TouchEvent touch = getNextFreeTouchEvent(); - touch.set(Type.SHOWPRESS, event.getX(), view.getHeight() - event.getY(), 0f, 0f); - touch.setPointerId(0); - touch.setTime(event.getEventTime()); - processEvent(touch); - } - - public boolean onSingleTapUp(MotionEvent event) { - TouchEvent touch = getNextFreeTouchEvent(); - touch.set(Type.TAP, event.getX(), view.getHeight() - event.getY(), 0f, 0f); - touch.setPointerId(0); - touch.setTime(event.getEventTime()); - processEvent(touch); - return true; - } - - @Override - public void setSimulateKeyboard(boolean simulate) { - keyboardEventsEnabled = simulate; - } - - @Override - public void setOmitHistoricEvents(boolean dontSendHistory) { - this.dontSendHistory = dontSendHistory; - } - - /** - * @deprecated Use {@link #getSimulateMouse()}; - */ - @Deprecated - public boolean isMouseEventsEnabled() { - return mouseEventsEnabled; - } - - @Deprecated - public void setMouseEventsEnabled(boolean mouseEventsEnabled) { - this.mouseEventsEnabled = mouseEventsEnabled; - } - - public boolean isMouseEventsInvertY() { - return mouseEventsInvertY; - } - - public void setMouseEventsInvertY(boolean mouseEventsInvertY) { - this.mouseEventsInvertY = mouseEventsInvertY; - } - - public boolean isMouseEventsInvertX() { - return mouseEventsInvertX; - } - - public void setMouseEventsInvertX(boolean mouseEventsInvertX) { - this.mouseEventsInvertX = mouseEventsInvertX; - } - - public void setSimulateMouse(boolean simulate) { - mouseEventsEnabled = simulate; - } - - public boolean getSimulateMouse() { - return isSimulateMouse(); - } - - public boolean isSimulateMouse() { - return mouseEventsEnabled; - } - - public boolean isSimulateKeyboard() { - return keyboardEventsEnabled; - } - -} diff --git a/jme3-android/src/main/java/com/jme3/input/android/AndroidInputHandler.java b/jme3-android/src/main/java/com/jme3/input/android/AndroidInputHandler.java index 592baecaf..9f4729c66 100644 --- a/jme3-android/src/main/java/com/jme3/input/android/AndroidInputHandler.java +++ b/jme3-android/src/main/java/com/jme3/input/android/AndroidInputHandler.java @@ -1,265 +1,238 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package com.jme3.input.android; - -import android.opengl.GLSurfaceView; -import android.os.Build; -import android.view.View; -import com.jme3.input.RawInputListener; -import com.jme3.input.TouchInput; -import com.jme3.input.event.InputEvent; -import com.jme3.input.event.KeyInputEvent; -import com.jme3.input.event.MouseButtonEvent; -import com.jme3.input.event.MouseMotionEvent; -import com.jme3.input.event.TouchEvent; -import com.jme3.system.AppSettings; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * AndroidInput is the main class that connects the Android system - * inputs to jME. It serves as the manager that gathers inputs from the various - * Android input methods and provides them to jME's InputManager. - * - * @author iwgeric - */ -public class AndroidInputHandler implements TouchInput { - private static final Logger logger = Logger.getLogger(AndroidInputHandler.class.getName()); - - // Custom settings - private boolean mouseEventsEnabled = true; - private boolean mouseEventsInvertX = false; - private boolean mouseEventsInvertY = false; - private boolean keyboardEventsEnabled = false; - private boolean joystickEventsEnabled = false; - private boolean dontSendHistory = false; - - - // Internal - private GLSurfaceView view; - private AndroidTouchHandler touchHandler; - private AndroidKeyHandler keyHandler; - private AndroidGestureHandler gestureHandler; - private boolean initialized = false; - private RawInputListener listener = null; - private ConcurrentLinkedQueue inputEventQueue = new ConcurrentLinkedQueue(); - private final static int MAX_TOUCH_EVENTS = 1024; - private final TouchEventPool touchEventPool = new TouchEventPool(MAX_TOUCH_EVENTS); - private float scaleX = 1f; - private float scaleY = 1f; - - - public AndroidInputHandler() { - int buildVersion = Build.VERSION.SDK_INT; - logger.log(Level.INFO, "Android Build Version: {0}", buildVersion); - if (buildVersion >= 14) { - // add support for onHover and GenericMotionEvent (ie. gamepads) - gestureHandler = new AndroidGestureHandler(this); - touchHandler = new AndroidTouchHandler14(this, gestureHandler); - keyHandler = new AndroidKeyHandler(this); - } else if (buildVersion >= 8){ - gestureHandler = new AndroidGestureHandler(this); - touchHandler = new AndroidTouchHandler(this, gestureHandler); - keyHandler = new AndroidKeyHandler(this); - } - } - - public AndroidInputHandler(AndroidTouchHandler touchInput, - AndroidKeyHandler keyInput, AndroidGestureHandler gestureHandler) { - this.touchHandler = touchInput; - this.keyHandler = keyInput; - this.gestureHandler = gestureHandler; - } - - public void setView(View view) { - if (touchHandler != null) { - touchHandler.setView(view); - } - if (keyHandler != null) { - keyHandler.setView(view); - } - if (gestureHandler != null) { - gestureHandler.setView(view); - } - this.view = (GLSurfaceView)view; - } - - public View getView() { - return view; - } - - public float invertX(float origX) { - return getJmeX(view.getWidth()) - origX; - } - - public float invertY(float origY) { - return getJmeY(view.getHeight()) - origY; - } - - public float getJmeX(float origX) { - return origX * scaleX; - } - - public float getJmeY(float origY) { - return origY * scaleY; - } - - public void loadSettings(AppSettings settings) { - keyboardEventsEnabled = settings.isEmulateKeyboard(); - mouseEventsEnabled = settings.isEmulateMouse(); - mouseEventsInvertX = settings.isEmulateMouseFlipX(); - mouseEventsInvertY = settings.isEmulateMouseFlipY(); - joystickEventsEnabled = settings.useJoysticks(); - - // view width and height are 0 until the view is displayed on the screen - if (view.getWidth() != 0 && view.getHeight() != 0) { - scaleX = (float)settings.getWidth() / (float)view.getWidth(); - scaleY = (float)settings.getHeight() / (float)view.getHeight(); - } - logger.log(Level.FINE, "Setting input scaling, scaleX: {0}, scaleY: {1}", - new Object[]{scaleX, scaleY}); - - } - - // ----------------------------------------- - // JME3 Input interface - @Override - public void initialize() { - touchEventPool.initialize(); - if (touchHandler != null) { - touchHandler.initialize(); - } - if (keyHandler != null) { - keyHandler.initialize(); - } - if (gestureHandler != null) { - gestureHandler.initialize(); - } - - initialized = true; - } - - @Override - public void destroy() { - initialized = false; - - touchEventPool.destroy(); - if (touchHandler != null) { - touchHandler.destroy(); - } - if (keyHandler != null) { - keyHandler.destroy(); - } - if (gestureHandler != null) { - gestureHandler.destroy(); - } - - setView(null); - } - - @Override - public boolean isInitialized() { - return initialized; - } - - @Override - public void setInputListener(RawInputListener listener) { - this.listener = listener; - } - - @Override - public long getInputTimeNanos() { - return System.nanoTime(); - } - - public void update() { - if (listener != null) { - InputEvent inputEvent; - - while ((inputEvent = inputEventQueue.poll()) != null) { - if (inputEvent instanceof TouchEvent) { - listener.onTouchEvent((TouchEvent)inputEvent); - } else if (inputEvent instanceof MouseButtonEvent) { - listener.onMouseButtonEvent((MouseButtonEvent)inputEvent); - } else if (inputEvent instanceof MouseMotionEvent) { - listener.onMouseMotionEvent((MouseMotionEvent)inputEvent); - } else if (inputEvent instanceof KeyInputEvent) { - listener.onKeyEvent((KeyInputEvent)inputEvent); - } - } - } - } - - // ----------------------------------------- - - public TouchEvent getFreeTouchEvent() { - return touchEventPool.getNextFreeEvent(); - } - - public void addEvent(InputEvent event) { - inputEventQueue.add(event); - if (event instanceof TouchEvent) { - touchEventPool.storeEvent((TouchEvent)event); - } - } - - public void setSimulateMouse(boolean simulate) { - this.mouseEventsEnabled = simulate; - } - - public boolean isSimulateMouse() { - return mouseEventsEnabled; - } - - public boolean isMouseEventsInvertX() { - return mouseEventsInvertX; - } - - public boolean isMouseEventsInvertY() { - return mouseEventsInvertY; - } - - public void setSimulateKeyboard(boolean simulate) { - this.keyboardEventsEnabled = simulate; - } - - public boolean isSimulateKeyboard() { - return keyboardEventsEnabled; - } - - public void setOmitHistoricEvents(boolean dontSendHistory) { - this.dontSendHistory = dontSendHistory; - } - -} +/* + * Copyright (c) 2009-2012 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jme3.input.android; + +import android.opengl.GLSurfaceView; +import android.view.GestureDetector; +import android.view.InputDevice; +import android.view.KeyEvent; +import android.view.MotionEvent; +import android.view.ScaleGestureDetector; +import android.view.View; +import com.jme3.input.JoyInput; +import com.jme3.input.TouchInput; +import com.jme3.system.AppSettings; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * AndroidInput is the main class that connects the Android system + * inputs to jME. It receives the inputs from the Android View and passes them + * to the appropriate classes based on the source of the input.
+ * This class is to be extended when new functionality is released in Android. + * + * @author iwgeric + */ +public class AndroidInputHandler implements View.OnTouchListener, + View.OnKeyListener { + + private static final Logger logger = Logger.getLogger(AndroidInputHandler.class.getName()); + + protected GLSurfaceView view; + protected AndroidTouchInput touchInput; + protected AndroidJoyInput joyInput; + + + public AndroidInputHandler() { + touchInput = new AndroidTouchInput(this); + joyInput = new AndroidJoyInput(this); + } + + public void setView(View view) { + if (this.view != null && view != null && this.view.equals(view)) { + return; + } + + if (this.view != null) { + removeListeners(this.view); + } + + this.view = (GLSurfaceView)view; + + if (this.view != null) { + addListeners(this.view); + } + + joyInput.setView((GLSurfaceView)view); + } + + public View getView() { + return view; + } + + protected void removeListeners(GLSurfaceView view) { + view.setOnTouchListener(null); + view.setOnKeyListener(null); + touchInput.setGestureDetector(null); + touchInput.setScaleDetector(null); + } + + protected void addListeners(GLSurfaceView view) { + view.setOnTouchListener(this); + view.setOnKeyListener(this); + AndroidGestureProcessor gestureHandler = new AndroidGestureProcessor(touchInput); + touchInput.setGestureDetector(new GestureDetector( + view.getContext(), gestureHandler)); + touchInput.setScaleDetector(new ScaleGestureDetector( + view.getContext(), gestureHandler)); + } + + public void loadSettings(AppSettings settings) { + touchInput.loadSettings(settings); + } + + public TouchInput getTouchInput() { + return touchInput; + } + + public JoyInput getJoyInput() { + return joyInput; + } + + /* + * Android input events include the source from which the input came from. + * We must look at the source of the input event to determine which type + * of jME input it belongs to. + * If the input is from a gamepad or joystick source, the event is sent + * to the JoyInput class to convert the event into jME joystick events. + *
+ * If the input is from a touchscreen source, the event is sent to the + * TouchProcessor to convert the event into touch events. + * The TouchProcessor also converts the events into Mouse and Key events + * if AppSettings is set to simulate Mouse or Keyboard events. + * + * Android reports the source as a bitmask as shown below.
+ * + * InputDevice Sources + * 0000 0000 0000 0000 0000 0000 0000 0000 - 32 bit bitmask + * + * 0000 0000 0000 0000 0000 0000 1111 1111 - SOURCE_CLASS_MASK (0x000000ff) + * 0000 0000 0000 0000 0000 0000 0000 0000 - SOURCE_CLASS_NONE (0x00000000) + * 0000 0000 0000 0000 0000 0000 0000 0001 - SOURCE_CLASS_BUTTON (0x00000001) + * 0000 0000 0000 0000 0000 0000 0000 0010 - SOURCE_CLASS_POINTER (0x00000002) + * 0000 0000 0000 0000 0000 0000 0000 0100 - SOURCE_CLASS_TRACKBALL (0x00000004) + * 0000 0000 0000 0000 0000 0000 0000 1000 - SOURCE_CLASS_POSITION (0x00000008) + * 0000 0000 0000 0000 0000 0000 0001 0000 - SOURCE_CLASS_JOYSTICK (0x00000010) + * + * 1111 1111 1111 1111 1111 1111 0000 0000 - Source_Any (0xffffff00) + * 0000 0000 0000 0000 0000 0000 0000 0000 - SOURCE_UNKNOWN (0x00000000) + * 0000 0000 0000 0000 0000 0001 0000 0001 - SOURCE_KEYBOARD (0x00000101) + * 0000 0000 0000 0000 0000 0010 0000 0001 - SOURCE_DPAD (0x00000201) + * 0000 0000 0000 0000 0000 0100 0000 0001 - SOURCE_GAMEPAD (0x00000401) + * 0000 0000 0000 0000 0001 0000 0000 0010 - SOURCE_TOUCHSCREEN (0x00001002) + * 0000 0000 0000 0000 0010 0000 0000 0010 - SOURCE_MOUSE (0x00002002) + * 0000 0000 0000 0000 0100 0000 0000 0010 - SOURCE_STYLUS (0x00004002) + * 0000 0000 0000 0001 0000 0000 0000 0100 - SOURCE_TRACKBALL (0x00010004) + * 0000 0000 0001 0000 0000 0000 0000 1000 - SOURCE_TOUCHPAD (0x00100008) + * 0000 0000 0010 0000 0000 0000 0000 0000 - SOURCE_TOUCH_NAVIGATION (0x00200000) + * 0000 0001 0000 0000 0000 0000 0001 0000 - SOURCE_JOYSTICK (0x01000010) + * 0000 0010 0000 0000 0000 0000 0000 0001 - SOURCE_HDMI (0x02000001) + * + * Example values reported by Android for Source + * 4,098 = 0x00001002 = + * 0000 0000 0000 0000 0001 0000 0000 0010 - SOURCE_CLASS_POINTER + * SOURCE_TOUCHSCREEN + * 1,281 = 0x00000501 = + * 0000 0000 0000 0000 0000 0101 0000 0001 - SOURCE_CLASS_BUTTON + * SOURCE_KEYBOARD + * SOURCE_GAMEPAD + * 16,777,232 = 0x01000010 = + * 0000 0001 0000 0000 0000 0000 0001 0000 - SOURCE_CLASS_JOYSTICK + * SOURCE_JOYSTICK + * + * 16,778,513 = 0x01000511 = + * 0000 0001 0000 0000 0000 0101 0001 0001 - SOURCE_CLASS_BUTTON + * SOURCE_CLASS_JOYSTICK + * SOURCE_GAMEPAD + * SOURCE_KEYBOARD + * SOURCE_JOYSTICK + * + * 257 = 0x00000101 = + * 0000 0000 0000 0000 0000 0001 0000 0001 - SOURCE_CLASS_BUTTON + * SOURCE_KEYBOARD + * + * + * + */ + + + @Override + public boolean onTouch(View view, MotionEvent event) { + if (view != getView()) { + return false; + } + + boolean consumed = false; + + int source = event.getSource(); +// logger.log(Level.INFO, "onTouch source: {0}", source); + + boolean isTouch = ((source & InputDevice.SOURCE_TOUCHSCREEN) == InputDevice.SOURCE_TOUCHSCREEN); +// logger.log(Level.INFO, "onTouch source: {0}, isTouch: {1}", +// new Object[]{source, isTouch}); + + if (isTouch && touchInput != null) { + // send the event to the touch processor + consumed = touchInput.onTouch(event); + } + + return consumed; + + } + + @Override + public boolean onKey(View view, int keyCode, KeyEvent event) { + if (view != getView()) { + return false; + } + + boolean consumed = false; + + int source = event.getSource(); +// logger.log(Level.INFO, "onKey source: {0}", source); + + boolean isTouch = + ((source & InputDevice.SOURCE_TOUCHSCREEN) == InputDevice.SOURCE_TOUCHSCREEN) || + ((source & InputDevice.SOURCE_KEYBOARD) == InputDevice.SOURCE_KEYBOARD); +// logger.log(Level.INFO, "onKey source: {0}, isTouch: {1}", +// new Object[]{source, isTouch}); + + if (touchInput != null) { + consumed = touchInput.onKey(event); + } + + return consumed; + + } + +} diff --git a/jme3-android/src/main/java/com/jme3/input/android/AndroidInputHandler14.java b/jme3-android/src/main/java/com/jme3/input/android/AndroidInputHandler14.java new file mode 100644 index 000000000..4b39ed24c --- /dev/null +++ b/jme3-android/src/main/java/com/jme3/input/android/AndroidInputHandler14.java @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2009-2012 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jme3.input.android; + +import android.opengl.GLSurfaceView; +import android.view.InputDevice; +import android.view.KeyEvent; +import android.view.MotionEvent; +import android.view.View; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * AndroidInputHandler14 extends AndroidInputHandler to + * add the onHover and onGenericMotion events that where added in Android rev 14 (Android 4.0).
+ * The onGenericMotion events are the main interface to Joystick axes. They + * were actually released in Android rev 12. + * + * @author iwgeric + */ +public class AndroidInputHandler14 extends AndroidInputHandler implements View.OnHoverListener, + View.OnGenericMotionListener { + + private static final Logger logger = Logger.getLogger(AndroidInputHandler14.class.getName()); + + public AndroidInputHandler14() { + touchInput = new AndroidTouchInput14(this); + joyInput = new AndroidJoyInput14(this); + } + + @Override + protected void removeListeners(GLSurfaceView view) { + super.removeListeners(view); + view.setOnHoverListener(null); + view.setOnGenericMotionListener(null); + } + + @Override + protected void addListeners(GLSurfaceView view) { + super.addListeners(view); + view.setOnHoverListener(this); + view.setOnGenericMotionListener(this); + } + + @Override + public boolean onHover(View view, MotionEvent event) { + if (view != getView()) { + return false; + } + + boolean consumed = false; + + int source = event.getSource(); +// logger.log(Level.INFO, "onTouch source: {0}", source); + + boolean isTouch = ((source & InputDevice.SOURCE_TOUCHSCREEN) == InputDevice.SOURCE_TOUCHSCREEN); +// logger.log(Level.INFO, "onTouch source: {0}, isTouch: {1}", +// new Object[]{source, isTouch}); + + if (isTouch && touchInput != null) { + // send the event to the touch processor + consumed = ((AndroidTouchInput14)touchInput).onHover(event); + } + + return consumed; + } + + @Override + public boolean onGenericMotion(View view, MotionEvent event) { + if (view != getView()) { + return false; + } + + boolean consumed = false; + + int source = event.getSource(); +// logger.log(Level.INFO, "onGenericMotion source: {0}", source); + + boolean isJoystick = + ((source & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) || + ((source & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK); + + if (isJoystick && joyInput != null) { +// logger.log(Level.INFO, "onGenericMotion source: {0}, isJoystick: {1}", +// new Object[]{source, isJoystick}); + // send the event to the touch processor + consumed = consumed || ((AndroidJoyInput14)joyInput).onGenericMotion(event); + } + + return consumed; + } + + @Override + public boolean onKey(View view, int keyCode, KeyEvent event) { + if (view != getView()) { + return false; + } + + boolean consumed = false; + +// logger.log(Level.INFO, "onKey keyCode: {0}, action: {1}, event: {2}", +// new Object[]{KeyEvent.keyCodeToString(keyCode), event.getAction(), event}); + int source = event.getSource(); +// logger.log(Level.INFO, "onKey source: {0}", source); + + boolean isTouch = + ((source & InputDevice.SOURCE_TOUCHSCREEN) == InputDevice.SOURCE_TOUCHSCREEN) || + ((source & InputDevice.SOURCE_KEYBOARD) == InputDevice.SOURCE_KEYBOARD); + boolean isJoystick = + ((source & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) || + ((source & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK); + + if (isTouch && touchInput != null) { +// logger.log(Level.INFO, "onKey source: {0}, isTouch: {1}", +// new Object[]{source, isTouch}); + consumed = touchInput.onKey(event); + } + if (isJoystick && joyInput != null) { +// logger.log(Level.INFO, "onKey source: {0}, isJoystick: {1}", +// new Object[]{source, isJoystick}); + // use inclusive OR to make sure the onKey method is called. + consumed = consumed | ((AndroidJoyInput14)joyInput).onKey(event); + } + + return consumed; + + } + +} diff --git a/jme3-android/src/main/java/com/jme3/input/android/AndroidJoyInput.java b/jme3-android/src/main/java/com/jme3/input/android/AndroidJoyInput.java new file mode 100644 index 000000000..1e610d24e --- /dev/null +++ b/jme3-android/src/main/java/com/jme3/input/android/AndroidJoyInput.java @@ -0,0 +1,238 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.input.android; + +import android.content.Context; +import android.opengl.GLSurfaceView; +import android.os.Vibrator; +import com.jme3.input.InputManager; +import com.jme3.input.JoyInput; +import com.jme3.input.Joystick; +import com.jme3.input.RawInputListener; +import com.jme3.input.event.InputEvent; +import com.jme3.input.event.JoyAxisEvent; +import com.jme3.input.event.JoyButtonEvent; +import com.jme3.system.AppSettings; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Main class that manages various joystick devices. Joysticks can be many forms + * including a simulated joystick to communicate the device orientation as well + * as physical gamepads.
+ * This class manages all the joysticks and feeds the inputs from each back + * to jME's InputManager. + * + * This handler also supports the joystick.rumble(rumbleAmount) method. In this + * case, when joystick.rumble(rumbleAmount) is called, the Android device will vibrate + * if the device has a built in vibrate motor. + * + * Because Andorid does not allow for the user to define the intensity of the + * vibration, the rumble amount (ie strength) is converted into vibration pulses + * The stronger the strength amount, the shorter the delay between pulses. If + * amount is 1, then the vibration stays on the whole time. If amount is 0.5, + * the vibration will a pulse of equal parts vibration and delay. + * To turn off vibration, set rumble amount to 0. + * + * MainActivity needs the following line to enable Joysticks on Android platforms + * joystickEventsEnabled = true; + * This is done to allow for battery conservation when sensor data or gamepads + * are not required by the application. + * + * To use the joystick rumble feature, the following line needs to be + * added to the Android Manifest File + * + * + * @author iwgeric + */ +public class AndroidJoyInput implements JoyInput { + private static final Logger logger = Logger.getLogger(AndroidJoyInput.class.getName()); + public static boolean disableSensors = false; + + protected AndroidInputHandler inputHandler; + protected List joystickList = new ArrayList(); +// private boolean dontSendHistory = false; + + + // Internal + private boolean initialized = false; + private RawInputListener listener = null; + private ConcurrentLinkedQueue eventQueue = new ConcurrentLinkedQueue(); + private AndroidSensorJoyInput sensorJoyInput; + private Vibrator vibrator = null; + private boolean vibratorActive = false; + private long maxRumbleTime = 250; // 250ms + + public AndroidJoyInput(AndroidInputHandler inputHandler) { + this.inputHandler = inputHandler; + sensorJoyInput = new AndroidSensorJoyInput(this); + } + + public void setView(GLSurfaceView view) { + if (view == null) { + vibrator = null; + } else { + // Get instance of Vibrator from current Context + vibrator = (Vibrator) view.getContext().getSystemService(Context.VIBRATOR_SERVICE); + if (vibrator == null) { + logger.log(Level.FINE, "Vibrator Service not found."); + } + } + + if (sensorJoyInput != null) { + sensorJoyInput.setView(view); + } + } + + public void loadSettings(AppSettings settings) { + + } + + public void addEvent(InputEvent event) { + eventQueue.add(event); + } + + /** + * Pauses the joystick device listeners to save battery life if they are not needed. + * Used to pause when the activity pauses + */ + public void pauseJoysticks() { + if (sensorJoyInput != null) { + sensorJoyInput.pauseSensors(); + } + if (vibrator != null && vibratorActive) { + vibrator.cancel(); + } + + } + + /** + * Resumes the joystick device listeners. + * Used to resume when the activity comes to the top of the stack + */ + public void resumeJoysticks() { + if (sensorJoyInput != null) { + sensorJoyInput.resumeSensors(); + } + + } + + @Override + public void initialize() { + initialized = true; + } + + @Override + public boolean isInitialized() { + return initialized; + } + + @Override + public void destroy() { + initialized = false; + + if (sensorJoyInput != null) { + sensorJoyInput.destroy(); + } + + setView(null); + } + + @Override + public void setInputListener(RawInputListener listener) { + this.listener = listener; + } + + @Override + public long getInputTimeNanos() { + return System.nanoTime(); + } + + @Override + public void setJoyRumble(int joyId, float amount) { + // convert amount to pulses since Android doesn't allow intensity + if (vibrator != null) { + final long rumbleOnDur = (long)(amount * maxRumbleTime); // ms to pulse vibration on + final long rumbleOffDur = maxRumbleTime - rumbleOnDur; // ms to delay between pulses + final long[] rumblePattern = { + 0, // start immediately + rumbleOnDur, // time to leave vibration on + rumbleOffDur // time to delay between vibrations + }; + final int rumbleRepeatFrom = 0; // index into rumble pattern to repeat from + +// logger.log(Level.FINE, "Rumble amount: {0}, rumbleOnDur: {1}, rumbleOffDur: {2}", +// new Object[]{amount, rumbleOnDur, rumbleOffDur}); + + if (rumbleOnDur > 0) { + vibrator.vibrate(rumblePattern, rumbleRepeatFrom); + vibratorActive = true; + } else { + vibrator.cancel(); + vibratorActive = false; + } + } + } + + @Override + public Joystick[] loadJoysticks(InputManager inputManager) { + logger.log(Level.INFO, "loading joysticks for {0}", this.getClass().getName()); + if (!disableSensors) { + joystickList.add(sensorJoyInput.loadJoystick(joystickList.size(), inputManager)); + } + return joystickList.toArray( new Joystick[joystickList.size()] ); + } + + @Override + public void update() { + if (sensorJoyInput != null) { + sensorJoyInput.update(); + } + + if (listener != null) { + InputEvent inputEvent; + + while ((inputEvent = eventQueue.poll()) != null) { + if (inputEvent instanceof JoyAxisEvent) { + listener.onJoyAxisEvent((JoyAxisEvent)inputEvent); + } else if (inputEvent instanceof JoyButtonEvent) { + listener.onJoyButtonEvent((JoyButtonEvent)inputEvent); + } + } + } + + } + +} diff --git a/jme3-android/src/main/java/com/jme3/input/android/AndroidJoyInput14.java b/jme3-android/src/main/java/com/jme3/input/android/AndroidJoyInput14.java new file mode 100644 index 000000000..00478aea1 --- /dev/null +++ b/jme3-android/src/main/java/com/jme3/input/android/AndroidJoyInput14.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.input.android; + +import android.view.KeyEvent; +import android.view.MotionEvent; +import com.jme3.input.InputManager; +import com.jme3.input.Joystick; +import java.util.logging.Logger; + +/** + * AndroidJoyInput14 extends AndroidJoyInput + * to include support for physical joysticks/gamepads.
+ * + * @author iwgeric + */ +public class AndroidJoyInput14 extends AndroidJoyInput { + private static final Logger logger = Logger.getLogger(AndroidJoyInput14.class.getName()); + + private AndroidJoystickJoyInput14 joystickJoyInput; + + public AndroidJoyInput14(AndroidInputHandler inputHandler) { + super(inputHandler); + joystickJoyInput = new AndroidJoystickJoyInput14(this); + } + + /** + * Pauses the joystick device listeners to save battery life if they are not needed. + * Used to pause when the activity pauses + */ + @Override + public void pauseJoysticks() { + super.pauseJoysticks(); + + if (joystickJoyInput != null) { + joystickJoyInput.pauseJoysticks(); + } + } + + /** + * Resumes the joystick device listeners. + * Used to resume when the activity comes to the top of the stack + */ + @Override + public void resumeJoysticks() { + super.resumeJoysticks(); + if (joystickJoyInput != null) { + joystickJoyInput.resumeJoysticks(); + } + + } + + @Override + public void destroy() { + super.destroy(); + if (joystickJoyInput != null) { + joystickJoyInput.destroy(); + } + } + + @Override + public Joystick[] loadJoysticks(InputManager inputManager) { + // load the simulated joystick for device orientation + super.loadJoysticks(inputManager); + // load physical gamepads/joysticks + joystickList.addAll(joystickJoyInput.loadJoysticks(joystickList.size(), inputManager)); + // return the list of joysticks back to InputManager + return joystickList.toArray( new Joystick[joystickList.size()] ); + } + + public boolean onGenericMotion(MotionEvent event) { + return joystickJoyInput.onGenericMotion(event); + } + + public boolean onKey(KeyEvent event) { + return joystickJoyInput.onKey(event); + } + +} diff --git a/jme3-android/src/main/java/com/jme3/input/android/AndroidJoystickJoyInput14.java b/jme3-android/src/main/java/com/jme3/input/android/AndroidJoystickJoyInput14.java new file mode 100644 index 000000000..1ed98977c --- /dev/null +++ b/jme3-android/src/main/java/com/jme3/input/android/AndroidJoystickJoyInput14.java @@ -0,0 +1,416 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.input.android; + +import android.view.InputDevice; +import android.view.InputDevice.MotionRange; +import android.view.KeyCharacterMap; +import android.view.KeyEvent; +import android.view.MotionEvent; +import com.jme3.input.AbstractJoystick; +import com.jme3.input.DefaultJoystickAxis; +import com.jme3.input.DefaultJoystickButton; +import com.jme3.input.InputManager; +import com.jme3.input.JoyInput; +import com.jme3.input.Joystick; +import com.jme3.input.JoystickAxis; +import com.jme3.input.JoystickButton; +import com.jme3.input.JoystickCompatibilityMappings; +import com.jme3.input.event.JoyAxisEvent; +import com.jme3.input.event.JoyButtonEvent; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Main class that creates and manages Android inputs for physical gamepads/joysticks. + * + * @author iwgeric + */ +public class AndroidJoystickJoyInput14 { + private static final Logger logger = Logger.getLogger(AndroidJoystickJoyInput14.class.getName()); + + private boolean loaded = false; + private AndroidJoyInput joyInput; + private Map joystickIndex = new HashMap(); + + private static int[] AndroidGamepadButtons = { + // Dpad buttons + KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN, + KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT, + KeyEvent.KEYCODE_DPAD_CENTER, + + // pressing joystick down + KeyEvent.KEYCODE_BUTTON_THUMBL, KeyEvent.KEYCODE_BUTTON_THUMBR, + + // buttons + KeyEvent.KEYCODE_BUTTON_A, KeyEvent.KEYCODE_BUTTON_B, + KeyEvent.KEYCODE_BUTTON_X, KeyEvent.KEYCODE_BUTTON_Y, + + // buttons on back of device + KeyEvent.KEYCODE_BUTTON_L1, KeyEvent.KEYCODE_BUTTON_R1, + KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.KEYCODE_BUTTON_R2, + + // start / select buttons + KeyEvent.KEYCODE_BUTTON_START, KeyEvent.KEYCODE_BUTTON_SELECT, + KeyEvent.KEYCODE_BUTTON_MODE, + + }; + + public AndroidJoystickJoyInput14(AndroidJoyInput joyInput) { + this.joyInput = joyInput; + } + + + public void pauseJoysticks() { + + } + + public void resumeJoysticks() { + + } + + public void destroy() { + + } + + public List loadJoysticks(int joyId, InputManager inputManager) { + logger.log(Level.INFO, "loading Joystick devices"); + ArrayList joysticks = new ArrayList(); + joysticks.clear(); + joystickIndex.clear(); + + ArrayList gameControllerDeviceIds = new ArrayList(); + int[] deviceIds = InputDevice.getDeviceIds(); + for (int deviceId : deviceIds) { + InputDevice dev = InputDevice.getDevice(deviceId); + int sources = dev.getSources(); + logger.log(Level.FINE, "deviceId[{0}] sources: {1}", new Object[]{deviceId, sources}); + + // Verify that the device has gamepad buttons, control sticks, or both. + if (((sources & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) || + ((sources & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK)) { + // This device is a game controller. Store its device ID. + if (!gameControllerDeviceIds.contains(deviceId)) { + gameControllerDeviceIds.add(deviceId); + logger.log(Level.FINE, "Attempting to create joystick for device: {0}", dev); + // Create an AndroidJoystick and store the InputDevice so we + // can later correspond the input from the InputDevice to the + // appropriate jME Joystick event + AndroidJoystick joystick = new AndroidJoystick(inputManager, + joyInput, + dev, + joyId+joysticks.size(), + dev.getName()); + joystickIndex.put(deviceId, joystick); + joysticks.add(joystick); + + // Each analog input is reported as a MotionRange + // The axis number corresponds to the type of axis + // The AndroidJoystick.addAxis(MotionRange) converts the axis + // type reported by Android into the jME Joystick axis + List motionRanges = dev.getMotionRanges(); + for (MotionRange motionRange: motionRanges) { + logger.log(Level.INFO, "motion range: {0}", motionRange.toString()); + logger.log(Level.INFO, "axis: {0}", motionRange.getAxis()); + JoystickAxis axis = joystick.addAxis(motionRange); + logger.log(Level.INFO, "added axis: {0}", axis); + } + + // InputDevice has a method for determining if a keyCode is + // supported (InputDevice public boolean[] hasKeys (int... keys)). + // But this method wasn't added until rev 19 (Android 4.4) + // Therefore, we only can query the entire device and see if + // any InputDevice supports the keyCode. This may result in + // buttons being configured that don't exist on the specific + // device, but I haven't found a better way yet. + for (int keyCode: AndroidGamepadButtons) { + logger.log(Level.INFO, "button[{0}]: {1}", + new Object[]{keyCode, KeyCharacterMap.deviceHasKey(keyCode)}); + if (KeyCharacterMap.deviceHasKey(keyCode)) { + // add button even though we aren't sure if the button + // actually exists on this InputDevice + logger.log(Level.INFO, "button[{0}] exists somewhere", keyCode); + JoystickButton button = joystick.addButton(keyCode); + logger.log(Level.INFO, "added button: {0}", button); + } + } + + } + } + } + + + loaded = true; + return joysticks; + } + + public boolean onGenericMotion(MotionEvent event) { + boolean consumed = false; +// logger.log(Level.INFO, "onGenericMotion event: {0}", event); + event.getDeviceId(); + event.getSource(); +// logger.log(Level.INFO, "deviceId: {0}, source: {1}", new Object[]{event.getDeviceId(), event.getSource()}); + AndroidJoystick joystick = joystickIndex.get(event.getDeviceId()); + if (joystick != null) { + for (int androidAxis: joystick.getAndroidAxes()) { + String axisName = MotionEvent.axisToString(androidAxis); + float value = event.getAxisValue(androidAxis); + int action = event.getAction(); + if (action == MotionEvent.ACTION_MOVE) { +// logger.log(Level.INFO, "MOVE axis num: {0}, axisName: {1}, value: {2}", +// new Object[]{androidAxis, axisName, value}); + JoystickAxis axis = joystick.getAxis(androidAxis); + if (axis != null) { +// logger.log(Level.INFO, "MOVE axis num: {0}, axisName: {1}, value: {2}, deadzone: {3}", +// new Object[]{androidAxis, axisName, value, axis.getDeadZone()}); + JoyAxisEvent axisEvent = new JoyAxisEvent(axis, value); + joyInput.addEvent(axisEvent); + consumed = true; + } else { +// logger.log(Level.INFO, "axis was null for axisName: {0}", axisName); + } + } else { +// logger.log(Level.INFO, "action: {0}", action); + } + } + } + + return consumed; + } + + public boolean onKey(KeyEvent event) { + boolean consumed = false; +// logger.log(Level.INFO, "onKey event: {0}", event); + + event.getDeviceId(); + event.getSource(); + AndroidJoystick joystick = joystickIndex.get(event.getDeviceId()); + if (joystick != null) { + JoystickButton button = joystick.getButton(event.getKeyCode()); + boolean pressed = event.getAction() == KeyEvent.ACTION_DOWN; + if (button != null) { + JoyButtonEvent buttonEvent = new JoyButtonEvent(button, pressed); + joyInput.addEvent(buttonEvent); + consumed = true; + } else { + JoystickButton newButton = joystick.addButton(event.getKeyCode()); + JoyButtonEvent buttonEvent = new JoyButtonEvent(newButton, pressed); + joyInput.addEvent(buttonEvent); + consumed = true; + } + } + + return consumed; + } + + protected class AndroidJoystick extends AbstractJoystick { + + private JoystickAxis nullAxis; + private InputDevice device; + private JoystickAxis xAxis; + private JoystickAxis yAxis; + private JoystickAxis povX; + private JoystickAxis povY; + private Map axisIndex = new HashMap(); + private Map buttonIndex = new HashMap(); + + public AndroidJoystick( InputManager inputManager, JoyInput joyInput, InputDevice device, + int joyId, String name ) { + super( inputManager, joyInput, joyId, name ); + + this.device = device; + + this.nullAxis = new DefaultJoystickAxis( getInputManager(), this, -1, + "Null", "null", false, false, 0 ); + this.xAxis = nullAxis; + this.yAxis = nullAxis; + this.povX = nullAxis; + this.povY = nullAxis; + } + + protected JoystickAxis getAxis(int androidAxis) { + return axisIndex.get(androidAxis); + } + + protected Set getAndroidAxes() { + return axisIndex.keySet(); + } + + protected JoystickButton getButton(int keyCode) { + return buttonIndex.get(keyCode); + } + + protected JoystickButton addButton( int keyCode ) { + +// logger.log(Level.FINE, "Adding button: {0}", keyCode); + + String name = KeyEvent.keyCodeToString(keyCode); + String original = KeyEvent.keyCodeToString(keyCode); + // A/B/X/Y buttons + if (keyCode == KeyEvent.KEYCODE_BUTTON_Y) { + original = JoystickButton.BUTTON_0; + } else if (keyCode == KeyEvent.KEYCODE_BUTTON_B) { + original = JoystickButton.BUTTON_1; + } else if (keyCode == KeyEvent.KEYCODE_BUTTON_A) { + original = JoystickButton.BUTTON_2; + } else if (keyCode == KeyEvent.KEYCODE_BUTTON_X) { + original = JoystickButton.BUTTON_3; + // Front buttons Some of these have the top ones and the bottoms ones flipped. + } else if (keyCode == KeyEvent.KEYCODE_BUTTON_L1) { + original = JoystickButton.BUTTON_4; + } else if (keyCode == KeyEvent.KEYCODE_BUTTON_R1) { + original = JoystickButton.BUTTON_5; + } else if (keyCode == KeyEvent.KEYCODE_BUTTON_L2) { + original = JoystickButton.BUTTON_6; + } else if (keyCode == KeyEvent.KEYCODE_BUTTON_R2) { + original = JoystickButton.BUTTON_7; +// // Dpad buttons +// } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) { +// original = JoystickButton.BUTTON_8; +// } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) { +// original = JoystickButton.BUTTON_9; +// } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) { +// original = JoystickButton.BUTTON_8; +// } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) { +// original = JoystickButton.BUTTON_9; + // Select and start buttons + } else if (keyCode == KeyEvent.KEYCODE_BUTTON_SELECT) { + original = JoystickButton.BUTTON_8; + } else if (keyCode == KeyEvent.KEYCODE_BUTTON_START) { + original = JoystickButton.BUTTON_9; + // Joystick push buttons + } else if (keyCode == KeyEvent.KEYCODE_BUTTON_THUMBL) { + original = JoystickButton.BUTTON_10; + } else if (keyCode == KeyEvent.KEYCODE_BUTTON_THUMBR) { + original = JoystickButton.BUTTON_11; + } + + String logicalId = JoystickCompatibilityMappings.remapComponent( getName(), original ); + if( logicalId == null ? original != null : !logicalId.equals(original) ) { + logger.log(Level.FINE, "Remapped: {0} to: {1}", + new Object[]{original, logicalId}); + } + + JoystickButton button = new DefaultJoystickButton( getInputManager(), this, getButtonCount(), + name, logicalId ); + addButton(button); + buttonIndex.put( keyCode, button ); + return button; + } + + protected JoystickAxis addAxis(MotionRange motionRange) { + + String name = MotionEvent.axisToString(motionRange.getAxis()); + + String original = MotionEvent.axisToString(motionRange.getAxis()); + if (motionRange.getAxis() == MotionEvent.AXIS_X) { + original = JoystickAxis.X_AXIS; + } else if (motionRange.getAxis() == MotionEvent.AXIS_Y) { + original = JoystickAxis.Y_AXIS; + } else if (motionRange.getAxis() == MotionEvent.AXIS_Z) { + original = JoystickAxis.Z_AXIS; + } else if (motionRange.getAxis() == MotionEvent.AXIS_RZ) { + original = JoystickAxis.Z_ROTATION; + } else if (motionRange.getAxis() == MotionEvent.AXIS_HAT_X) { + original = JoystickAxis.POV_X; + } else if (motionRange.getAxis() == MotionEvent.AXIS_HAT_Y) { + original = JoystickAxis.POV_Y; + } + String logicalId = JoystickCompatibilityMappings.remapComponent( getName(), original ); + if( logicalId == null ? original != null : !logicalId.equals(original) ) { + logger.log(Level.FINE, "Remapped: {0} to: {1}", + new Object[]{original, logicalId}); + } + + JoystickAxis axis = new DefaultJoystickAxis(getInputManager(), + this, + getAxisCount(), + name, + logicalId, + true, + true, + motionRange.getFlat()); + + if (motionRange.getAxis() == MotionEvent.AXIS_X) { + xAxis = axis; + } + if (motionRange.getAxis() == MotionEvent.AXIS_Y) { + yAxis = axis; + } + if (motionRange.getAxis() == MotionEvent.AXIS_HAT_X) { + povX = axis; + } + if (motionRange.getAxis() == MotionEvent.AXIS_HAT_Y) { + povY = axis; + } + + addAxis(axis); + axisIndex.put(motionRange.getAxis(), axis); + return axis; + } + + @Override + public JoystickAxis getXAxis() { + return xAxis; + } + + @Override + public JoystickAxis getYAxis() { + return yAxis; + } + + @Override + public JoystickAxis getPovXAxis() { + return povX; + } + + @Override + public JoystickAxis getPovYAxis() { + return povY; + } + + @Override + public int getXAxisIndex(){ + return xAxis.getAxisId(); + } + + @Override + public int getYAxisIndex(){ + return yAxis.getAxisId(); + } + } +} diff --git a/jme3-android/src/main/java/com/jme3/input/android/AndroidKeyHandler.java b/jme3-android/src/main/java/com/jme3/input/android/AndroidKeyHandler.java deleted file mode 100644 index 997974c31..000000000 --- a/jme3-android/src/main/java/com/jme3/input/android/AndroidKeyHandler.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package com.jme3.input.android; - -import android.content.Context; -import android.view.KeyEvent; -import android.view.View; -import android.view.inputmethod.InputMethodManager; -import com.jme3.input.event.KeyInputEvent; -import com.jme3.input.event.TouchEvent; -import java.util.logging.Logger; - -/** - * AndroidKeyHandler recieves onKey events from the Android system and creates - * the jME KeyEvents. onKey is used by Android to receive keys from the keyboard - * or device buttons. All key events are consumed by jME except for the Volume - * buttons and menu button. - * - * This class also provides the functionality to display or hide the soft keyboard - * for inputing single key events. Use OGLESContext to display an dialog to type - * in complete strings. - * - * @author iwgeric - */ -public class AndroidKeyHandler implements View.OnKeyListener { - private static final Logger logger = Logger.getLogger(AndroidKeyHandler.class.getName()); - - private AndroidInputHandler androidInput; - private boolean sendKeyEvents = true; - - public AndroidKeyHandler(AndroidInputHandler androidInput) { - this.androidInput = androidInput; - } - - public void initialize() { - } - - public void destroy() { - } - - public void setView(View view) { - if (view != null) { - view.setOnKeyListener(this); - } else { - androidInput.getView().setOnKeyListener(null); - } - } - - /** - * onKey gets called from android thread on key events - */ - public boolean onKey(View view, int keyCode, KeyEvent event) { - if (androidInput.isInitialized() && view != androidInput.getView()) { - return false; - } - - TouchEvent evt; - // TODO: get touch event from pool - if (event.getAction() == KeyEvent.ACTION_DOWN) { - evt = new TouchEvent(); - evt.set(TouchEvent.Type.KEY_DOWN); - evt.setKeyCode(keyCode); - evt.setCharacters(event.getCharacters()); - evt.setTime(event.getEventTime()); - - // Send the event - androidInput.addEvent(evt); - - } else if (event.getAction() == KeyEvent.ACTION_UP) { - evt = new TouchEvent(); - evt.set(TouchEvent.Type.KEY_UP); - evt.setKeyCode(keyCode); - evt.setCharacters(event.getCharacters()); - evt.setTime(event.getEventTime()); - - // Send the event - androidInput.addEvent(evt); - - } - - if (androidInput.isSimulateKeyboard()) { - KeyInputEvent kie; - char unicodeChar = (char)event.getUnicodeChar(); - int jmeKeyCode = AndroidKeyMapping.getJmeKey(keyCode); - - boolean pressed = event.getAction() == KeyEvent.ACTION_DOWN; - boolean repeating = pressed && event.getRepeatCount() > 0; - - kie = new KeyInputEvent(jmeKeyCode, unicodeChar, pressed, repeating); - kie.setTime(event.getEventTime()); - androidInput.addEvent(kie); -// logger.log(Level.FINE, "onKey keyCode: {0}, jmeKeyCode: {1}, pressed: {2}, repeating: {3}", -// new Object[]{keyCode, jmeKeyCode, pressed, repeating}); -// logger.log(Level.FINE, "creating KeyInputEvent: {0}", kie); - } - - // consume all keys ourself except Volume Up/Down and Menu - // Don't do Menu so that typical Android Menus can be created and used - // by the user in MainActivity - if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP) || - (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) || - (keyCode == KeyEvent.KEYCODE_MENU)) { - return false; - } else { - return true; - } - - } - -} diff --git a/jme3-android/src/main/java/com/jme3/input/android/AndroidKeyMapping.java b/jme3-android/src/main/java/com/jme3/input/android/AndroidKeyMapping.java index e99d8e9fc..32d1e0008 100644 --- a/jme3-android/src/main/java/com/jme3/input/android/AndroidKeyMapping.java +++ b/jme3-android/src/main/java/com/jme3/input/android/AndroidKeyMapping.java @@ -37,13 +37,14 @@ import java.util.logging.Logger; /** * AndroidKeyMapping is just a utility to convert the Android keyCodes into - * jME KeyCodes received in jME's KeyEvent will match between Desktop and Android. - * + * jME KeyCodes so that events received in jME's KeyEvent will match between + * Desktop and Android. + * * @author iwgeric */ public class AndroidKeyMapping { private static final Logger logger = Logger.getLogger(AndroidKeyMapping.class.getName()); - + private static final int[] ANDROID_TO_JME = { 0x0, // unknown 0x0, // key code soft left @@ -141,9 +142,13 @@ public class AndroidKeyMapping { 0x0,//media fastforward 0x0,//mute }; - + public static int getJmeKey(int androidKey) { - return ANDROID_TO_JME[androidKey]; + if (androidKey > ANDROID_TO_JME.length) { + return androidKey; + } else { + return ANDROID_TO_JME[androidKey]; + } } - + } diff --git a/jme3-android/src/main/java/com/jme3/input/android/AndroidSensorJoyInput.java b/jme3-android/src/main/java/com/jme3/input/android/AndroidSensorJoyInput.java index 034b068d8..cdd7e6494 100644 --- a/jme3-android/src/main/java/com/jme3/input/android/AndroidSensorJoyInput.java +++ b/jme3-android/src/main/java/com/jme3/input/android/AndroidSensorJoyInput.java @@ -37,7 +37,7 @@ import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; -import android.os.Vibrator; +import android.opengl.GLSurfaceView; import android.view.Surface; import android.view.WindowManager; import com.jme3.input.AbstractJoystick; @@ -47,10 +47,8 @@ import com.jme3.input.JoyInput; import com.jme3.input.Joystick; import com.jme3.input.JoystickAxis; import com.jme3.input.SensorJoystickAxis; -import com.jme3.input.RawInputListener; import com.jme3.input.event.JoyAxisEvent; import com.jme3.math.FastMath; -import com.jme3.system.android.JmeAndroidSystem; import com.jme3.util.IntMap; import com.jme3.util.IntMap.Entry; import java.util.ArrayList; @@ -63,7 +61,7 @@ import java.util.logging.Logger; * A single joystick is configured and includes data for all configured sensors * as seperate axes of the joystick. * - * Each axis is named accounting to the static strings in SensorJoystickAxis. + * Each axis is named according to the static strings in SensorJoystickAxis. * Refer to the strings defined in SensorJoystickAxis for a list of supported * sensors and their axis data. Each sensor type defined in SensorJoystickAxis * will be attempted to be configured. If the device does not support a particular @@ -72,46 +70,21 @@ import java.util.logging.Logger; * The joystick.getXAxis and getYAxis methods of the joystick are configured to * return the device orientation values in the device's X and Y directions. * - * This joystick also supports the joystick.rumble(rumbleAmount) method. In this - * case, when joystick.rumble(rumbleAmount) is called, the Android device will vibrate - * if the device has a built in vibrate motor. - * - * Because Andorid does not allow for the user to define the intensity of the - * vibration, the rumble amount (ie strength) is converted into vibration pulses - * The stronger the strength amount, the shorter the delay between pulses. If - * amount is 1, then the vibration stays on the whole time. If amount is 0.5, - * the vibration will a pulse of equal parts vibration and delay. - * To turn off vibration, set rumble amount to 0. - * - * MainActivity needs the following line to enable Joysticks on Android platforms - * joystickEventsEnabled = true; - * This is done to allow for battery conservation when sensor data is not required - * by the application. - * - * To use the joystick rumble feature, the following line needs to be - * added to the Android Manifest File - * - * * @author iwgeric */ -public class AndroidSensorJoyInput implements JoyInput, SensorEventListener { +public class AndroidSensorJoyInput implements SensorEventListener { private final static Logger logger = Logger.getLogger(AndroidSensorJoyInput.class.getName()); - private Context context = null; - private InputManager inputManager = null; + private AndroidJoyInput joyInput; private SensorManager sensorManager = null; private WindowManager windowManager = null; - private Vibrator vibrator = null; - private boolean vibratorActive = false; - private long maxRumbleTime = 250; // 250ms - private RawInputListener listener = null; private IntMap sensors = new IntMap(); - private AndroidJoystick[] joysticks; private int lastRotation = 0; - private boolean initialized = false; private boolean loaded = false; - private final ArrayList eventQueue = new ArrayList(); + public AndroidSensorJoyInput(AndroidJoyInput joyInput) { + this.joyInput = joyInput; + } /** * Internal class to enclose data for each sensor. @@ -120,10 +93,10 @@ public class AndroidSensorJoyInput implements JoyInput, SensorEventListener { int androidSensorType = -1; int androidSensorSpeed = SensorManager.SENSOR_DELAY_GAME; Sensor sensor = null; - int sensorAccuracy = 0; + int sensorAccuracy = -1; float[] lastValues; final Object valuesLock = new Object(); - ArrayList axes = new ArrayList(); + ArrayList axes = new ArrayList(); boolean enabled = false; boolean haveData = false; @@ -134,16 +107,19 @@ public class AndroidSensorJoyInput implements JoyInput, SensorEventListener { } - private void initSensorManager() { - this.context = JmeAndroidSystem.getView().getContext(); - // Get instance of the WindowManager from the current Context - windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); - // Get instance of the SensorManager from the current Context - sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); - // Get instance of Vibrator from current Context - vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); - if (vibrator == null) { - logger.log(Level.FINE, "Vibrator Service not found."); + public void setView(GLSurfaceView view) { + pauseSensors(); + if (sensorManager != null) { + sensorManager.unregisterListener(this); + } + if (view == null) { + windowManager = null; + sensorManager = null; + } else { + // Get instance of the WindowManager from the current Context + windowManager = (WindowManager) view.getContext().getSystemService(Context.WINDOW_SERVICE); + // Get instance of the SensorManager from the current Context + sensorManager = (SensorManager) view.getContext().getSystemService(Context.SENSOR_SERVICE); } } @@ -222,9 +198,6 @@ public class AndroidSensorJoyInput implements JoyInput, SensorEventListener { unRegisterListener(entry.getKey()); } } - if (vibrator != null && vibratorActive) { - vibrator.cancel(); - } } /** @@ -333,7 +306,7 @@ public class AndroidSensorJoyInput implements JoyInput, SensorEventListener { */ private boolean updateOrientation() { SensorData sensorData; - AndroidJoystickAxis axis; + AndroidSensorJoystickAxis axis; final float[] curInclinationMat = new float[16]; final float[] curRotationMat = new float[16]; final float[] rotatedRotationMat = new float[16]; @@ -400,10 +373,8 @@ public class AndroidSensorJoyInput implements JoyInput, SensorEventListener { if (!sensorData.haveData) { sensorData.haveData = true; } else { - synchronized (eventQueue){ - if (axis.isChanged()) { - eventQueue.add(new JoyAxisEvent(axis, axis.getJoystickAxisValue())); - } + if (axis.isChanged()) { + joyInput.addEvent(new JoyAxisEvent(axis, axis.getJoystickAxisValue())); } } } @@ -428,47 +399,14 @@ public class AndroidSensorJoyInput implements JoyInput, SensorEventListener { // Start of JoyInput methods - public void setJoyRumble(int joyId, float amount) { - // convert amount to pulses since Android doesn't allow intensity - if (vibrator != null) { - final long rumbleOnDur = (long)(amount * maxRumbleTime); // ms to pulse vibration on - final long rumbleOffDur = maxRumbleTime - rumbleOnDur; // ms to delay between pulses - final long[] rumblePattern = { - 0, // start immediately - rumbleOnDur, // time to leave vibration on - rumbleOffDur // time to delay between vibrations - }; - final int rumbleRepeatFrom = 0; // index into rumble pattern to repeat from - - logger.log(Level.FINE, "Rumble amount: {0}, rumbleOnDur: {1}, rumbleOffDur: {2}", - new Object[]{amount, rumbleOnDur, rumbleOffDur}); - - if (rumbleOnDur > 0) { - vibrator.vibrate(rumblePattern, rumbleRepeatFrom); - vibratorActive = true; - } else { - vibrator.cancel(); - vibratorActive = false; - } - } - - } - - public Joystick[] loadJoysticks(InputManager inputManager) { - this.inputManager = inputManager; - - initSensorManager(); - + public Joystick loadJoystick(int joyId, InputManager inputManager) { SensorData sensorData; - List list = new ArrayList(); - AndroidJoystick joystick; - AndroidJoystickAxis axis; + AndroidSensorJoystickAxis axis; - joystick = new AndroidJoystick(inputManager, - this, - list.size(), + AndroidSensorJoystick joystick = new AndroidSensorJoystick(inputManager, + joyInput, + joyId, "AndroidSensorsJoystick"); - list.add(joystick); List availSensors = sensorManager.getSensorList(Sensor.TYPE_ALL); for (Sensor sensor: availSensors) { @@ -555,14 +493,8 @@ public class AndroidSensorJoyInput implements JoyInput, SensorEventListener { // } - joysticks = list.toArray( new AndroidJoystick[list.size()] ); loaded = true; - return joysticks; - } - - public void initialize() { - initialized = true; - loaded = false; + return joystick; } public void update() { @@ -570,15 +502,6 @@ public class AndroidSensorJoyInput implements JoyInput, SensorEventListener { return; } updateOrientation(); - synchronized (eventQueue){ - // flush events to listener - if (listener != null && eventQueue.size() > 0) { - for (int i = 0; i < eventQueue.size(); i++){ - listener.onJoyAxisEvent(eventQueue.get(i)); - } - eventQueue.clear(); - } - } } public void destroy() { @@ -588,39 +511,27 @@ public class AndroidSensorJoyInput implements JoyInput, SensorEventListener { sensorManager.unregisterListener(this); } sensors.clear(); - eventQueue.clear(); - initialized = false; loaded = false; - joysticks = null; sensorManager = null; - vibrator = null; - context = null; - } - - public boolean isInitialized() { - return initialized; - } - - public void setInputListener(RawInputListener listener) { - this.listener = listener; - } - - public long getInputTimeNanos() { - return System.nanoTime(); } - // End of JoyInput methods - // Start of Android SensorEventListener methods + @Override public void onSensorChanged(SensorEvent se) { - if (!initialized || !loaded) { + if (!loaded) { return; } +// logger.log(Level.FINE, "onSensorChanged for {0}: accuracy: {1}, values: {2}", +// new Object[]{se.sensor.getName(), se.accuracy, se.values}); int sensorType = se.sensor.getType(); SensorData sensorData = sensors.get(sensorType); + if (sensorData != null) { +// logger.log(Level.FINE, "sensorData name: {0}, enabled: {1}, unreliable: {2}", +// new Object[]{sensorData.sensor.getName(), sensorData.enabled, sensorData.sensorAccuracy == SensorManager.SENSOR_STATUS_UNRELIABLE}); + } if (sensorData != null && sensorData.sensor.equals(se.sensor) && sensorData.enabled) { if (sensorData.sensorAccuracy == SensorManager.SENSOR_STATUS_UNRELIABLE) { @@ -632,8 +543,8 @@ public class AndroidSensorJoyInput implements JoyInput, SensorEventListener { } } - if (sensorData != null && sensorData.axes.size() > 0) { - AndroidJoystickAxis axis; + if (sensorData.axes.size() > 0) { + AndroidSensorJoystickAxis axis; for (int i=0; i lastPositions = new HashMap(); - - protected int numPointers = 0; - - protected AndroidInputHandler androidInput; - protected AndroidGestureHandler gestureHandler; - - public AndroidTouchHandler(AndroidInputHandler androidInput, AndroidGestureHandler gestureHandler) { - this.androidInput = androidInput; - this.gestureHandler = gestureHandler; - } - - public void initialize() { - } - - public void destroy() { - setView(null); - } - - public void setView(View view) { - if (view != null) { - view.setOnTouchListener(this); - } else { - androidInput.getView().setOnTouchListener(null); - } - } - - protected int getPointerIndex(MotionEvent event) { - return (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) - >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; - } - - protected int getPointerId(MotionEvent event) { - return event.getPointerId(getPointerIndex(event)); - } - - protected int getAction(MotionEvent event) { - return event.getAction() & MotionEvent.ACTION_MASK; - } - - /** - * onTouch gets called from android thread on touch events - */ - public boolean onTouch(View view, MotionEvent event) { - if (!androidInput.isInitialized() || view != androidInput.getView()) { - return false; - } - - boolean bWasHandled = false; - TouchEvent touch = null; - // System.out.println("native : " + event.getAction()); - int action = getAction(event); - int pointerIndex = getPointerIndex(event); - int pointerId = getPointerId(event); - Vector2f lastPos = lastPositions.get(pointerId); - float jmeX; - float jmeY; - - numPointers = event.getPointerCount(); - - // final int historySize = event.getHistorySize(); - //final int pointerCount = event.getPointerCount(); - switch (getAction(event)) { - case MotionEvent.ACTION_POINTER_DOWN: - case MotionEvent.ACTION_DOWN: - jmeX = androidInput.getJmeX(event.getX(pointerIndex)); - jmeY = androidInput.invertY(androidInput.getJmeY(event.getY(pointerIndex))); - touch = androidInput.getFreeTouchEvent(); - touch.set(TouchEvent.Type.DOWN, jmeX, jmeY, 0, 0); - touch.setPointerId(pointerId); - touch.setTime(event.getEventTime()); - touch.setPressure(event.getPressure(pointerIndex)); - - lastPos = new Vector2f(jmeX, jmeY); - lastPositions.put(pointerId, lastPos); - - processEvent(touch); - - bWasHandled = true; - break; - case MotionEvent.ACTION_POINTER_UP: - case MotionEvent.ACTION_CANCEL: - case MotionEvent.ACTION_UP: - jmeX = androidInput.getJmeX(event.getX(pointerIndex)); - jmeY = androidInput.invertY(androidInput.getJmeY(event.getY(pointerIndex))); - touch = androidInput.getFreeTouchEvent(); - touch.set(TouchEvent.Type.UP, jmeX, jmeY, 0, 0); - touch.setPointerId(pointerId); - touch.setTime(event.getEventTime()); - touch.setPressure(event.getPressure(pointerIndex)); - lastPositions.remove(pointerId); - - processEvent(touch); - - bWasHandled = true; - break; - case MotionEvent.ACTION_MOVE: - // Convert all pointers into events - for (int p = 0; p < event.getPointerCount(); p++) { - jmeX = androidInput.getJmeX(event.getX(p)); - jmeY = androidInput.invertY(androidInput.getJmeY(event.getY(p))); - lastPos = lastPositions.get(event.getPointerId(p)); - if (lastPos == null) { - lastPos = new Vector2f(jmeX, jmeY); - lastPositions.put(event.getPointerId(p), lastPos); - } - - float dX = jmeX - lastPos.x; - float dY = jmeY - lastPos.y; - if (dX != 0 || dY != 0) { - touch = androidInput.getFreeTouchEvent(); - touch.set(TouchEvent.Type.MOVE, jmeX, jmeY, dX, dY); - touch.setPointerId(event.getPointerId(p)); - touch.setTime(event.getEventTime()); - touch.setPressure(event.getPressure(p)); - lastPos.set(jmeX, jmeY); - - processEvent(touch); - - bWasHandled = true; - } - } - break; - case MotionEvent.ACTION_OUTSIDE: - break; - - } - - // Try to detect gestures - if (gestureHandler != null) { - gestureHandler.detectGesture(event); - } - - return bWasHandled; - } - - protected void processEvent(TouchEvent event) { - // Add the touch event - androidInput.addEvent(event); - // MouseEvents do not support multi-touch, so only evaluate 1 finger pointer events - if (androidInput.isSimulateMouse() && numPointers == 1) { - InputEvent mouseEvent = generateMouseEvent(event); - if (mouseEvent != null) { - // Add the mouse event - androidInput.addEvent(mouseEvent); - } - } - - } - - // TODO: Ring Buffer for mouse events? - protected InputEvent generateMouseEvent(TouchEvent event) { - InputEvent inputEvent = null; - int newX; - int newY; - int newDX; - int newDY; - - if (androidInput.isMouseEventsInvertX()) { - newX = (int) (androidInput.invertX(event.getX())); - newDX = (int)event.getDeltaX() * -1; - } else { - newX = (int) event.getX(); - newDX = (int)event.getDeltaX(); - } - - if (androidInput.isMouseEventsInvertY()) { - newY = (int) (androidInput.invertY(event.getY())); - newDY = (int)event.getDeltaY() * -1; - } else { - newY = (int) event.getY(); - newDY = (int)event.getDeltaY(); - } - - switch (event.getType()) { - case DOWN: - // Handle mouse down event - inputEvent = new MouseButtonEvent(0, true, newX, newY); - inputEvent.setTime(event.getTime()); - break; - - case UP: - // Handle mouse up event - inputEvent = new MouseButtonEvent(0, false, newX, newY); - inputEvent.setTime(event.getTime()); - break; - - case HOVER_MOVE: - case MOVE: - inputEvent = new MouseMotionEvent(newX, newY, newDX, newDY, (int)event.getScaleSpan(), (int)event.getDeltaScaleSpan()); - inputEvent.setTime(event.getTime()); - break; - } - - return inputEvent; - } - -} diff --git a/jme3-android/src/main/java/com/jme3/input/android/AndroidTouchInput.java b/jme3-android/src/main/java/com/jme3/input/android/AndroidTouchInput.java new file mode 100644 index 000000000..bddc5fab3 --- /dev/null +++ b/jme3-android/src/main/java/com/jme3/input/android/AndroidTouchInput.java @@ -0,0 +1,475 @@ +/* + * Copyright (c) 2009-2012 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jme3.input.android; + +import android.view.GestureDetector; +import android.view.KeyEvent; +import android.view.MotionEvent; +import android.view.ScaleGestureDetector; +import com.jme3.input.RawInputListener; +import com.jme3.input.TouchInput; +import com.jme3.input.event.InputEvent; +import com.jme3.input.event.KeyInputEvent; +import com.jme3.input.event.MouseButtonEvent; +import com.jme3.input.event.MouseMotionEvent; +import com.jme3.input.event.TouchEvent; +import static com.jme3.input.event.TouchEvent.Type.DOWN; +import static com.jme3.input.event.TouchEvent.Type.MOVE; +import static com.jme3.input.event.TouchEvent.Type.UP; +import com.jme3.math.Vector2f; +import com.jme3.system.AppSettings; +import java.util.HashMap; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * AndroidTouchInput is the base class that receives touch inputs from the + * Android system and creates the TouchEvents for jME. This class is designed + * to handle the base touch events for Android rev 9 (Android 2.3). This is + * extended by other classes to add features that were introducted after + * Android rev 9. + * + * @author iwgeric + */ +public class AndroidTouchInput implements TouchInput { + private static final Logger logger = Logger.getLogger(AndroidTouchInput.class.getName()); + + private boolean mouseEventsEnabled = true; + private boolean mouseEventsInvertX = false; + private boolean mouseEventsInvertY = false; + private boolean keyboardEventsEnabled = false; + private boolean dontSendHistory = false; + + protected int numPointers = 0; + final private HashMap lastPositions = new HashMap(); + final private ConcurrentLinkedQueue inputEventQueue = new ConcurrentLinkedQueue(); + private final static int MAX_TOUCH_EVENTS = 1024; + private final TouchEventPool touchEventPool = new TouchEventPool(MAX_TOUCH_EVENTS); + private float scaleX = 1f; + private float scaleY = 1f; + + private boolean initialized = false; + private RawInputListener listener = null; + + private GestureDetector gestureDetector; + private ScaleGestureDetector scaleDetector; + + protected AndroidInputHandler androidInput; + + public AndroidTouchInput(AndroidInputHandler androidInput) { + this.androidInput = androidInput; + } + + public GestureDetector getGestureDetector() { + return gestureDetector; + } + + public void setGestureDetector(GestureDetector gestureDetector) { + this.gestureDetector = gestureDetector; + } + + public ScaleGestureDetector getScaleDetector() { + return scaleDetector; + } + + public void setScaleDetector(ScaleGestureDetector scaleDetector) { + this.scaleDetector = scaleDetector; + } + + public float invertX(float origX) { + return getJmeX(androidInput.getView().getWidth()) - origX; + } + + public float invertY(float origY) { + return getJmeY(androidInput.getView().getHeight()) - origY; + } + + public float getJmeX(float origX) { + return origX * scaleX; + } + + public float getJmeY(float origY) { + return origY * scaleY; + } + + public void loadSettings(AppSettings settings) { + keyboardEventsEnabled = settings.isEmulateKeyboard(); + mouseEventsEnabled = settings.isEmulateMouse(); + mouseEventsInvertX = settings.isEmulateMouseFlipX(); + mouseEventsInvertY = settings.isEmulateMouseFlipY(); + + // view width and height are 0 until the view is displayed on the screen + if (androidInput.getView().getWidth() != 0 && androidInput.getView().getHeight() != 0) { + scaleX = (float)settings.getWidth() / (float)androidInput.getView().getWidth(); + scaleY = (float)settings.getHeight() / (float)androidInput.getView().getHeight(); + } + logger.log(Level.FINE, "Setting input scaling, scaleX: {0}, scaleY: {1}", + new Object[]{scaleX, scaleY}); + + + } + + + protected int getPointerIndex(MotionEvent event) { + return (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) + >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; + } + + protected int getPointerId(MotionEvent event) { + return event.getPointerId(getPointerIndex(event)); + } + + protected int getAction(MotionEvent event) { + return event.getAction() & MotionEvent.ACTION_MASK; + } + + public boolean onTouch(MotionEvent event) { + if (!isInitialized()) { + return false; + } + + boolean bWasHandled = false; + TouchEvent touch = null; + // System.out.println("native : " + event.getAction()); + int action = getAction(event); + int pointerIndex = getPointerIndex(event); + int pointerId = getPointerId(event); + Vector2f lastPos = lastPositions.get(pointerId); + float jmeX; + float jmeY; + + numPointers = event.getPointerCount(); + + // final int historySize = event.getHistorySize(); + //final int pointerCount = event.getPointerCount(); + switch (getAction(event)) { + case MotionEvent.ACTION_POINTER_DOWN: + case MotionEvent.ACTION_DOWN: + jmeX = getJmeX(event.getX(pointerIndex)); + jmeY = invertY(getJmeY(event.getY(pointerIndex))); + touch = getFreeTouchEvent(); + touch.set(TouchEvent.Type.DOWN, jmeX, jmeY, 0, 0); + touch.setPointerId(pointerId); + touch.setTime(event.getEventTime()); + touch.setPressure(event.getPressure(pointerIndex)); + + lastPos = new Vector2f(jmeX, jmeY); + lastPositions.put(pointerId, lastPos); + + addEvent(touch); + addEvent(generateMouseEvent(touch)); + + bWasHandled = true; + break; + case MotionEvent.ACTION_POINTER_UP: + case MotionEvent.ACTION_CANCEL: + case MotionEvent.ACTION_UP: + jmeX = getJmeX(event.getX(pointerIndex)); + jmeY = invertY(getJmeY(event.getY(pointerIndex))); + touch = getFreeTouchEvent(); + touch.set(TouchEvent.Type.UP, jmeX, jmeY, 0, 0); + touch.setPointerId(pointerId); + touch.setTime(event.getEventTime()); + touch.setPressure(event.getPressure(pointerIndex)); + lastPositions.remove(pointerId); + + addEvent(touch); + addEvent(generateMouseEvent(touch)); + + bWasHandled = true; + break; + case MotionEvent.ACTION_MOVE: + // Convert all pointers into events + for (int p = 0; p < event.getPointerCount(); p++) { + jmeX = getJmeX(event.getX(p)); + jmeY = invertY(getJmeY(event.getY(p))); + lastPos = lastPositions.get(event.getPointerId(p)); + if (lastPos == null) { + lastPos = new Vector2f(jmeX, jmeY); + lastPositions.put(event.getPointerId(p), lastPos); + } + + float dX = jmeX - lastPos.x; + float dY = jmeY - lastPos.y; + if (dX != 0 || dY != 0) { + touch = getFreeTouchEvent(); + touch.set(TouchEvent.Type.MOVE, jmeX, jmeY, dX, dY); + touch.setPointerId(event.getPointerId(p)); + touch.setTime(event.getEventTime()); + touch.setPressure(event.getPressure(p)); + lastPos.set(jmeX, jmeY); + + addEvent(touch); + addEvent(generateMouseEvent(touch)); + + bWasHandled = true; + } + } + break; + case MotionEvent.ACTION_OUTSIDE: + break; + + } + + // Try to detect gestures + if (gestureDetector != null) { + gestureDetector.onTouchEvent(event); + } + if (scaleDetector != null) { + scaleDetector.onTouchEvent(event); + } + + return bWasHandled; + } + + // TODO: Ring Buffer for mouse events? + public InputEvent generateMouseEvent(TouchEvent event) { + InputEvent inputEvent = null; + int newX; + int newY; + int newDX; + int newDY; + + // MouseEvents do not support multi-touch, so only evaluate 1 finger pointer events + if (!isSimulateMouse() || numPointers > 1) { + return null; + } + + + if (isMouseEventsInvertX()) { + newX = (int) (invertX(event.getX())); + newDX = (int)event.getDeltaX() * -1; + } else { + newX = (int) event.getX(); + newDX = (int)event.getDeltaX(); + } + + if (isMouseEventsInvertY()) { + newY = (int) (invertY(event.getY())); + newDY = (int)event.getDeltaY() * -1; + } else { + newY = (int) event.getY(); + newDY = (int)event.getDeltaY(); + } + + switch (event.getType()) { + case DOWN: + // Handle mouse down event + inputEvent = new MouseButtonEvent(0, true, newX, newY); + inputEvent.setTime(event.getTime()); + break; + + case UP: + // Handle mouse up event + inputEvent = new MouseButtonEvent(0, false, newX, newY); + inputEvent.setTime(event.getTime()); + break; + + case HOVER_MOVE: + case MOVE: + inputEvent = new MouseMotionEvent(newX, newY, newDX, newDY, (int)event.getScaleSpan(), (int)event.getDeltaScaleSpan()); + inputEvent.setTime(event.getTime()); + break; + } + + return inputEvent; + } + + + public boolean onKey(KeyEvent event) { + if (!isInitialized()) { + return false; + } + + TouchEvent evt; + // TODO: get touch event from pool + if (event.getAction() == KeyEvent.ACTION_DOWN) { + evt = new TouchEvent(); + evt.set(TouchEvent.Type.KEY_DOWN); + evt.setKeyCode(event.getKeyCode()); + evt.setCharacters(event.getCharacters()); + evt.setTime(event.getEventTime()); + + // Send the event + addEvent(evt); + + } else if (event.getAction() == KeyEvent.ACTION_UP) { + evt = new TouchEvent(); + evt.set(TouchEvent.Type.KEY_UP); + evt.setKeyCode(event.getKeyCode()); + evt.setCharacters(event.getCharacters()); + evt.setTime(event.getEventTime()); + + // Send the event + addEvent(evt); + + } + + if (isSimulateKeyboard()) { + KeyInputEvent kie; + char unicodeChar = (char)event.getUnicodeChar(); + int jmeKeyCode = AndroidKeyMapping.getJmeKey(event.getKeyCode()); + + boolean pressed = event.getAction() == KeyEvent.ACTION_DOWN; + boolean repeating = pressed && event.getRepeatCount() > 0; + + kie = new KeyInputEvent(jmeKeyCode, unicodeChar, pressed, repeating); + kie.setTime(event.getEventTime()); + addEvent(kie); +// logger.log(Level.FINE, "onKey keyCode: {0}, jmeKeyCode: {1}, pressed: {2}, repeating: {3}", +// new Object[]{event.getKeyCode(), jmeKeyCode, pressed, repeating}); +// logger.log(Level.FINE, "creating KeyInputEvent: {0}", kie); + } + + // consume all keys ourself except Volume Up/Down and Menu + // Don't do Menu so that typical Android Menus can be created and used + // by the user in MainActivity + if ((event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) || + (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) || + (event.getKeyCode() == KeyEvent.KEYCODE_MENU)) { + return false; + } else { + return true; + } + + } + + + + + // ----------------------------------------- + // JME3 Input interface + @Override + public void initialize() { + touchEventPool.initialize(); + + initialized = true; + } + + @Override + public void destroy() { + initialized = false; + + touchEventPool.destroy(); + + } + + @Override + public boolean isInitialized() { + return initialized; + } + + @Override + public void setInputListener(RawInputListener listener) { + this.listener = listener; + } + + @Override + public long getInputTimeNanos() { + return System.nanoTime(); + } + + @Override + public void update() { + if (listener != null) { + InputEvent inputEvent; + + while ((inputEvent = inputEventQueue.poll()) != null) { + if (inputEvent instanceof TouchEvent) { + listener.onTouchEvent((TouchEvent)inputEvent); + } else if (inputEvent instanceof MouseButtonEvent) { + listener.onMouseButtonEvent((MouseButtonEvent)inputEvent); + } else if (inputEvent instanceof MouseMotionEvent) { + listener.onMouseMotionEvent((MouseMotionEvent)inputEvent); + } else if (inputEvent instanceof KeyInputEvent) { + listener.onKeyEvent((KeyInputEvent)inputEvent); + } + } + } + } + + // ----------------------------------------- + + public TouchEvent getFreeTouchEvent() { + return touchEventPool.getNextFreeEvent(); + } + + public void addEvent(InputEvent event) { + if (event == null) { + return; + } + + logger.log(Level.INFO, "event: {0}", event); + + inputEventQueue.add(event); + if (event instanceof TouchEvent) { + touchEventPool.storeEvent((TouchEvent)event); + } + + } + + @Override + public void setSimulateMouse(boolean simulate) { + this.mouseEventsEnabled = simulate; + } + + @Override + public boolean isSimulateMouse() { + return mouseEventsEnabled; + } + + public boolean isMouseEventsInvertX() { + return mouseEventsInvertX; + } + + public boolean isMouseEventsInvertY() { + return mouseEventsInvertY; + } + + @Override + public void setSimulateKeyboard(boolean simulate) { + this.keyboardEventsEnabled = simulate; + } + + @Override + public boolean isSimulateKeyboard() { + return keyboardEventsEnabled; + } + + @Override + public void setOmitHistoricEvents(boolean dontSendHistory) { + this.dontSendHistory = dontSendHistory; + } + +} diff --git a/jme3-android/src/main/java/com/jme3/input/android/AndroidTouchHandler14.java b/jme3-android/src/main/java/com/jme3/input/android/AndroidTouchInput14.java similarity index 67% rename from jme3-android/src/main/java/com/jme3/input/android/AndroidTouchHandler14.java rename to jme3-android/src/main/java/com/jme3/input/android/AndroidTouchInput14.java index 1a785a5e9..617a4b719 100644 --- a/jme3-android/src/main/java/com/jme3/input/android/AndroidTouchHandler14.java +++ b/jme3-android/src/main/java/com/jme3/input/android/AndroidTouchInput14.java @@ -33,7 +33,6 @@ package com.jme3.input.android; import android.view.MotionEvent; -import android.view.View; import com.jme3.input.event.TouchEvent; import com.jme3.math.Vector2f; import java.util.HashMap; @@ -41,36 +40,20 @@ import java.util.logging.Level; import java.util.logging.Logger; /** - * AndroidTouchHandler14 is an extension of AndroidTouchHander that adds the - * Android touch event functionality between Android rev 9 (Android 2.3) and - * Android rev 14 (Android 4.0). - * + * AndroidTouchHandler14 extends AndroidTouchHandler to process the onHover + * events added in Android rev 14 (Android 4.0). + * * @author iwgeric */ -public class AndroidTouchHandler14 extends AndroidTouchHandler implements - View.OnHoverListener { - private static final Logger logger = Logger.getLogger(AndroidTouchHandler14.class.getName()); +public class AndroidTouchInput14 extends AndroidTouchInput { + private static final Logger logger = Logger.getLogger(AndroidTouchInput14.class.getName()); final private HashMap lastHoverPositions = new HashMap(); - - public AndroidTouchHandler14(AndroidInputHandler androidInput, AndroidGestureHandler gestureHandler) { - super(androidInput, gestureHandler); - } - @Override - public void setView(View view) { - if (view != null) { - view.setOnHoverListener(this); - } else { - androidInput.getView().setOnHoverListener(null); - } - super.setView(view); + public AndroidTouchInput14(AndroidInputHandler androidInput) { + super(androidInput); } - - public boolean onHover(View view, MotionEvent event) { - if (view == null || view != androidInput.getView()) { - return false; - } - + + public boolean onHover(MotionEvent event) { boolean consumed = false; int action = getAction(event); int pointerId = getPointerId(event); @@ -78,34 +61,34 @@ public class AndroidTouchHandler14 extends AndroidTouchHandler implements Vector2f lastPos = lastHoverPositions.get(pointerId); float jmeX; float jmeY; - + numPointers = event.getPointerCount(); - - logger.log(Level.INFO, "onHover pointerId: {0}, action: {1}, x: {2}, y: {3}, numPointers: {4}", - new Object[]{pointerId, action, event.getX(), event.getY(), event.getPointerCount()}); + +// logger.log(Level.INFO, "onHover pointerId: {0}, action: {1}, x: {2}, y: {3}, numPointers: {4}", +// new Object[]{pointerId, action, event.getX(), event.getY(), event.getPointerCount()}); TouchEvent touchEvent; switch (action) { case MotionEvent.ACTION_HOVER_ENTER: - jmeX = androidInput.getJmeX(event.getX(pointerIndex)); - jmeY = androidInput.invertY(androidInput.getJmeY(event.getY(pointerIndex))); - touchEvent = androidInput.getFreeTouchEvent(); + jmeX = getJmeX(event.getX(pointerIndex)); + jmeY = invertY(getJmeY(event.getY(pointerIndex))); + touchEvent = getFreeTouchEvent(); touchEvent.set(TouchEvent.Type.HOVER_START, jmeX, jmeY, 0, 0); touchEvent.setPointerId(pointerId); touchEvent.setTime(event.getEventTime()); touchEvent.setPressure(event.getPressure(pointerIndex)); - + lastPos = new Vector2f(jmeX, jmeY); lastHoverPositions.put(pointerId, lastPos); - - processEvent(touchEvent); + + addEvent(touchEvent); consumed = true; break; case MotionEvent.ACTION_HOVER_MOVE: // Convert all pointers into events for (int p = 0; p < event.getPointerCount(); p++) { - jmeX = androidInput.getJmeX(event.getX(p)); - jmeY = androidInput.invertY(androidInput.getJmeY(event.getY(p))); + jmeX = getJmeX(event.getX(p)); + jmeY = invertY(getJmeY(event.getY(p))); lastPos = lastHoverPositions.get(event.getPointerId(p)); if (lastPos == null) { lastPos = new Vector2f(jmeX, jmeY); @@ -115,38 +98,39 @@ public class AndroidTouchHandler14 extends AndroidTouchHandler implements float dX = jmeX - lastPos.x; float dY = jmeY - lastPos.y; if (dX != 0 || dY != 0) { - touchEvent = androidInput.getFreeTouchEvent(); + touchEvent = getFreeTouchEvent(); touchEvent.set(TouchEvent.Type.HOVER_MOVE, jmeX, jmeY, dX, dY); touchEvent.setPointerId(event.getPointerId(p)); touchEvent.setTime(event.getEventTime()); touchEvent.setPressure(event.getPressure(p)); lastPos.set(jmeX, jmeY); - processEvent(touchEvent); + addEvent(touchEvent); } } consumed = true; break; case MotionEvent.ACTION_HOVER_EXIT: - jmeX = androidInput.getJmeX(event.getX(pointerIndex)); - jmeY = androidInput.invertY(androidInput.getJmeY(event.getY(pointerIndex))); - touchEvent = androidInput.getFreeTouchEvent(); + jmeX = getJmeX(event.getX(pointerIndex)); + jmeY = invertY(getJmeY(event.getY(pointerIndex))); + touchEvent = getFreeTouchEvent(); touchEvent.set(TouchEvent.Type.HOVER_END, jmeX, jmeY, 0, 0); touchEvent.setPointerId(pointerId); touchEvent.setTime(event.getEventTime()); touchEvent.setPressure(event.getPressure(pointerIndex)); lastHoverPositions.remove(pointerId); - processEvent(touchEvent); + addEvent(touchEvent); consumed = true; break; default: consumed = false; break; } - + return consumed; + } - + } diff --git a/jme3-android/src/main/java/com/jme3/renderer/android/AndroidGL.java b/jme3-android/src/main/java/com/jme3/renderer/android/AndroidGL.java index 2a7b54023..b77c4a36d 100644 --- a/jme3-android/src/main/java/com/jme3/renderer/android/AndroidGL.java +++ b/jme3-android/src/main/java/com/jme3/renderer/android/AndroidGL.java @@ -35,39 +35,43 @@ import android.opengl.GLES20; import com.jme3.renderer.RendererException; import com.jme3.renderer.opengl.GL; import com.jme3.renderer.opengl.GLExt; +import com.jme3.renderer.opengl.GLFbo; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; -public class AndroidGL implements GL, GLExt { +public class AndroidGL implements GL, GLExt, GLFbo { + + public void resetStats() { + } private static int getLimitBytes(ByteBuffer buffer) { checkLimit(buffer); return buffer.limit(); } - + private static int getLimitBytes(ShortBuffer buffer) { checkLimit(buffer); return buffer.limit() * 2; } - + private static int getLimitBytes(IntBuffer buffer) { checkLimit(buffer); return buffer.limit() * 4; } - + private static int getLimitBytes(FloatBuffer buffer) { checkLimit(buffer); return buffer.limit() * 4; } - + private static int getLimitCount(Buffer buffer, int elementSize) { checkLimit(buffer); return buffer.limit() / elementSize; } - + private static void checkLimit(Buffer buffer) { if (buffer == null) { return; @@ -79,7 +83,7 @@ public class AndroidGL implements GL, GLExt { throw new RendererException("Attempting to upload empty buffer (remaining = 0), that's an error"); } } - + public void glActiveTexture(int texture) { GLES20.glActiveTexture(texture); } @@ -127,7 +131,7 @@ public class AndroidGL implements GL, GLExt { public void glBufferSubData(int target, long offset, ByteBuffer data) { GLES20.glBufferSubData(target, (int) offset, getLimitBytes(data), data); } - + public void glGetBufferSubData(int target, long offset, ByteBuffer data) { throw new UnsupportedOperationException("OpenGL ES 2 does not support glGetBufferSubData"); } diff --git a/jme3-android/src/main/java/com/jme3/renderer/android/OGLESShaderRenderer.java b/jme3-android/src/main/java/com/jme3/renderer/android/OGLESShaderRenderer.java deleted file mode 100644 index cef3e9f66..000000000 --- a/jme3-android/src/main/java/com/jme3/renderer/android/OGLESShaderRenderer.java +++ /dev/null @@ -1,2566 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.renderer.android; - -import android.opengl.GLES20; -import android.os.Build; -import com.jme3.asset.AndroidImageInfo; -import com.jme3.light.LightList; -import com.jme3.material.RenderState; -import com.jme3.math.ColorRGBA; -import com.jme3.math.Quaternion; -import com.jme3.math.Vector2f; -import com.jme3.math.Vector3f; -import com.jme3.math.Vector4f; -import com.jme3.renderer.Caps; -import com.jme3.renderer.IDList; -import com.jme3.renderer.RenderContext; -import com.jme3.renderer.Renderer; -import com.jme3.renderer.RendererException; -import com.jme3.renderer.Statistics; -import com.jme3.renderer.android.TextureUtil.AndroidGLImageFormat; -import com.jme3.renderer.opengl.GLRenderer; -import com.jme3.scene.Mesh; -import com.jme3.scene.Mesh.Mode; -import com.jme3.scene.VertexBuffer; -import com.jme3.scene.VertexBuffer.Format; -import com.jme3.scene.VertexBuffer.Type; -import com.jme3.scene.VertexBuffer.Usage; -import com.jme3.shader.Attribute; -import com.jme3.shader.Shader; -import com.jme3.shader.Shader.ShaderSource; -import com.jme3.shader.Shader.ShaderType; -import com.jme3.shader.Uniform; -import com.jme3.texture.FrameBuffer; -import com.jme3.texture.FrameBuffer.RenderBuffer; -import com.jme3.texture.Image; -import com.jme3.texture.Texture; -import com.jme3.texture.Texture.WrapAxis; -import com.jme3.util.BufferUtils; -import com.jme3.util.ListMap; -import com.jme3.util.NativeObjectManager; -import java.nio.Buffer; -import java.nio.ByteBuffer; -import java.nio.FloatBuffer; -import java.nio.IntBuffer; -import java.nio.ShortBuffer; -import java.util.EnumSet; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import jme3tools.shader.ShaderDebug; - -/** - * @deprecated Should not be used anymore. Use {@link GLRenderer} instead. - */ -@Deprecated -public class OGLESShaderRenderer implements Renderer { - - private static final Logger logger = Logger.getLogger(OGLESShaderRenderer.class.getName()); - private static final boolean VALIDATE_SHADER = false; - private final ByteBuffer nameBuf = BufferUtils.createByteBuffer(250); - private final StringBuilder stringBuf = new StringBuilder(250); - private final IntBuffer intBuf1 = BufferUtils.createIntBuffer(1); - private final IntBuffer intBuf16 = BufferUtils.createIntBuffer(16); - private final RenderContext context = new RenderContext(); - private final NativeObjectManager objManager = new NativeObjectManager(); - private final EnumSet caps = EnumSet.noneOf(Caps.class); - // current state - private Shader boundShader; - // initalDrawBuf and initialReadBuf are not used on ES, - // http://www.khronos.org/opengles/sdk/docs/man/xhtml/glBindFramebuffer.xml - //private int initialDrawBuf, initialReadBuf; - private int glslVer; - private int vertexTextureUnits; - private int fragTextureUnits; - private int vertexUniforms; - private int fragUniforms; - private int vertexAttribs; -// private int maxFBOSamples; - private final int maxFBOAttachs = 1; // Only 1 color attachment on ES - private final int maxMRTFBOAttachs = 1; // FIXME for now, not sure if > 1 is needed for ES - private int maxRBSize; - private int maxTexSize; - private int maxCubeTexSize; - private int maxVertCount; - private int maxTriCount; - private boolean tdc; - private FrameBuffer lastFb = null; - private FrameBuffer mainFbOverride = null; - private final Statistics statistics = new Statistics(); - private int vpX, vpY, vpW, vpH; - private int clipX, clipY, clipW, clipH; - //private final GL10 gl; - private boolean powerVr = false; - private boolean useVBO = false; - - public OGLESShaderRenderer() { - } - - protected void updateNameBuffer() { - int len = stringBuf.length(); - - nameBuf.position(0); - nameBuf.limit(len); - for (int i = 0; i < len; i++) { - nameBuf.put((byte) stringBuf.charAt(i)); - } - - nameBuf.rewind(); - } - - public Statistics getStatistics() { - return statistics; - } - - public EnumSet getCaps() { - return caps; - } - - private static final Pattern VERSION = Pattern.compile(".*?(\\d+)\\.(\\d+).*"); - - public static int extractVersion(String version) { - - Matcher m = VERSION.matcher(version); - if (m.matches()) { - int major = Integer.parseInt(m.group(1)); - int minor = Integer.parseInt(m.group(2)); - - return major * 100 + minor * 10; - } else { - return -1; - } - } - - public void initialize() { - logger.log(Level.FINE, "Vendor: {0}", GLES20.glGetString(GLES20.GL_VENDOR)); - logger.log(Level.FINE, "Renderer: {0}", GLES20.glGetString(GLES20.GL_RENDERER)); - logger.log(Level.FINE, "Version: {0}", GLES20.glGetString(GLES20.GL_VERSION)); - logger.log(Level.FINE, "Shading Language Version: {0}", GLES20.glGetString(GLES20.GL_SHADING_LANGUAGE_VERSION)); - - powerVr = GLES20.glGetString(GLES20.GL_RENDERER).contains("PowerVR"); - - - //workaround, always assume we support GLSL100 - //some cards just don't report this correctly - caps.add(Caps.GLSL100); - - /* - // Fix issue in TestRenderToMemory when GL_FRONT is the main - // buffer being used. - initialDrawBuf = glGetInteger(GL_DRAW_BUFFER); - initialReadBuf = glGetInteger(GL_READ_BUFFER); - - // XXX: This has to be GL_BACK for canvas on Mac - // Since initialDrawBuf is GL_FRONT for pbuffer, gotta - // change this value later on ... -// initialDrawBuf = GL_BACK; -// initialReadBuf = GL_BACK; - */ - - // Check OpenGL version - int openGlVer = extractVersion(GLES20.glGetString(GLES20.GL_VERSION)); - if (openGlVer == -1) { - glslVer = -1; - throw new UnsupportedOperationException("OpenGL ES 2.0+ is required for OGLESShaderRenderer!"); - } - - // Check shader language version - glslVer = extractVersion(GLES20.glGetString(GLES20.GL_SHADING_LANGUAGE_VERSION)); - switch (glslVer) { - // TODO: When new versions of OpenGL ES shader language come out, - // update this. - default: - caps.add(Caps.GLSL100); - break; - } - - GLES20.glGetIntegerv(GLES20.GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, intBuf16); - vertexTextureUnits = intBuf16.get(0); - logger.log(Level.FINE, "VTF Units: {0}", vertexTextureUnits); - if (vertexTextureUnits > 0) { - caps.add(Caps.VertexTextureFetch); - } - - GLES20.glGetIntegerv(GLES20.GL_MAX_TEXTURE_IMAGE_UNITS, intBuf16); - fragTextureUnits = intBuf16.get(0); - logger.log(Level.FINE, "Texture Units: {0}", fragTextureUnits); - - // Multiply vector count by 4 to get float count. - GLES20.glGetIntegerv(GLES20.GL_MAX_VERTEX_UNIFORM_VECTORS, intBuf16); - vertexUniforms = intBuf16.get(0) * 4; - logger.log(Level.FINER, "Vertex Uniforms: {0}", vertexUniforms); - - GLES20.glGetIntegerv(GLES20.GL_MAX_FRAGMENT_UNIFORM_VECTORS, intBuf16); - fragUniforms = intBuf16.get(0) * 4; - logger.log(Level.FINER, "Fragment Uniforms: {0}", fragUniforms); - - GLES20.glGetIntegerv(GLES20.GL_MAX_VARYING_VECTORS, intBuf16); - int varyingFloats = intBuf16.get(0) * 4; - logger.log(Level.FINER, "Varying Floats: {0}", varyingFloats); - - GLES20.glGetIntegerv(GLES20.GL_MAX_VERTEX_ATTRIBS, intBuf16); - vertexAttribs = intBuf16.get(0); - logger.log(Level.FINE, "Vertex Attributes: {0}", vertexAttribs); - - GLES20.glGetIntegerv(GLES20.GL_SUBPIXEL_BITS, intBuf16); - int subpixelBits = intBuf16.get(0); - logger.log(Level.FINE, "Subpixel Bits: {0}", subpixelBits); - -// GLES10.glGetIntegerv(GLES10.GL_MAX_ELEMENTS_VERTICES, intBuf16); -// maxVertCount = intBuf16.get(0); -// logger.log(Level.FINER, "Preferred Batch Vertex Count: {0}", maxVertCount); -// -// GLES10.glGetIntegerv(GLES10.GL_MAX_ELEMENTS_INDICES, intBuf16); -// maxTriCount = intBuf16.get(0); -// logger.log(Level.FINER, "Preferred Batch Index Count: {0}", maxTriCount); - - GLES20.glGetIntegerv(GLES20.GL_MAX_TEXTURE_SIZE, intBuf16); - maxTexSize = intBuf16.get(0); - logger.log(Level.FINE, "Maximum Texture Resolution: {0}", maxTexSize); - - GLES20.glGetIntegerv(GLES20.GL_MAX_CUBE_MAP_TEXTURE_SIZE, intBuf16); - maxCubeTexSize = intBuf16.get(0); - logger.log(Level.FINE, "Maximum CubeMap Resolution: {0}", maxCubeTexSize); - - GLES20.glGetIntegerv(GLES20.GL_MAX_RENDERBUFFER_SIZE, intBuf16); - maxRBSize = intBuf16.get(0); - logger.log(Level.FINER, "FBO RB Max Size: {0}", maxRBSize); - - /* - if (ctxCaps.GL_ARB_color_buffer_float){ - // XXX: Require both 16 and 32 bit float support for FloatColorBuffer. - if (ctxCaps.GL_ARB_half_float_pixel){ - caps.add(Caps.FloatColorBuffer); - } - } - - if (ctxCaps.GL_ARB_depth_buffer_float){ - caps.add(Caps.FloatDepthBuffer); - } - - if (ctxCaps.GL_ARB_draw_instanced) - caps.add(Caps.MeshInstancing); - - if (ctxCaps.GL_ARB_texture_buffer_object) - caps.add(Caps.TextureBuffer); - - if (ctxCaps.GL_ARB_texture_float){ - if (ctxCaps.GL_ARB_half_float_pixel){ - caps.add(Caps.FloatTexture); - } - } - - if (ctxCaps.GL_EXT_packed_float){ - caps.add(Caps.PackedFloatColorBuffer); - if (ctxCaps.GL_ARB_half_float_pixel){ - // because textures are usually uploaded as RGB16F - // need half-float pixel - caps.add(Caps.PackedFloatTexture); - } - } - - if (ctxCaps.GL_EXT_texture_array) - caps.add(Caps.TextureArray); - - if (ctxCaps.GL_EXT_texture_shared_exponent) - caps.add(Caps.SharedExponentTexture); - - if (ctxCaps.GL_EXT_framebuffer_object){ - caps.add(Caps.FrameBuffer); - - glGetInteger(GL_MAX_RENDERBUFFER_SIZE_EXT, intBuf16); - maxRBSize = intBuf16.get(0); - logger.log(Level.FINER, "FBO RB Max Size: {0}", maxRBSize); - - glGetInteger(GL_MAX_COLOR_ATTACHMENTS_EXT, intBuf16); - maxFBOAttachs = intBuf16.get(0); - logger.log(Level.FINER, "FBO Max renderbuffers: {0}", maxFBOAttachs); - - if (ctxCaps.GL_EXT_framebuffer_multisample){ - caps.add(Caps.FrameBufferMultisample); - - glGetInteger(GL_MAX_SAMPLES_EXT, intBuf16); - maxFBOSamples = intBuf16.get(0); - logger.log(Level.FINER, "FBO Max Samples: {0}", maxFBOSamples); - } - - if (ctxCaps.GL_ARB_draw_buffers){ - caps.add(Caps.FrameBufferMRT); - glGetInteger(ARBDrawBuffers.GL_MAX_DRAW_BUFFERS_ARB, intBuf16); - maxMRTFBOAttachs = intBuf16.get(0); - logger.log(Level.FINER, "FBO Max MRT renderbuffers: {0}", maxMRTFBOAttachs); - } - } - - if (ctxCaps.GL_ARB_multisample){ - glGetInteger(ARBMultisample.GL_SAMPLE_BUFFERS_ARB, intBuf16); - boolean available = intBuf16.get(0) != 0; - glGetInteger(ARBMultisample.GL_SAMPLES_ARB, intBuf16); - int samples = intBuf16.get(0); - logger.log(Level.FINER, "Samples: {0}", samples); - boolean enabled = glIsEnabled(ARBMultisample.GL_MULTISAMPLE_ARB); - if (samples > 0 && available && !enabled){ - glEnable(ARBMultisample.GL_MULTISAMPLE_ARB); - } - } - */ - - String extensions = GLES20.glGetString(GLES20.GL_EXTENSIONS); - logger.log(Level.FINE, "GL_EXTENSIONS: {0}", extensions); - - // Get number of compressed formats available. - GLES20.glGetIntegerv(GLES20.GL_NUM_COMPRESSED_TEXTURE_FORMATS, intBuf16); - int numCompressedFormats = intBuf16.get(0); - - // Allocate buffer for compressed formats. - IntBuffer compressedFormats = BufferUtils.createIntBuffer(numCompressedFormats); - GLES20.glGetIntegerv(GLES20.GL_COMPRESSED_TEXTURE_FORMATS, compressedFormats); - - // Check for errors after all glGet calls. - RendererUtil.checkGLError(); - - // Print compressed formats. - for (int i = 0; i < numCompressedFormats; i++) { - logger.log(Level.FINE, "Compressed Texture Formats: {0}", compressedFormats.get(i)); - } - - TextureUtil.loadTextureFeatures(extensions); - - applyRenderState(RenderState.DEFAULT); - GLES20.glDisable(GLES20.GL_DITHER); - RendererUtil.checkGLError(); - - useVBO = false; - - // NOTE: SDK_INT is only available since 1.6, - // but for jME3 it doesn't matter since android versions 1.5 and below - // are not supported. - if (Build.VERSION.SDK_INT >= 9){ - logger.log(Level.FINE, "Force-enabling VBO (Android 2.3 or higher)"); - useVBO = true; - } else { - useVBO = false; - } - - logger.log(Level.FINE, "Caps: {0}", caps); - } - - /** - * resetGLObjects should be called when die GLView gets recreated to reset all GPU objects - */ - public void resetGLObjects() { - objManager.resetObjects(); - statistics.clearMemory(); - boundShader = null; - lastFb = null; - context.reset(); - } - - public void cleanup() { - objManager.deleteAllObjects(this); - statistics.clearMemory(); - } - - private void checkCap(Caps cap) { - if (!caps.contains(cap)) { - throw new UnsupportedOperationException("Required capability missing: " + cap.name()); - } - } - - /*********************************************************************\ - |* Render State *| - \*********************************************************************/ - public void setDepthRange(float start, float end) { - GLES20.glDepthRangef(start, end); - RendererUtil.checkGLError(); - } - - public void clearBuffers(boolean color, boolean depth, boolean stencil) { - int bits = 0; - if (color) { - //See explanations of the depth below, we must enable color write to be able to clear the color buffer - if (context.colorWriteEnabled == false) { - GLES20.glColorMask(true, true, true, true); - context.colorWriteEnabled = true; - } - bits = GLES20.GL_COLOR_BUFFER_BIT; - } - if (depth) { - //glClear(GL_DEPTH_BUFFER_BIT) seems to not work when glDepthMask is false - //here s some link on openl board - //http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=257223 - //if depth clear is requested, we enable the depthMask - if (context.depthWriteEnabled == false) { - GLES20.glDepthMask(true); - context.depthWriteEnabled = true; - } - bits |= GLES20.GL_DEPTH_BUFFER_BIT; - } - if (stencil) { - bits |= GLES20.GL_STENCIL_BUFFER_BIT; - } - if (bits != 0) { - GLES20.glClear(bits); - RendererUtil.checkGLError(); - } - } - - public void setBackgroundColor(ColorRGBA color) { - GLES20.glClearColor(color.r, color.g, color.b, color.a); - RendererUtil.checkGLError(); - } - - public void applyRenderState(RenderState state) { - /* - if (state.isWireframe() && !context.wireframe){ - GLES20.glPolygonMode(GLES20.GL_FRONT_AND_BACK, GLES20.GL_LINE); - context.wireframe = true; - }else if (!state.isWireframe() && context.wireframe){ - GLES20.glPolygonMode(GLES20.GL_FRONT_AND_BACK, GLES20.GL_FILL); - context.wireframe = false; - } - */ - if (state.isDepthTest() && !context.depthTestEnabled) { - GLES20.glEnable(GLES20.GL_DEPTH_TEST); - GLES20.glDepthFunc(convertTestFunction(context.depthFunc)); - RendererUtil.checkGLError(); - context.depthTestEnabled = true; - } else if (!state.isDepthTest() && context.depthTestEnabled) { - GLES20.glDisable(GLES20.GL_DEPTH_TEST); - RendererUtil.checkGLError(); - context.depthTestEnabled = false; - } - if (state.getDepthFunc() != context.depthFunc) { - GLES20.glDepthFunc(convertTestFunction(state.getDepthFunc())); - context.depthFunc = state.getDepthFunc(); - } - - if (state.isDepthWrite() && !context.depthWriteEnabled) { - GLES20.glDepthMask(true); - RendererUtil.checkGLError(); - context.depthWriteEnabled = true; - } else if (!state.isDepthWrite() && context.depthWriteEnabled) { - GLES20.glDepthMask(false); - RendererUtil.checkGLError(); - context.depthWriteEnabled = false; - } - if (state.isColorWrite() && !context.colorWriteEnabled) { - GLES20.glColorMask(true, true, true, true); - RendererUtil.checkGLError(); - context.colorWriteEnabled = true; - } else if (!state.isColorWrite() && context.colorWriteEnabled) { - GLES20.glColorMask(false, false, false, false); - RendererUtil.checkGLError(); - context.colorWriteEnabled = false; - } -// if (state.isPointSprite() && !context.pointSprite) { -//// GLES20.glEnable(GLES20.GL_POINT_SPRITE); -//// GLES20.glTexEnvi(GLES20.GL_POINT_SPRITE, GLES20.GL_COORD_REPLACE, GLES20.GL_TRUE); -//// GLES20.glEnable(GLES20.GL_VERTEX_PROGRAM_POINT_SIZE); -//// GLES20.glPointParameterf(GLES20.GL_POINT_SIZE_MIN, 1.0f); -// } else if (!state.isPointSprite() && context.pointSprite) { -//// GLES20.glDisable(GLES20.GL_POINT_SPRITE); -// } - - if (state.isPolyOffset()) { - if (!context.polyOffsetEnabled) { - GLES20.glEnable(GLES20.GL_POLYGON_OFFSET_FILL); - GLES20.glPolygonOffset(state.getPolyOffsetFactor(), - state.getPolyOffsetUnits()); - RendererUtil.checkGLError(); - - context.polyOffsetEnabled = true; - context.polyOffsetFactor = state.getPolyOffsetFactor(); - context.polyOffsetUnits = state.getPolyOffsetUnits(); - } else { - if (state.getPolyOffsetFactor() != context.polyOffsetFactor - || state.getPolyOffsetUnits() != context.polyOffsetUnits) { - GLES20.glPolygonOffset(state.getPolyOffsetFactor(), - state.getPolyOffsetUnits()); - RendererUtil.checkGLError(); - - context.polyOffsetFactor = state.getPolyOffsetFactor(); - context.polyOffsetUnits = state.getPolyOffsetUnits(); - } - } - } else { - if (context.polyOffsetEnabled) { - GLES20.glDisable(GLES20.GL_POLYGON_OFFSET_FILL); - RendererUtil.checkGLError(); - - context.polyOffsetEnabled = false; - context.polyOffsetFactor = 0; - context.polyOffsetUnits = 0; - } - } - if (state.getFaceCullMode() != context.cullMode) { - if (state.getFaceCullMode() == RenderState.FaceCullMode.Off) { - GLES20.glDisable(GLES20.GL_CULL_FACE); - RendererUtil.checkGLError(); - } else { - GLES20.glEnable(GLES20.GL_CULL_FACE); - RendererUtil.checkGLError(); - } - - switch (state.getFaceCullMode()) { - case Off: - break; - case Back: - GLES20.glCullFace(GLES20.GL_BACK); - RendererUtil.checkGLError(); - break; - case Front: - GLES20.glCullFace(GLES20.GL_FRONT); - RendererUtil.checkGLError(); - break; - case FrontAndBack: - GLES20.glCullFace(GLES20.GL_FRONT_AND_BACK); - RendererUtil.checkGLError(); - break; - default: - throw new UnsupportedOperationException("Unrecognized face cull mode: " - + state.getFaceCullMode()); - } - - context.cullMode = state.getFaceCullMode(); - } - - if (state.getBlendMode() != context.blendMode) { - if (state.getBlendMode() == RenderState.BlendMode.Off) { - GLES20.glDisable(GLES20.GL_BLEND); - RendererUtil.checkGLError(); - } else { - GLES20.glEnable(GLES20.GL_BLEND); - switch (state.getBlendMode()) { - case Off: - break; - case Additive: - GLES20.glBlendFunc(GLES20.GL_ONE, GLES20.GL_ONE); - break; - case AlphaAdditive: - GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE); - break; - case Color: - GLES20.glBlendFunc(GLES20.GL_ONE, GLES20.GL_ONE_MINUS_SRC_COLOR); - break; - case Alpha: - GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); - break; - case PremultAlpha: - GLES20.glBlendFunc(GLES20.GL_ONE, GLES20.GL_ONE_MINUS_SRC_ALPHA); - break; - case Modulate: - GLES20.glBlendFunc(GLES20.GL_DST_COLOR, GLES20.GL_ZERO); - break; - case ModulateX2: - GLES20.glBlendFunc(GLES20.GL_DST_COLOR, GLES20.GL_SRC_COLOR); - break; - case Screen: - GLES20.glBlendFunc(GLES20.GL_ONE, GLES20.GL_ONE_MINUS_SRC_COLOR); - break; - case Exclusion: - GLES20.glBlendFunc(GLES20.GL_ONE_MINUS_DST_COLOR, GLES20.GL_ONE_MINUS_SRC_COLOR); - break; - default: - throw new UnsupportedOperationException("Unrecognized blend mode: " - + state.getBlendMode()); - } - RendererUtil.checkGLError(); - } - context.blendMode = state.getBlendMode(); - } - } - - /*********************************************************************\ - |* Camera and World transforms *| - \*********************************************************************/ - public void setViewPort(int x, int y, int w, int h) { - if (x != vpX || vpY != y || vpW != w || vpH != h) { - GLES20.glViewport(x, y, w, h); - RendererUtil.checkGLError(); - - vpX = x; - vpY = y; - vpW = w; - vpH = h; - } - } - - public void setClipRect(int x, int y, int width, int height) { - if (!context.clipRectEnabled) { - GLES20.glEnable(GLES20.GL_SCISSOR_TEST); - RendererUtil.checkGLError(); - context.clipRectEnabled = true; - } - if (clipX != x || clipY != y || clipW != width || clipH != height) { - GLES20.glScissor(x, y, width, height); - RendererUtil.checkGLError(); - clipX = x; - clipY = y; - clipW = width; - clipH = height; - } - } - - public void clearClipRect() { - if (context.clipRectEnabled) { - GLES20.glDisable(GLES20.GL_SCISSOR_TEST); - RendererUtil.checkGLError(); - context.clipRectEnabled = false; - - clipX = 0; - clipY = 0; - clipW = 0; - clipH = 0; - } - } - - public void postFrame() { - RendererUtil.checkGLErrorForced(); - - objManager.deleteUnused(this); - } - - /*********************************************************************\ - |* Shaders *| - \*********************************************************************/ - protected void updateUniformLocation(Shader shader, Uniform uniform) { - stringBuf.setLength(0); - stringBuf.append(uniform.getName()).append('\0'); - updateNameBuffer(); - int loc = GLES20.glGetUniformLocation(shader.getId(), uniform.getName()); - RendererUtil.checkGLError(); - - if (loc < 0) { - uniform.setLocation(-1); - // uniform is not declared in shader - } else { - uniform.setLocation(loc); - } - } - - protected void bindProgram(Shader shader) { - int shaderId = shader.getId(); - if (context.boundShaderProgram != shaderId) { - GLES20.glUseProgram(shaderId); - RendererUtil.checkGLError(); - - statistics.onShaderUse(shader, true); - boundShader = shader; - context.boundShaderProgram = shaderId; - } else { - statistics.onShaderUse(shader, false); - } - } - - protected void updateUniform(Shader shader, Uniform uniform) { - assert uniform.getName() != null; - assert shader.getId() > 0; - - bindProgram(shader); - - int loc = uniform.getLocation(); - if (loc == -1) { - return; - } - - if (loc == -2) { - // get uniform location - updateUniformLocation(shader, uniform); - if (uniform.getLocation() == -1) { - // not declared, ignore - uniform.clearUpdateNeeded(); - return; - } - loc = uniform.getLocation(); - } - - if (uniform.getVarType() == null) { - // removed logging the warning to avoid flooding the log - // (LWJGL also doesn't post a warning) - //logger.log(Level.FINEST, "Uniform value is not set yet. Shader: {0}, Uniform: {1}", - // new Object[]{shader.toString(), uniform.toString()}); - return; // value not set yet.. - } - - statistics.onUniformSet(); - - uniform.clearUpdateNeeded(); - FloatBuffer fb; - IntBuffer ib; - switch (uniform.getVarType()) { - case Float: - Float f = (Float) uniform.getValue(); - GLES20.glUniform1f(loc, f.floatValue()); - break; - case Vector2: - Vector2f v2 = (Vector2f) uniform.getValue(); - GLES20.glUniform2f(loc, v2.getX(), v2.getY()); - break; - case Vector3: - Vector3f v3 = (Vector3f) uniform.getValue(); - GLES20.glUniform3f(loc, v3.getX(), v3.getY(), v3.getZ()); - break; - case Vector4: - Object val = uniform.getValue(); - if (val instanceof ColorRGBA) { - ColorRGBA c = (ColorRGBA) val; - GLES20.glUniform4f(loc, c.r, c.g, c.b, c.a); - } else if (val instanceof Vector4f) { - Vector4f c = (Vector4f) val; - GLES20.glUniform4f(loc, c.x, c.y, c.z, c.w); - } else { - Quaternion c = (Quaternion) uniform.getValue(); - GLES20.glUniform4f(loc, c.getX(), c.getY(), c.getZ(), c.getW()); - } - break; - case Boolean: - Boolean b = (Boolean) uniform.getValue(); - GLES20.glUniform1i(loc, b.booleanValue() ? GLES20.GL_TRUE : GLES20.GL_FALSE); - break; - case Matrix3: - fb = (FloatBuffer) uniform.getValue(); - assert fb.remaining() == 9; - GLES20.glUniformMatrix3fv(loc, 1, false, fb); - break; - case Matrix4: - fb = (FloatBuffer) uniform.getValue(); - assert fb.remaining() == 16; - GLES20.glUniformMatrix4fv(loc, 1, false, fb); - break; - case IntArray: - ib = (IntBuffer) uniform.getValue(); - GLES20.glUniform1iv(loc, ib.limit(), ib); - break; - case FloatArray: - fb = (FloatBuffer) uniform.getValue(); - GLES20.glUniform1fv(loc, fb.limit(), fb); - break; - case Vector2Array: - fb = (FloatBuffer) uniform.getValue(); - GLES20.glUniform2fv(loc, fb.limit() / 2, fb); - break; - case Vector3Array: - fb = (FloatBuffer) uniform.getValue(); - GLES20.glUniform3fv(loc, fb.limit() / 3, fb); - break; - case Vector4Array: - fb = (FloatBuffer) uniform.getValue(); - GLES20.glUniform4fv(loc, fb.limit() / 4, fb); - break; - case Matrix4Array: - fb = (FloatBuffer) uniform.getValue(); - GLES20.glUniformMatrix4fv(loc, fb.limit() / 16, false, fb); - break; - case Int: - Integer i = (Integer) uniform.getValue(); - GLES20.glUniform1i(loc, i.intValue()); - break; - default: - throw new UnsupportedOperationException("Unsupported uniform type: " + uniform.getVarType()); - } - RendererUtil.checkGLError(); - } - - protected void updateShaderUniforms(Shader shader) { - ListMap uniforms = shader.getUniformMap(); - for (int i = 0; i < uniforms.size(); i++) { - Uniform uniform = uniforms.getValue(i); - if (uniform.isUpdateNeeded()) { - updateUniform(shader, uniform); - } - } - } - - protected void resetUniformLocations(Shader shader) { - ListMap uniforms = shader.getUniformMap(); - for (int i = 0; i < uniforms.size(); i++) { - Uniform uniform = uniforms.getValue(i); - uniform.reset(); // e.g check location again - } - } - - /* - * (Non-javadoc) - * Only used for fixed-function. Ignored. - */ - public void setLighting(LightList list) { - } - - public int convertShaderType(ShaderType type) { - switch (type) { - case Fragment: - return GLES20.GL_FRAGMENT_SHADER; - case Vertex: - return GLES20.GL_VERTEX_SHADER; -// case Geometry: -// return ARBGeometryShader4.GL_GEOMETRY_SHADER_ARB; - default: - throw new RuntimeException("Unrecognized shader type."); - } - } - - public void updateShaderSourceData(ShaderSource source) { - int id = source.getId(); - if (id == -1) { - // Create id - id = GLES20.glCreateShader(convertShaderType(source.getType())); - RendererUtil.checkGLError(); - - if (id <= 0) { - throw new RendererException("Invalid ID received when trying to create shader."); - } - source.setId(id); - } - - if (!source.getLanguage().equals("GLSL100")) { - throw new RendererException("This shader cannot run in OpenGL ES. " - + "Only GLSL 1.0 shaders are supported."); - } - - // upload shader source - // merge the defines and source code - byte[] definesCodeData = source.getDefines().getBytes(); - byte[] sourceCodeData = source.getSource().getBytes(); - ByteBuffer codeBuf = BufferUtils.createByteBuffer(definesCodeData.length - + sourceCodeData.length); - codeBuf.put(definesCodeData); - codeBuf.put(sourceCodeData); - codeBuf.flip(); - - if (powerVr && source.getType() == ShaderType.Vertex) { - // XXX: This is to fix a bug in old PowerVR, remove - // when no longer applicable. - GLES20.glShaderSource( - id, source.getDefines() - + source.getSource()); - } else { - String precision =""; - if (source.getType() == ShaderType.Fragment) { - precision = "precision mediump float;\n"; - } - GLES20.glShaderSource( - id, - precision - +source.getDefines() - + source.getSource()); - } -// int range[] = new int[2]; -// int precision[] = new int[1]; -// GLES20.glGetShaderPrecisionFormat(GLES20.GL_VERTEX_SHADER, GLES20.GL_HIGH_FLOAT, range, 0, precision, 0); -// System.out.println("PRECISION HIGH FLOAT VERTEX"); -// System.out.println("range "+range[0]+"," +range[1]); -// System.out.println("precision "+precision[0]); - - GLES20.glCompileShader(id); - RendererUtil.checkGLError(); - - GLES20.glGetShaderiv(id, GLES20.GL_COMPILE_STATUS, intBuf1); - RendererUtil.checkGLError(); - - boolean compiledOK = intBuf1.get(0) == GLES20.GL_TRUE; - String infoLog = null; - - if (VALIDATE_SHADER || !compiledOK) { - // even if compile succeeded, check - // log for warnings - GLES20.glGetShaderiv(id, GLES20.GL_INFO_LOG_LENGTH, intBuf1); - RendererUtil.checkGLError(); - infoLog = GLES20.glGetShaderInfoLog(id); - } - - if (compiledOK) { - if (infoLog != null) { - logger.log(Level.FINE, "compile success: {0}, {1}", new Object[]{source.getName(), infoLog}); - } else { - logger.log(Level.FINE, "compile success: {0}", source.getName()); - } - source.clearUpdateNeeded(); - } else { - logger.log(Level.WARNING, "Bad compile of:\n{0}", - new Object[]{ShaderDebug.formatShaderSource(stringBuf.toString() + source.getDefines() + source.getSource())}); - if (infoLog != null) { - throw new RendererException("compile error in: " + source + "\n" + infoLog); - } else { - throw new RendererException("compile error in: " + source + "\nerror: "); - } - } - } - - public void updateShaderData(Shader shader) { - int id = shader.getId(); - boolean needRegister = false; - if (id == -1) { - // create program - id = GLES20.glCreateProgram(); - RendererUtil.checkGLError(); - - if (id <= 0) { - throw new RendererException("Invalid ID received when trying to create shader program."); - } - - shader.setId(id); - needRegister = true; - } - - for (ShaderSource source : shader.getSources()) { - if (source.isUpdateNeeded()) { - updateShaderSourceData(source); - } - - GLES20.glAttachShader(id, source.getId()); - RendererUtil.checkGLError(); - } - - // link shaders to program - GLES20.glLinkProgram(id); - RendererUtil.checkGLError(); - - GLES20.glGetProgramiv(id, GLES20.GL_LINK_STATUS, intBuf1); - RendererUtil.checkGLError(); - - boolean linkOK = intBuf1.get(0) == GLES20.GL_TRUE; - String infoLog = null; - - if (VALIDATE_SHADER || !linkOK) { - GLES20.glGetProgramiv(id, GLES20.GL_INFO_LOG_LENGTH, intBuf1); - RendererUtil.checkGLError(); - - int length = intBuf1.get(0); - if (length > 3) { - // get infos - infoLog = GLES20.glGetProgramInfoLog(id); - RendererUtil.checkGLError(); - } - } - - if (linkOK) { - if (infoLog != null) { - logger.log(Level.FINE, "shader link success. \n{0}", infoLog); - } else { - logger.fine("shader link success"); - } - shader.clearUpdateNeeded(); - if (needRegister) { - // Register shader for clean up if it was created in this method. - objManager.registerObject(shader); - statistics.onNewShader(); - } else { - // OpenGL spec: uniform locations may change after re-link - resetUniformLocations(shader); - } - } else { - if (infoLog != null) { - throw new RendererException("Shader link failure, shader: " + shader + "\n" + infoLog); - } else { - throw new RendererException("Shader link failure, shader: " + shader + "\ninfo: "); - } - } - } - - public void setShader(Shader shader) { - if (shader == null) { - throw new IllegalArgumentException("Shader cannot be null"); - } else { - if (shader.isUpdateNeeded()) { - updateShaderData(shader); - } - - // NOTE: might want to check if any of the - // sources need an update? - - assert shader.getId() > 0; - - updateShaderUniforms(shader); - bindProgram(shader); - } - } - - public void deleteShaderSource(ShaderSource source) { - if (source.getId() < 0) { - logger.warning("Shader source is not uploaded to GPU, cannot delete."); - return; - } - - source.clearUpdateNeeded(); - - GLES20.glDeleteShader(source.getId()); - RendererUtil.checkGLError(); - - source.resetObject(); - } - - public void deleteShader(Shader shader) { - if (shader.getId() == -1) { - logger.warning("Shader is not uploaded to GPU, cannot delete."); - return; - } - - for (ShaderSource source : shader.getSources()) { - if (source.getId() != -1) { - GLES20.glDetachShader(shader.getId(), source.getId()); - RendererUtil.checkGLError(); - - deleteShaderSource(source); - } - } - - GLES20.glDeleteProgram(shader.getId()); - RendererUtil.checkGLError(); - - statistics.onDeleteShader(); - shader.resetObject(); - } - - private int convertTestFunction(RenderState.TestFunction testFunc) { - switch (testFunc) { - case Never: - return GLES20.GL_NEVER; - case Less: - return GLES20.GL_LESS; - case LessOrEqual: - return GLES20.GL_LEQUAL; - case Greater: - return GLES20.GL_GREATER; - case GreaterOrEqual: - return GLES20.GL_GEQUAL; - case Equal: - return GLES20.GL_EQUAL; - case NotEqual: - return GLES20.GL_NOTEQUAL; - case Always: - return GLES20.GL_ALWAYS; - default: - throw new UnsupportedOperationException("Unrecognized test function: " + testFunc); - } - } - - /*********************************************************************\ - |* Framebuffers *| - \*********************************************************************/ - - public void copyFrameBuffer(FrameBuffer src, FrameBuffer dst, boolean copyDepth) { - throw new RendererException("Copy framebuffer not implemented yet."); - -// if (GLContext.getCapabilities().GL_EXT_framebuffer_blit) { -// int srcX0 = 0; -// int srcY0 = 0; -// int srcX1 = 0; -// int srcY1 = 0; -// -// int dstX0 = 0; -// int dstY0 = 0; -// int dstX1 = 0; -// int dstY1 = 0; -// -// int prevFBO = context.boundFBO; -// -// if (mainFbOverride != null) { -// if (src == null) { -// src = mainFbOverride; -// } -// if (dst == null) { -// dst = mainFbOverride; -// } -// } -// -// if (src != null && src.isUpdateNeeded()) { -// updateFrameBuffer(src); -// } -// -// if (dst != null && dst.isUpdateNeeded()) { -// updateFrameBuffer(dst); -// } -// -// if (src == null) { -// GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0); -// srcX0 = vpX; -// srcY0 = vpY; -// srcX1 = vpX + vpW; -// srcY1 = vpY + vpH; -// } else { -// GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, src.getId()); -// srcX1 = src.getWidth(); -// srcY1 = src.getHeight(); -// } -// if (dst == null) { -// GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0); -// dstX0 = vpX; -// dstY0 = vpY; -// dstX1 = vpX + vpW; -// dstY1 = vpY + vpH; -// } else { -// GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, dst.getId()); -// dstX1 = dst.getWidth(); -// dstY1 = dst.getHeight(); -// } -// -// -// int mask = GL_COLOR_BUFFER_BIT; -// if (copyDepth) { -// mask |= GL_DEPTH_BUFFER_BIT; -// } -// GLES20.glBlitFramebufferEXT(srcX0, srcY0, srcX1, srcY1, -// dstX0, dstY0, dstX1, dstY1, mask, -// GL_NEAREST); -// -// -// GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, prevFBO); -// try { -// checkFrameBufferError(); -// } catch (IllegalStateException ex) { -// logger.log(Level.SEVERE, "Source FBO:\n{0}", src); -// logger.log(Level.SEVERE, "Dest FBO:\n{0}", dst); -// throw ex; -// } -// } else { -// throw new RendererException("EXT_framebuffer_blit required."); -// // TODO: support non-blit copies? -// } - } - - private void checkFrameBufferStatus(FrameBuffer fb) { - try { - checkFrameBufferError(); - } catch (IllegalStateException ex) { - logger.log(Level.SEVERE, "=== jMonkeyEngine FBO State ===\n{0}", fb); - printRealFrameBufferInfo(fb); - throw ex; - } - } - - private void checkFrameBufferError() { - int status = GLES20.glCheckFramebufferStatus(GLES20.GL_FRAMEBUFFER); - switch (status) { - case GLES20.GL_FRAMEBUFFER_COMPLETE: - break; - case GLES20.GL_FRAMEBUFFER_UNSUPPORTED: - //Choose different formats - throw new IllegalStateException("Framebuffer object format is " - + "unsupported by the video hardware."); - case GLES20.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: - throw new IllegalStateException("Framebuffer has erronous attachment."); - case GLES20.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: - throw new IllegalStateException("Framebuffer doesn't have any renderbuffers attached."); - case GLES20.GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: - throw new IllegalStateException("Framebuffer attachments must have same dimensions."); -// case GLES20.GL_FRAMEBUFFER_INCOMPLETE_FORMATS: -// throw new IllegalStateException("Framebuffer attachments must have same formats."); -// case GLES20.GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: -// throw new IllegalStateException("Incomplete draw buffer."); -// case GLES20.GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT: -// throw new IllegalStateException("Incomplete read buffer."); -// case GLES20.GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT: -// throw new IllegalStateException("Incomplete multisample buffer."); - default: - //Programming error; will fail on all hardware - throw new IllegalStateException("Some video driver error " - + "or programming error occured. " - + "Framebuffer object status is invalid: " + status); - } - } - - private void printRealRenderBufferInfo(FrameBuffer fb, RenderBuffer rb, String name) { - System.out.println("== Renderbuffer " + name + " =="); - System.out.println("RB ID: " + rb.getId()); - System.out.println("Is proper? " + GLES20.glIsRenderbuffer(rb.getId())); - - int attachment = convertAttachmentSlot(rb.getSlot()); - - intBuf16.clear(); - GLES20.glGetFramebufferAttachmentParameteriv(GLES20.GL_FRAMEBUFFER, - attachment, GLES20.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, intBuf16); - int type = intBuf16.get(0); - - intBuf16.clear(); - GLES20.glGetFramebufferAttachmentParameteriv(GLES20.GL_FRAMEBUFFER, - attachment, GLES20.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, intBuf16); - int rbName = intBuf16.get(0); - - switch (type) { - case GLES20.GL_NONE: - System.out.println("Type: None"); - break; - case GLES20.GL_TEXTURE: - System.out.println("Type: Texture"); - break; - case GLES20.GL_RENDERBUFFER: - System.out.println("Type: Buffer"); - System.out.println("RB ID: " + rbName); - break; - } - - - - } - - private void printRealFrameBufferInfo(FrameBuffer fb) { -// boolean doubleBuffer = GLES20.glGetBooleanv(GLES20.GL_DOUBLEBUFFER); - boolean doubleBuffer = false; // FIXME -// String drawBuf = getTargetBufferName(glGetInteger(GL_DRAW_BUFFER)); -// String readBuf = getTargetBufferName(glGetInteger(GL_READ_BUFFER)); - - int fbId = fb.getId(); - intBuf16.clear(); -// int curDrawBinding = GLES20.glGetIntegerv(GLES20.GL_DRAW_FRAMEBUFFER_BINDING); -// int curReadBinding = glGetInteger(ARBFramebufferObject.GL_READ_FRAMEBUFFER_BINDING); - - System.out.println("=== OpenGL FBO State ==="); - System.out.println("Context doublebuffered? " + doubleBuffer); - System.out.println("FBO ID: " + fbId); - System.out.println("Is proper? " + GLES20.glIsFramebuffer(fbId)); -// System.out.println("Is bound to draw? " + (fbId == curDrawBinding)); -// System.out.println("Is bound to read? " + (fbId == curReadBinding)); -// System.out.println("Draw buffer: " + drawBuf); -// System.out.println("Read buffer: " + readBuf); - - if (context.boundFBO != fbId) { - GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, fbId); - context.boundFBO = fbId; - } - - if (fb.getDepthBuffer() != null) { - printRealRenderBufferInfo(fb, fb.getDepthBuffer(), "Depth"); - } - for (int i = 0; i < fb.getNumColorBuffers(); i++) { - printRealRenderBufferInfo(fb, fb.getColorBuffer(i), "Color" + i); - } - } - - private void updateRenderBuffer(FrameBuffer fb, RenderBuffer rb) { - int id = rb.getId(); - if (id == -1) { - GLES20.glGenRenderbuffers(1, intBuf1); - RendererUtil.checkGLError(); - - id = intBuf1.get(0); - rb.setId(id); - } - - if (context.boundRB != id) { - GLES20.glBindRenderbuffer(GLES20.GL_RENDERBUFFER, id); - RendererUtil.checkGLError(); - - context.boundRB = id; - } - - if (fb.getWidth() > maxRBSize || fb.getHeight() > maxRBSize) { - throw new RendererException("Resolution " + fb.getWidth() - + ":" + fb.getHeight() + " is not supported."); - } - - AndroidGLImageFormat imageFormat = TextureUtil.getImageFormat(rb.getFormat(), true); - if (imageFormat.renderBufferStorageFormat == 0) { - throw new RendererException("The format '" + rb.getFormat() + "' cannot be used for renderbuffers."); - } - -// if (fb.getSamples() > 1 && GLContext.getCapabilities().GL_EXT_framebuffer_multisample) { - if (fb.getSamples() > 1) { -// // FIXME - throw new RendererException("Multisample FrameBuffer is not supported yet."); -// int samples = fb.getSamples(); -// if (maxFBOSamples < samples) { -// samples = maxFBOSamples; -// } -// glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, -// samples, -// glFmt.internalFormat, -// fb.getWidth(), -// fb.getHeight()); - } else { - GLES20.glRenderbufferStorage(GLES20.GL_RENDERBUFFER, - imageFormat.renderBufferStorageFormat, - fb.getWidth(), - fb.getHeight()); - - RendererUtil.checkGLError(); - } - } - - private int convertAttachmentSlot(int attachmentSlot) { - // can also add support for stencil here - if (attachmentSlot == FrameBuffer.SLOT_DEPTH) { - return GLES20.GL_DEPTH_ATTACHMENT; -// if (attachmentSlot == FrameBuffer.SLOT_DEPTH_STENCIL) { -// return GLES30.GL_DEPTH_STENCIL_ATTACHMENT; - } else if (attachmentSlot == 0) { - return GLES20.GL_COLOR_ATTACHMENT0; - } else { - throw new UnsupportedOperationException("Android does not support multiple color attachments to an FBO"); - } - } - - public void updateRenderTexture(FrameBuffer fb, RenderBuffer rb) { - Texture tex = rb.getTexture(); - Image image = tex.getImage(); - if (image.isUpdateNeeded()) { - updateTexImageData(image, tex.getType()); - - // NOTE: For depth textures, sets nearest/no-mips mode - // Required to fix "framebuffer unsupported" - // for old NVIDIA drivers! - setupTextureParams(tex); - } - - GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, - convertAttachmentSlot(rb.getSlot()), - convertTextureType(tex.getType()), - image.getId(), - 0); - - RendererUtil.checkGLError(); - } - - public void updateFrameBufferAttachment(FrameBuffer fb, RenderBuffer rb) { - boolean needAttach; - if (rb.getTexture() == null) { - // if it hasn't been created yet, then attach is required. - needAttach = rb.getId() == -1; - updateRenderBuffer(fb, rb); - } else { - needAttach = false; - updateRenderTexture(fb, rb); - } - if (needAttach) { - GLES20.glFramebufferRenderbuffer(GLES20.GL_FRAMEBUFFER, - convertAttachmentSlot(rb.getSlot()), - GLES20.GL_RENDERBUFFER, - rb.getId()); - - RendererUtil.checkGLError(); - } - } - - public void updateFrameBuffer(FrameBuffer fb) { - int id = fb.getId(); - if (id == -1) { - intBuf1.clear(); - // create FBO - GLES20.glGenFramebuffers(1, intBuf1); - RendererUtil.checkGLError(); - - id = intBuf1.get(0); - fb.setId(id); - objManager.registerObject(fb); - - statistics.onNewFrameBuffer(); - } - - if (context.boundFBO != id) { - GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, id); - RendererUtil.checkGLError(); - - // binding an FBO automatically sets draw buf to GL_COLOR_ATTACHMENT0 - context.boundDrawBuf = 0; - context.boundFBO = id; - } - - FrameBuffer.RenderBuffer depthBuf = fb.getDepthBuffer(); - if (depthBuf != null) { - updateFrameBufferAttachment(fb, depthBuf); - } - - for (int i = 0; i < fb.getNumColorBuffers(); i++) { - FrameBuffer.RenderBuffer colorBuf = fb.getColorBuffer(i); - updateFrameBufferAttachment(fb, colorBuf); - } - - fb.clearUpdateNeeded(); - } - - public void setMainFrameBufferOverride(FrameBuffer fb){ - mainFbOverride = fb; - } - - public void setFrameBuffer(FrameBuffer fb) { - if (fb == null && mainFbOverride != null) { - fb = mainFbOverride; - } - - if (lastFb == fb) { - if (fb == null || !fb.isUpdateNeeded()) { - return; - } - } - - // generate mipmaps for last FB if needed - if (lastFb != null) { - for (int i = 0; i < lastFb.getNumColorBuffers(); i++) { - RenderBuffer rb = lastFb.getColorBuffer(i); - Texture tex = rb.getTexture(); - if (tex != null - && tex.getMinFilter().usesMipMapLevels()) { - setTexture(0, rb.getTexture()); - -// int textureType = convertTextureType(tex.getType(), tex.getImage().getMultiSamples(), rb.getFace()); - int textureType = convertTextureType(tex.getType()); - GLES20.glGenerateMipmap(textureType); - RendererUtil.checkGLError(); - } - } - } - - if (fb == null) { - // unbind any fbos - if (context.boundFBO != 0) { - GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0); - RendererUtil.checkGLError(); - - statistics.onFrameBufferUse(null, true); - - context.boundFBO = 0; - } - - /* - // select back buffer - if (context.boundDrawBuf != -1) { - glDrawBuffer(initialDrawBuf); - context.boundDrawBuf = -1; - } - if (context.boundReadBuf != -1) { - glReadBuffer(initialReadBuf); - context.boundReadBuf = -1; - } - */ - - lastFb = null; - } else { - if (fb.getNumColorBuffers() == 0 && fb.getDepthBuffer() == null) { - throw new IllegalArgumentException("The framebuffer: " + fb - + "\nDoesn't have any color/depth buffers"); - } - - if (fb.isUpdateNeeded()) { - updateFrameBuffer(fb); - } - - if (context.boundFBO != fb.getId()) { - GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, fb.getId()); - RendererUtil.checkGLError(); - - statistics.onFrameBufferUse(fb, true); - - // update viewport to reflect framebuffer's resolution - setViewPort(0, 0, fb.getWidth(), fb.getHeight()); - - context.boundFBO = fb.getId(); - } else { - statistics.onFrameBufferUse(fb, false); - } - if (fb.getNumColorBuffers() == 0) { -// // make sure to select NONE as draw buf -// // no color buffer attached. select NONE - if (context.boundDrawBuf != -2) { -// glDrawBuffer(GL_NONE); - context.boundDrawBuf = -2; - } - if (context.boundReadBuf != -2) { -// glReadBuffer(GL_NONE); - context.boundReadBuf = -2; - } - } else { - if (fb.getNumColorBuffers() > maxFBOAttachs) { - throw new RendererException("Framebuffer has more color " - + "attachments than are supported" - + " by the video hardware!"); - } - if (fb.isMultiTarget()) { - if (fb.getNumColorBuffers() > maxMRTFBOAttachs) { - throw new RendererException("Framebuffer has more" - + " multi targets than are supported" - + " by the video hardware!"); - } - - if (context.boundDrawBuf != 100 + fb.getNumColorBuffers()) { - intBuf16.clear(); - for (int i = 0; i < fb.getNumColorBuffers(); i++) { - intBuf16.put(GLES20.GL_COLOR_ATTACHMENT0 + i); - } - - intBuf16.flip(); -// glDrawBuffers(intBuf16); - context.boundDrawBuf = 100 + fb.getNumColorBuffers(); - } - } else { - RenderBuffer rb = fb.getColorBuffer(fb.getTargetIndex()); - // select this draw buffer - if (context.boundDrawBuf != rb.getSlot()) { - GLES20.glActiveTexture(convertAttachmentSlot(rb.getSlot())); - RendererUtil.checkGLError(); - - context.boundDrawBuf = rb.getSlot(); - } - } - } - - assert fb.getId() >= 0; - assert context.boundFBO == fb.getId(); - - lastFb = fb; - - checkFrameBufferStatus(fb); - } - } - - /** - * Reads the Color Buffer from OpenGL and stores into the ByteBuffer. - * Make sure to call setViewPort with the appropriate viewport size before - * calling readFrameBuffer. - * @param fb FrameBuffer - * @param byteBuf ByteBuffer to store the Color Buffer from OpenGL - */ - public void readFrameBuffer(FrameBuffer fb, ByteBuffer byteBuf) { - if (fb != null) { - RenderBuffer rb = fb.getColorBuffer(); - if (rb == null) { - throw new IllegalArgumentException("Specified framebuffer" - + " does not have a colorbuffer"); - } - - setFrameBuffer(fb); - } else { - setFrameBuffer(null); - } - - GLES20.glReadPixels(vpX, vpY, vpW, vpH, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, byteBuf); - RendererUtil.checkGLError(); - } - - private void deleteRenderBuffer(FrameBuffer fb, RenderBuffer rb) { - intBuf1.put(0, rb.getId()); - GLES20.glDeleteRenderbuffers(1, intBuf1); - RendererUtil.checkGLError(); - } - - public void deleteFrameBuffer(FrameBuffer fb) { - if (fb.getId() != -1) { - if (context.boundFBO == fb.getId()) { - GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0); - RendererUtil.checkGLError(); - - context.boundFBO = 0; - } - - if (fb.getDepthBuffer() != null) { - deleteRenderBuffer(fb, fb.getDepthBuffer()); - } - if (fb.getColorBuffer() != null) { - deleteRenderBuffer(fb, fb.getColorBuffer()); - } - - intBuf1.put(0, fb.getId()); - GLES20.glDeleteFramebuffers(1, intBuf1); - RendererUtil.checkGLError(); - - fb.resetObject(); - - statistics.onDeleteFrameBuffer(); - } - } - - /*********************************************************************\ - |* Textures *| - \*********************************************************************/ - private int convertTextureType(Texture.Type type) { - switch (type) { - case TwoDimensional: - return GLES20.GL_TEXTURE_2D; - // case TwoDimensionalArray: - // return EXTTextureArray.GL_TEXTURE_2D_ARRAY_EXT; -// case ThreeDimensional: - // return GLES20.GL_TEXTURE_3D; - case CubeMap: - return GLES20.GL_TEXTURE_CUBE_MAP; - default: - throw new UnsupportedOperationException("Unknown texture type: " + type); - } - } - - private int convertMagFilter(Texture.MagFilter filter) { - switch (filter) { - case Bilinear: - return GLES20.GL_LINEAR; - case Nearest: - return GLES20.GL_NEAREST; - default: - throw new UnsupportedOperationException("Unknown mag filter: " + filter); - } - } - - private int convertMinFilter(Texture.MinFilter filter) { - switch (filter) { - case Trilinear: - return GLES20.GL_LINEAR_MIPMAP_LINEAR; - case BilinearNearestMipMap: - return GLES20.GL_LINEAR_MIPMAP_NEAREST; - case NearestLinearMipMap: - return GLES20.GL_NEAREST_MIPMAP_LINEAR; - case NearestNearestMipMap: - return GLES20.GL_NEAREST_MIPMAP_NEAREST; - case BilinearNoMipMaps: - return GLES20.GL_LINEAR; - case NearestNoMipMaps: - return GLES20.GL_NEAREST; - default: - throw new UnsupportedOperationException("Unknown min filter: " + filter); - } - } - - private int convertWrapMode(Texture.WrapMode mode) { - switch (mode) { - case BorderClamp: - case Clamp: - case EdgeClamp: - return GLES20.GL_CLAMP_TO_EDGE; - case Repeat: - return GLES20.GL_REPEAT; - case MirroredRepeat: - return GLES20.GL_MIRRORED_REPEAT; - default: - throw new UnsupportedOperationException("Unknown wrap mode: " + mode); - } - } - - /** - * setupTextureParams sets the OpenGL context texture parameters - * @param tex the Texture to set the texture parameters from - */ - private void setupTextureParams(Texture tex) { - int target = convertTextureType(tex.getType()); - - // filter things - int minFilter = convertMinFilter(tex.getMinFilter()); - int magFilter = convertMagFilter(tex.getMagFilter()); - - GLES20.glTexParameteri(target, GLES20.GL_TEXTURE_MIN_FILTER, minFilter); - GLES20.glTexParameteri(target, GLES20.GL_TEXTURE_MAG_FILTER, magFilter); - RendererUtil.checkGLError(); - - /* - if (tex.getAnisotropicFilter() > 1){ - - if (GLContext.getCapabilities().GL_EXT_texture_filter_anisotropic){ - glTexParameterf(target, - EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT, - tex.getAnisotropicFilter()); - } - - } - */ - // repeat modes - - switch (tex.getType()) { - case ThreeDimensional: - case CubeMap: // cubemaps use 3D coords - // GL_TEXTURE_WRAP_R is not available in api 8 - //GLES20.glTexParameteri(target, GLES20.GL_TEXTURE_WRAP_R, convertWrapMode(tex.getWrap(WrapAxis.R))); - case TwoDimensional: - case TwoDimensionalArray: - GLES20.glTexParameteri(target, GLES20.GL_TEXTURE_WRAP_T, convertWrapMode(tex.getWrap(WrapAxis.T))); - - // fall down here is intentional.. -// case OneDimensional: - GLES20.glTexParameteri(target, GLES20.GL_TEXTURE_WRAP_S, convertWrapMode(tex.getWrap(WrapAxis.S))); - - RendererUtil.checkGLError(); - break; - default: - throw new UnsupportedOperationException("Unknown texture type: " + tex.getType()); - } - - // R to Texture compare mode -/* - if (tex.getShadowCompareMode() != Texture.ShadowCompareMode.Off){ - GLES20.glTexParameteri(target, GLES20.GL_TEXTURE_COMPARE_MODE, GLES20.GL_COMPARE_R_TO_TEXTURE); - GLES20.glTexParameteri(target, GLES20.GL_DEPTH_TEXTURE_MODE, GLES20.GL_INTENSITY); - if (tex.getShadowCompareMode() == Texture.ShadowCompareMode.GreaterOrEqual){ - GLES20.glTexParameteri(target, GLES20.GL_TEXTURE_COMPARE_FUNC, GLES20.GL_GEQUAL); - }else{ - GLES20.glTexParameteri(target, GLES20.GL_TEXTURE_COMPARE_FUNC, GLES20.GL_LEQUAL); - } - } - */ - } - - /** - * activates and binds the texture - * @param img - * @param type - */ - public void updateTexImageData(Image img, Texture.Type type) { - int texId = img.getId(); - if (texId == -1) { - // create texture - GLES20.glGenTextures(1, intBuf1); - RendererUtil.checkGLError(); - - texId = intBuf1.get(0); - img.setId(texId); - objManager.registerObject(img); - - statistics.onNewTexture(); - } - - // bind texture - int target = convertTextureType(type); - if (context.boundTextures[0] != img) { - if (context.boundTextureUnit != 0) { - GLES20.glActiveTexture(GLES20.GL_TEXTURE0); - RendererUtil.checkGLError(); - - context.boundTextureUnit = 0; - } - - GLES20.glBindTexture(target, texId); - RendererUtil.checkGLError(); - - context.boundTextures[0] = img; - } - - boolean needMips = false; - if (img.isGeneratedMipmapsRequired()) { - needMips = true; - img.setMipmapsGenerated(true); - } - - if (target == GLES20.GL_TEXTURE_CUBE_MAP) { - // Check max texture size before upload - if (img.getWidth() > maxCubeTexSize || img.getHeight() > maxCubeTexSize) { - throw new RendererException("Cannot upload cubemap " + img + ". The maximum supported cubemap resolution is " + maxCubeTexSize); - } - } else { - if (img.getWidth() > maxTexSize || img.getHeight() > maxTexSize) { - throw new RendererException("Cannot upload texture " + img + ". The maximum supported texture resolution is " + maxTexSize); - } - } - - if (target == GLES20.GL_TEXTURE_CUBE_MAP) { - // Upload a cube map / sky box - @SuppressWarnings("unchecked") - List bmps = (List) img.getEfficentData(); - if (bmps != null) { - // Native android bitmap - if (bmps.size() != 6) { - throw new UnsupportedOperationException("Invalid texture: " + img - + "Cubemap textures must contain 6 data units."); - } - for (int i = 0; i < 6; i++) { - TextureUtil.uploadTextureBitmap(GLES20.GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, bmps.get(i).getBitmap(), needMips); - bmps.get(i).notifyBitmapUploaded(); - } - } else { - // Standard jme3 image data - List data = img.getData(); - if (data.size() != 6) { - throw new UnsupportedOperationException("Invalid texture: " + img - + "Cubemap textures must contain 6 data units."); - } - for (int i = 0; i < 6; i++) { - TextureUtil.uploadTextureAny(img, GLES20.GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, i, needMips); - } - } - } else { - TextureUtil.uploadTextureAny(img, target, 0, needMips); - if (img.getEfficentData() instanceof AndroidImageInfo) { - AndroidImageInfo info = (AndroidImageInfo) img.getEfficentData(); - info.notifyBitmapUploaded(); - } - } - - img.clearUpdateNeeded(); - } - - public void setTexture(int unit, Texture tex) { - Image image = tex.getImage(); - if (image.isUpdateNeeded() || (image.isGeneratedMipmapsRequired() && !image.isMipmapsGenerated()) ) { - updateTexImageData(image, tex.getType()); - } - - int texId = image.getId(); - assert texId != -1; - - if (texId == -1) { - logger.warning("error: texture image has -1 id"); - } - - Image[] textures = context.boundTextures; - - int type = convertTextureType(tex.getType()); -// if (!context.textureIndexList.moveToNew(unit)) { -// if (context.boundTextureUnit != unit){ -// glActiveTexture(GL_TEXTURE0 + unit); -// context.boundTextureUnit = unit; -// } -// glEnable(type); -// } - - if (textures[unit] != image) { - if (context.boundTextureUnit != unit) { - GLES20.glActiveTexture(GLES20.GL_TEXTURE0 + unit); - context.boundTextureUnit = unit; - } - - GLES20.glBindTexture(type, texId); - RendererUtil.checkGLError(); - - textures[unit] = image; - - statistics.onTextureUse(tex.getImage(), true); - } else { - statistics.onTextureUse(tex.getImage(), false); - } - - setupTextureParams(tex); - } - - public void modifyTexture(Texture tex, Image pixels, int x, int y) { - setTexture(0, tex); - TextureUtil.uploadSubTexture(pixels, convertTextureType(tex.getType()), 0, x, y); - } - - public void clearTextureUnits() { - IDList textureList = context.textureIndexList; - Image[] textures = context.boundTextures; - for (int i = 0; i < textureList.oldLen; i++) { - int idx = textureList.oldList[i]; -// if (context.boundTextureUnit != idx){ -// glActiveTexture(GL_TEXTURE0 + idx); -// context.boundTextureUnit = idx; -// } -// glDisable(convertTextureType(textures[idx].getType())); - textures[idx] = null; - } - context.textureIndexList.copyNewToOld(); - } - - public void deleteImage(Image image) { - int texId = image.getId(); - if (texId != -1) { - intBuf1.put(0, texId); - intBuf1.position(0).limit(1); - - GLES20.glDeleteTextures(1, intBuf1); - RendererUtil.checkGLError(); - - image.resetObject(); - - statistics.onDeleteTexture(); - } - } - - /*********************************************************************\ - |* Vertex Buffers and Attributes *| - \*********************************************************************/ - private int convertUsage(Usage usage) { - switch (usage) { - case Static: - return GLES20.GL_STATIC_DRAW; - case Dynamic: - return GLES20.GL_DYNAMIC_DRAW; - case Stream: - return GLES20.GL_STREAM_DRAW; - default: - throw new RuntimeException("Unknown usage type."); - } - } - - private int convertVertexBufferFormat(Format format) { - switch (format) { - case Byte: - return GLES20.GL_BYTE; - case UnsignedByte: - return GLES20.GL_UNSIGNED_BYTE; - case Short: - return GLES20.GL_SHORT; - case UnsignedShort: - return GLES20.GL_UNSIGNED_SHORT; - case Int: - return GLES20.GL_INT; - case UnsignedInt: - return GLES20.GL_UNSIGNED_INT; - /* - case Half: - return NVHalfFloat.GL_HALF_FLOAT_NV; - // return ARBHalfFloatVertex.GL_HALF_FLOAT; - */ - case Float: - return GLES20.GL_FLOAT; -// case Double: -// return GLES20.GL_DOUBLE; - default: - throw new RuntimeException("Unknown buffer format."); - - } - } - - public void updateBufferData(VertexBuffer vb) { - int bufId = vb.getId(); - boolean created = false; - if (bufId == -1) { - // create buffer - GLES20.glGenBuffers(1, intBuf1); - RendererUtil.checkGLError(); - - bufId = intBuf1.get(0); - vb.setId(bufId); - objManager.registerObject(vb); - - created = true; - } - - // bind buffer - int target; - if (vb.getBufferType() == VertexBuffer.Type.Index) { - target = GLES20.GL_ELEMENT_ARRAY_BUFFER; - if (context.boundElementArrayVBO != bufId) { - GLES20.glBindBuffer(target, bufId); - RendererUtil.checkGLError(); - - context.boundElementArrayVBO = bufId; - } - } else { - target = GLES20.GL_ARRAY_BUFFER; - if (context.boundArrayVBO != bufId) { - GLES20.glBindBuffer(target, bufId); - RendererUtil.checkGLError(); - - context.boundArrayVBO = bufId; - } - } - - int usage = convertUsage(vb.getUsage()); - vb.getData().rewind(); - - // if (created || vb.hasDataSizeChanged()) { - // upload data based on format - int size = vb.getData().limit() * vb.getFormat().getComponentSize(); - - switch (vb.getFormat()) { - case Byte: - case UnsignedByte: - GLES20.glBufferData(target, size, (ByteBuffer) vb.getData(), usage); - RendererUtil.checkGLError(); - break; - case Short: - case UnsignedShort: - GLES20.glBufferData(target, size, (ShortBuffer) vb.getData(), usage); - RendererUtil.checkGLError(); - break; - case Int: - case UnsignedInt: - GLES20.glBufferData(target, size, (IntBuffer) vb.getData(), usage); - RendererUtil.checkGLError(); - break; - case Float: - GLES20.glBufferData(target, size, (FloatBuffer) vb.getData(), usage); - RendererUtil.checkGLError(); - break; - default: - throw new RuntimeException("Unknown buffer format."); - } -// } else { -// int size = vb.getData().limit() * vb.getFormat().getComponentSize(); -// -// switch (vb.getFormat()) { -// case Byte: -// case UnsignedByte: -// GLES20.glBufferSubData(target, 0, size, (ByteBuffer) vb.getData()); -// RendererUtil.checkGLError(); -// break; -// case Short: -// case UnsignedShort: -// GLES20.glBufferSubData(target, 0, size, (ShortBuffer) vb.getData()); -// RendererUtil.checkGLError(); -// break; -// case Int: -// case UnsignedInt: -// GLES20.glBufferSubData(target, 0, size, (IntBuffer) vb.getData()); -// RendererUtil.checkGLError(); -// break; -// case Float: -// GLES20.glBufferSubData(target, 0, size, (FloatBuffer) vb.getData()); -// RendererUtil.checkGLError(); -// break; -// default: -// throw new RuntimeException("Unknown buffer format."); -// } -// } - vb.clearUpdateNeeded(); - } - - public void deleteBuffer(VertexBuffer vb) { - int bufId = vb.getId(); - if (bufId != -1) { - // delete buffer - intBuf1.put(0, bufId); - intBuf1.position(0).limit(1); - - GLES20.glDeleteBuffers(1, intBuf1); - RendererUtil.checkGLError(); - - vb.resetObject(); - } - } - - public void clearVertexAttribs() { - IDList attribList = context.attribIndexList; - for (int i = 0; i < attribList.oldLen; i++) { - int idx = attribList.oldList[i]; - - GLES20.glDisableVertexAttribArray(idx); - RendererUtil.checkGLError(); - - context.boundAttribs[idx] = null; - } - context.attribIndexList.copyNewToOld(); - } - - public void setVertexAttrib(VertexBuffer vb, VertexBuffer idb) { - if (vb.getBufferType() == VertexBuffer.Type.Index) { - throw new IllegalArgumentException("Index buffers not allowed to be set to vertex attrib"); - } - - if (vb.isUpdateNeeded() && idb == null) { - updateBufferData(vb); - } - - int programId = context.boundShaderProgram; - if (programId > 0) { - Attribute attrib = boundShader.getAttribute(vb.getBufferType()); - int loc = attrib.getLocation(); - if (loc == -1) { - return; // not defined - } - - if (loc == -2) { -// stringBuf.setLength(0); -// stringBuf.append("in").append(vb.getBufferType().name()).append('\0'); -// updateNameBuffer(); - - String attributeName = "in" + vb.getBufferType().name(); - loc = GLES20.glGetAttribLocation(programId, attributeName); - RendererUtil.checkGLError(); - - // not really the name of it in the shader (inPosition\0) but - // the internal name of the enum (Position). - if (loc < 0) { - attrib.setLocation(-1); - return; // not available in shader. - } else { - attrib.setLocation(loc); - } - } - - VertexBuffer[] attribs = context.boundAttribs; - if (!context.attribIndexList.moveToNew(loc)) { - GLES20.glEnableVertexAttribArray(loc); - RendererUtil.checkGLError(); - //System.out.println("Enabled ATTRIB IDX: "+loc); - } - if (attribs[loc] != vb) { - // NOTE: Use id from interleaved buffer if specified - int bufId = idb != null ? idb.getId() : vb.getId(); - assert bufId != -1; - - if (bufId == -1) { - logger.warning("invalid buffer id"); - } - - if (context.boundArrayVBO != bufId) { - GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, bufId); - RendererUtil.checkGLError(); - - context.boundArrayVBO = bufId; - } - - vb.getData().rewind(); - - GLES20.glVertexAttribPointer(loc, - vb.getNumComponents(), - convertVertexBufferFormat(vb.getFormat()), - vb.isNormalized(), - vb.getStride(), - 0); - - RendererUtil.checkGLError(); - - attribs[loc] = vb; - } - } else { - throw new IllegalStateException("Cannot render mesh without shader bound"); - } - } - - public void setVertexAttrib(VertexBuffer vb) { - setVertexAttrib(vb, null); - } - - public void drawTriangleArray(Mesh.Mode mode, int count, int vertCount) { - /* if (count > 1){ - ARBDrawInstanced.glDrawArraysInstancedARB(convertElementMode(mode), 0, - vertCount, count); - }else{*/ - GLES20.glDrawArrays(convertElementMode(mode), 0, vertCount); - RendererUtil.checkGLError(); - /* - }*/ - } - - public void drawTriangleList(VertexBuffer indexBuf, Mesh mesh, int count) { - if (indexBuf.getBufferType() != VertexBuffer.Type.Index) { - throw new IllegalArgumentException("Only index buffers are allowed as triangle lists."); - } - - if (indexBuf.isUpdateNeeded()) { - updateBufferData(indexBuf); - } - - int bufId = indexBuf.getId(); - assert bufId != -1; - - if (bufId == -1) { - throw new RendererException("Invalid buffer ID"); - } - - if (context.boundElementArrayVBO != bufId) { - GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, bufId); - RendererUtil.checkGLError(); - - context.boundElementArrayVBO = bufId; - } - - int vertCount = mesh.getVertexCount(); - boolean useInstancing = count > 1 && caps.contains(Caps.MeshInstancing); - - Buffer indexData = indexBuf.getData(); - - if (indexBuf.getFormat() == Format.UnsignedInt) { - throw new RendererException("OpenGL ES does not support 32-bit index buffers." + - "Split your models to avoid going over 65536 vertices."); - } - - if (mesh.getMode() == Mode.Hybrid) { - int[] modeStart = mesh.getModeStart(); - int[] elementLengths = mesh.getElementLengths(); - - int elMode = convertElementMode(Mode.Triangles); - int fmt = convertVertexBufferFormat(indexBuf.getFormat()); - int elSize = indexBuf.getFormat().getComponentSize(); - int listStart = modeStart[0]; - int stripStart = modeStart[1]; - int fanStart = modeStart[2]; - int curOffset = 0; - for (int i = 0; i < elementLengths.length; i++) { - if (i == stripStart) { - elMode = convertElementMode(Mode.TriangleStrip); - } else if (i == fanStart) { - elMode = convertElementMode(Mode.TriangleStrip); - } - int elementLength = elementLengths[i]; - - if (useInstancing) { - //ARBDrawInstanced. - throw new IllegalArgumentException("instancing is not supported."); - /* - GLES20.glDrawElementsInstancedARB(elMode, - elementLength, - fmt, - curOffset, - count); - */ - } else { - indexBuf.getData().position(curOffset); - GLES20.glDrawElements(elMode, elementLength, fmt, indexBuf.getData()); - RendererUtil.checkGLError(); - /* - glDrawRangeElements(elMode, - 0, - vertCount, - elementLength, - fmt, - curOffset); - */ - } - - curOffset += elementLength * elSize; - } - } else { - if (useInstancing) { - throw new IllegalArgumentException("instancing is not supported."); - //ARBDrawInstanced. -/* - GLES20.glDrawElementsInstancedARB(convertElementMode(mesh.getMode()), - indexBuf.getData().limit(), - convertVertexBufferFormat(indexBuf.getFormat()), - 0, - count); - */ - } else { - indexData.rewind(); - GLES20.glDrawElements( - convertElementMode(mesh.getMode()), - indexBuf.getData().limit(), - convertVertexBufferFormat(indexBuf.getFormat()), - 0); - RendererUtil.checkGLError(); - } - } - } - - /*********************************************************************\ - |* Render Calls *| - \*********************************************************************/ - public int convertElementMode(Mesh.Mode mode) { - switch (mode) { - case Points: - return GLES20.GL_POINTS; - case Lines: - return GLES20.GL_LINES; - case LineLoop: - return GLES20.GL_LINE_LOOP; - case LineStrip: - return GLES20.GL_LINE_STRIP; - case Triangles: - return GLES20.GL_TRIANGLES; - case TriangleFan: - return GLES20.GL_TRIANGLE_FAN; - case TriangleStrip: - return GLES20.GL_TRIANGLE_STRIP; - default: - throw new UnsupportedOperationException("Unrecognized mesh mode: " + mode); - } - } - - public void updateVertexArray(Mesh mesh) { - logger.log(Level.FINE, "updateVertexArray({0})", mesh); - int id = mesh.getId(); - /* - if (id == -1){ - IntBuffer temp = intBuf1; - // ARBVertexArrayObject.glGenVertexArrays(temp); - GLES20.glGenVertexArrays(temp); - id = temp.get(0); - mesh.setId(id); - } - - if (context.boundVertexArray != id){ - // ARBVertexArrayObject.glBindVertexArray(id); - GLES20.glBindVertexArray(id); - context.boundVertexArray = id; - } - */ - VertexBuffer interleavedData = mesh.getBuffer(Type.InterleavedData); - if (interleavedData != null && interleavedData.isUpdateNeeded()) { - updateBufferData(interleavedData); - } - - - for (VertexBuffer vb : mesh.getBufferList().getArray()){ - - if (vb.getBufferType() == Type.InterleavedData - || vb.getUsage() == Usage.CpuOnly // ignore cpu-only buffers - || vb.getBufferType() == Type.Index) { - continue; - } - - if (vb.getStride() == 0) { - // not interleaved - setVertexAttrib(vb); - } else { - // interleaved - setVertexAttrib(vb, interleavedData); - } - } - } - - /** - * renderMeshVertexArray renders a mesh using vertex arrays - */ - private void renderMeshVertexArray(Mesh mesh, int lod, int count) { - for (VertexBuffer vb : mesh.getBufferList().getArray()) { - if (vb.getBufferType() == Type.InterleavedData - || vb.getUsage() == Usage.CpuOnly // ignore cpu-only buffers - || vb.getBufferType() == Type.Index) { - continue; - } - - if (vb.getStride() == 0) { - // not interleaved - setVertexAttrib_Array(vb); - } else { - // interleaved - VertexBuffer interleavedData = mesh.getBuffer(Type.InterleavedData); - setVertexAttrib_Array(vb, interleavedData); - } - } - - VertexBuffer indices; - if (mesh.getNumLodLevels() > 0) { - indices = mesh.getLodLevel(lod); - } else { - indices = mesh.getBuffer(Type.Index);//buffers.get(Type.Index.ordinal()); - } - if (indices != null) { - drawTriangleList_Array(indices, mesh, count); - } else { - GLES20.glDrawArrays(convertElementMode(mesh.getMode()), 0, mesh.getVertexCount()); - RendererUtil.checkGLError(); - } - clearVertexAttribs(); - clearTextureUnits(); - } - - private void renderMeshDefault(Mesh mesh, int lod, int count) { - VertexBuffer indices; - VertexBuffer interleavedData = mesh.getBuffer(Type.InterleavedData); - if (interleavedData != null && interleavedData.isUpdateNeeded()) { - updateBufferData(interleavedData); - } - - //IntMap buffers = mesh.getBuffers(); ; - if (mesh.getNumLodLevels() > 0) { - indices = mesh.getLodLevel(lod); - } else { - indices = mesh.getBuffer(Type.Index);// buffers.get(Type.Index.ordinal()); - } - for (VertexBuffer vb : mesh.getBufferList().getArray()){ - if (vb.getBufferType() == Type.InterleavedData - || vb.getUsage() == Usage.CpuOnly // ignore cpu-only buffers - || vb.getBufferType() == Type.Index) { - continue; - } - - if (vb.getStride() == 0) { - // not interleaved - setVertexAttrib(vb); - } else { - // interleaved - setVertexAttrib(vb, interleavedData); - } - } - if (indices != null) { - drawTriangleList(indices, mesh, count); - } else { -// throw new UnsupportedOperationException("Cannot render without index buffer"); - GLES20.glDrawArrays(convertElementMode(mesh.getMode()), 0, mesh.getVertexCount()); - RendererUtil.checkGLError(); - } - clearVertexAttribs(); - clearTextureUnits(); - } - - public void renderMesh(Mesh mesh, int lod, int count, VertexBuffer[] instanceData) { - if (mesh.getVertexCount() == 0) { - return; - } - - /* - * NOTE: not supported in OpenGL ES 2.0. - if (context.pointSize != mesh.getPointSize()) { - GLES10.glPointSize(mesh.getPointSize()); - context.pointSize = mesh.getPointSize(); - } - */ - if (context.lineWidth != mesh.getLineWidth()) { - GLES20.glLineWidth(mesh.getLineWidth()); - RendererUtil.checkGLError(); - context.lineWidth = mesh.getLineWidth(); - } - - statistics.onMeshDrawn(mesh, lod); -// if (GLContext.getCapabilities().GL_ARB_vertex_array_object){ -// renderMeshVertexArray(mesh, lod, count); -// }else{ - - if (useVBO) { - renderMeshDefault(mesh, lod, count); - } else { - renderMeshVertexArray(mesh, lod, count); - } - } - - /** - * drawTriangleList_Array uses Vertex Array - * @param indexBuf - * @param mesh - * @param count - */ - public void drawTriangleList_Array(VertexBuffer indexBuf, Mesh mesh, int count) { - if (indexBuf.getBufferType() != VertexBuffer.Type.Index) { - throw new IllegalArgumentException("Only index buffers are allowed as triangle lists."); - } - - boolean useInstancing = count > 1 && caps.contains(Caps.MeshInstancing); - if (useInstancing) { - throw new IllegalArgumentException("Caps.MeshInstancing is not supported."); - } - - int vertCount = mesh.getVertexCount(); - Buffer indexData = indexBuf.getData(); - indexData.rewind(); - - if (mesh.getMode() == Mode.Hybrid) { - int[] modeStart = mesh.getModeStart(); - int[] elementLengths = mesh.getElementLengths(); - - int elMode = convertElementMode(Mode.Triangles); - int fmt = convertVertexBufferFormat(indexBuf.getFormat()); - int elSize = indexBuf.getFormat().getComponentSize(); - int listStart = modeStart[0]; - int stripStart = modeStart[1]; - int fanStart = modeStart[2]; - int curOffset = 0; - for (int i = 0; i < elementLengths.length; i++) { - if (i == stripStart) { - elMode = convertElementMode(Mode.TriangleStrip); - } else if (i == fanStart) { - elMode = convertElementMode(Mode.TriangleFan); - } - int elementLength = elementLengths[i]; - - indexBuf.getData().position(curOffset); - GLES20.glDrawElements(elMode, elementLength, fmt, indexBuf.getData()); - RendererUtil.checkGLError(); - - curOffset += elementLength * elSize; - } - } else { - GLES20.glDrawElements( - convertElementMode(mesh.getMode()), - indexBuf.getData().limit(), - convertVertexBufferFormat(indexBuf.getFormat()), - indexBuf.getData()); - RendererUtil.checkGLError(); - } - } - - /** - * setVertexAttrib_Array uses Vertex Array - * @param vb - * @param idb - */ - public void setVertexAttrib_Array(VertexBuffer vb, VertexBuffer idb) { - if (vb.getBufferType() == VertexBuffer.Type.Index) { - throw new IllegalArgumentException("Index buffers not allowed to be set to vertex attrib"); - } - - // Get shader - int programId = context.boundShaderProgram; - if (programId > 0) { - VertexBuffer[] attribs = context.boundAttribs; - - Attribute attrib = boundShader.getAttribute(vb.getBufferType()); - int loc = attrib.getLocation(); - if (loc == -1) { - //throw new IllegalArgumentException("Location is invalid for attrib: [" + vb.getBufferType().name() + "]"); - return; - } else if (loc == -2) { - String attributeName = "in" + vb.getBufferType().name(); - - loc = GLES20.glGetAttribLocation(programId, attributeName); - RendererUtil.checkGLError(); - - if (loc < 0) { - attrib.setLocation(-1); - return; // not available in shader. - } else { - attrib.setLocation(loc); - } - - } // if (loc == -2) - - if ((attribs[loc] != vb) || vb.isUpdateNeeded()) { - // NOTE: Use data from interleaved buffer if specified - VertexBuffer avb = idb != null ? idb : vb; - avb.getData().rewind(); - avb.getData().position(vb.getOffset()); - - // Upload attribute data - GLES20.glVertexAttribPointer(loc, - vb.getNumComponents(), - convertVertexBufferFormat(vb.getFormat()), - vb.isNormalized(), - vb.getStride(), - avb.getData()); - - RendererUtil.checkGLError(); - - GLES20.glEnableVertexAttribArray(loc); - RendererUtil.checkGLError(); - - attribs[loc] = vb; - } // if (attribs[loc] != vb) - } else { - throw new IllegalStateException("Cannot render mesh without shader bound"); - } - } - - /** - * setVertexAttrib_Array uses Vertex Array - * @param vb - */ - public void setVertexAttrib_Array(VertexBuffer vb) { - setVertexAttrib_Array(vb, null); - } - - public void setAlphaToCoverage(boolean value) { - if (value) { - GLES20.glEnable(GLES20.GL_SAMPLE_ALPHA_TO_COVERAGE); - RendererUtil.checkGLError(); - } else { - GLES20.glDisable(GLES20.GL_SAMPLE_ALPHA_TO_COVERAGE); - RendererUtil.checkGLError(); - } - } - - @Override - public void invalidateState() { - context.reset(); - boundShader = null; - lastFb = null; - } - - public void setMainFrameBufferSrgb(boolean srgb) { - //TODO once opglES3.0 is supported maybe.... - } - - public void setLinearizeSrgbImages(boolean linearize) { - //TODO once opglES3.0 is supported maybe.... - } - - public void readFrameBufferWithFormat(FrameBuffer fb, ByteBuffer byteBuf, Image.Format format) { - throw new UnsupportedOperationException("Not supported yet. URA will make that work seamlessly"); - } -} diff --git a/jme3-android/src/main/java/com/jme3/system/android/OGLESContext.java b/jme3-android/src/main/java/com/jme3/system/android/OGLESContext.java index cd849b1dd..991ad25c0 100644 --- a/jme3-android/src/main/java/com/jme3/system/android/OGLESContext.java +++ b/jme3-android/src/main/java/com/jme3/system/android/OGLESContext.java @@ -46,17 +46,16 @@ import android.view.ViewGroup.LayoutParams; import android.widget.EditText; import android.widget.FrameLayout; import com.jme3.input.*; -import com.jme3.input.android.AndroidSensorJoyInput; import com.jme3.input.android.AndroidInputHandler; +import com.jme3.input.android.AndroidInputHandler14; import com.jme3.input.controls.SoftTextDialogInputListener; import com.jme3.input.dummy.DummyKeyInput; import com.jme3.input.dummy.DummyMouseInput; import com.jme3.renderer.android.AndroidGL; import com.jme3.renderer.opengl.GL; -import com.jme3.renderer.opengl.GLDebugES; import com.jme3.renderer.opengl.GLExt; +import com.jme3.renderer.opengl.GLFbo; import com.jme3.renderer.opengl.GLRenderer; -import com.jme3.renderer.opengl.GLTracer; import com.jme3.system.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; @@ -79,7 +78,6 @@ public class OGLESContext implements JmeContext, GLSurfaceView.Renderer, SoftTex protected AndroidInputHandler androidInput; protected long minFrameDuration = 0; // No FPS cap protected long lastUpdateTime = 0; - protected JoyInput androidSensorJoyInput = null; public OGLESContext() { } @@ -113,8 +111,13 @@ public class OGLESContext implements JmeContext, GLSurfaceView.Renderer, SoftTex // Start to set up the view GLSurfaceView view = new GLSurfaceView(context); + logger.log(Level.INFO, "Android Build Version: {0}", Build.VERSION.SDK_INT); if (androidInput == null) { - androidInput = new AndroidInputHandler(); + if (Build.VERSION.SDK_INT >= 14) { + androidInput = new AndroidInputHandler14(); + } else if (Build.VERSION.SDK_INT >= 9){ + androidInput = new AndroidInputHandler(); + } } androidInput.setView(view); androidInput.loadSettings(settings); @@ -194,7 +197,7 @@ public class OGLESContext implements JmeContext, GLSurfaceView.Renderer, SoftTex Object gl = new AndroidGL(); // gl = GLTracer.createGlesTracer((GL)gl, (GLExt)gl); // gl = new GLDebugES((GL)gl, (GLExt)gl); - renderer = new GLRenderer((GL)gl, (GLExt)gl); + renderer = new GLRenderer((GL)gl, (GLExt)gl, (GLFbo)gl); renderer.initialize(); JmeSystem.setSoftTextDialogInput(this); @@ -267,15 +270,12 @@ public class OGLESContext implements JmeContext, GLSurfaceView.Renderer, SoftTex @Override public JoyInput getJoyInput() { - if (androidSensorJoyInput == null) { - androidSensorJoyInput = new AndroidSensorJoyInput(); - } - return androidSensorJoyInput; + return androidInput.getJoyInput(); } @Override public TouchInput getTouchInput() { - return androidInput; + return androidInput.getTouchInput(); } @Override diff --git a/jme3-android/src/main/java/jme3test/android/DemoAndroidHarness.java b/jme3-android/src/main/java/jme3test/android/DemoAndroidHarness.java index 42c621a4f..61d0d6868 100644 --- a/jme3-android/src/main/java/jme3test/android/DemoAndroidHarness.java +++ b/jme3-android/src/main/java/jme3test/android/DemoAndroidHarness.java @@ -7,21 +7,19 @@ import com.jme3.app.AndroidHarness; public class DemoAndroidHarness extends AndroidHarness { @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) + { // Set the application class to run // First Extract the bundle from intent Bundle bundle = getIntent().getExtras(); //Next extract the values using the key as - appClass = bundle.getString("APPCLASSNAME"); - + appClass = bundle.getString("APPCLASSNAME"); + exitDialogTitle = "Close Demo?"; exitDialogMessage = "Press Yes"; - screenOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; - - super.onCreate(savedInstanceState); + super.onCreate(savedInstanceState); } } diff --git a/jme3-blender/build.gradle b/jme3-blender/build.gradle index 1b42c7109..a556d7a65 100644 --- a/jme3-blender/build.gradle +++ b/jme3-blender/build.gradle @@ -6,4 +6,7 @@ dependencies { compile project(':jme3-core') compile project(':jme3-desktop') compile project(':jme3-effects') -} + compile ('org.ejml:core:0.27') + compile ('org.ejml:dense64:0.27') + compile ('org.ejml:simple:0.27') +} \ No newline at end of file diff --git a/jme3-blender/src/main/java/com/jme3/asset/BlenderKey.java b/jme3-blender/src/main/java/com/jme3/asset/BlenderKey.java index c215d0677..c412c07b3 100644 --- a/jme3-blender/src/main/java/com/jme3/asset/BlenderKey.java +++ b/jme3-blender/src/main/java/com/jme3/asset/BlenderKey.java @@ -32,36 +32,19 @@ package com.jme3.asset; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Queue; -import com.jme3.animation.Animation; -import com.jme3.bounding.BoundingVolume; -import com.jme3.collision.Collidable; -import com.jme3.collision.CollisionResults; -import com.jme3.collision.UnsupportedCollisionException; import com.jme3.export.InputCapsule; import com.jme3.export.JmeExporter; import com.jme3.export.JmeImporter; import com.jme3.export.OutputCapsule; import com.jme3.material.Material; import com.jme3.material.RenderState.FaceCullMode; -import com.jme3.math.ColorRGBA; -import com.jme3.post.Filter; -import com.jme3.scene.CameraNode; -import com.jme3.scene.LightNode; -import com.jme3.scene.Node; -import com.jme3.scene.SceneGraphVisitor; -import com.jme3.scene.Spatial; -import com.jme3.texture.Texture; /** * Blender key. Contains path of the blender file and its loading properties. * @author Marcin Roguski (Kaelthas) */ public class BlenderKey extends ModelKey { - protected static final int DEFAULT_FPS = 25; /** * FramesPerSecond parameter describe how many frames there are in each second. It allows to calculate the time @@ -72,7 +55,7 @@ public class BlenderKey extends ModelKey { * This variable is a bitwise flag of FeatureToLoad interface values; By default everything is being loaded. */ protected int featuresToLoad = FeaturesToLoad.ALL; - /** This variable determines if assets that are not linked to the objects should be loaded. */ + /** The variable that tells if content of the file (along with data unlinked to any feature on the scene) should be stored as 'user data' in the result spatial. */ protected boolean loadUnlinkedAssets; /** The root path for all the assets. */ protected String assetRootPath; @@ -268,6 +251,7 @@ public class BlenderKey extends ModelKey { * @param featuresToLoad * bitwise flag of FeaturesToLoad interface values */ + @Deprecated public void includeInLoading(int featuresToLoad) { this.featuresToLoad |= featuresToLoad; } @@ -277,10 +261,12 @@ public class BlenderKey extends ModelKey { * @param featuresNotToLoad * bitwise flag of FeaturesToLoad interface values */ + @Deprecated public void excludeFromLoading(int featuresNotToLoad) { featuresToLoad &= ~featuresNotToLoad; } + @Deprecated public boolean shouldLoad(int featureToLoad) { return (featuresToLoad & featureToLoad) != 0; } @@ -290,6 +276,7 @@ public class BlenderKey extends ModelKey { * the blender file loader. * @return features that will be loaded by the blender file loader */ + @Deprecated public int getFeaturesToLoad() { return featuresToLoad; } @@ -317,15 +304,6 @@ public class BlenderKey extends ModelKey { this.loadUnlinkedAssets = loadUnlinkedAssets; } - /** - * This method creates an object where loading results will be stores. Only those features will be allowed to store - * that were specified by features-to-load flag. - * @return an object to store loading results - */ - public LoadingResults prepareLoadingResults() { - return new LoadingResults(featuresToLoad); - } - /** * This method sets the fix up axis state. If set to true then Y is up axis. Otherwise the up i Z axis. By default Y * is up axis. @@ -699,8 +677,11 @@ public class BlenderKey extends ModelKey { /** * This interface describes the features of the scene that are to be loaded. + * @deprecated this interface is deprecated and is not used anymore; to ensure the loading models consistency + * everything must be loaded because in blender one feature might depend on another * @author Marcin Roguski (Kaelthas) */ + @Deprecated public static interface FeaturesToLoad { int SCENES = 0x0000FFFF; @@ -745,281 +726,4 @@ public class BlenderKey extends ModelKey { */ ALL_NAMES_MATCH; } - - /** - * This class holds the loading results according to the given loading flag. - * @author Marcin Roguski (Kaelthas) - */ - public static class LoadingResults extends Spatial { - - /** Bitwise mask of features that are to be loaded. */ - private final int featuresToLoad; - /** The scenes from the file. */ - private List scenes; - /** Objects from all scenes. */ - private List objects; - /** Materials from all objects. */ - private List materials; - /** Textures from all objects. */ - private List textures; - /** Animations of all objects. */ - private List animations; - /** All cameras from the file. */ - private List cameras; - /** All lights from the file. */ - private List lights; - /** Loaded sky. */ - private Spatial sky; - /** Scene filters (ie. FOG). */ - private List filters; - /** - * The background color of the render loaded from the horizon color of the world. If no world is used than the gray color - * is set to default (as in blender editor. - */ - private ColorRGBA backgroundColor = ColorRGBA.Gray; - - /** - * Private constructor prevents users to create an instance of this class from outside the - * @param featuresToLoad - * bitwise mask of features that are to be loaded - * @see FeaturesToLoad FeaturesToLoad - */ - private LoadingResults(int featuresToLoad) { - this.featuresToLoad = featuresToLoad; - if ((featuresToLoad & FeaturesToLoad.SCENES) != 0) { - scenes = new ArrayList(); - } - if ((featuresToLoad & FeaturesToLoad.OBJECTS) != 0) { - objects = new ArrayList(); - if ((featuresToLoad & FeaturesToLoad.MATERIALS) != 0) { - materials = new ArrayList(); - if ((featuresToLoad & FeaturesToLoad.TEXTURES) != 0) { - textures = new ArrayList(); - } - } - if ((featuresToLoad & FeaturesToLoad.ANIMATIONS) != 0) { - animations = new ArrayList(); - } - } - if ((featuresToLoad & FeaturesToLoad.CAMERAS) != 0) { - cameras = new ArrayList(); - } - if ((featuresToLoad & FeaturesToLoad.LIGHTS) != 0) { - lights = new ArrayList(); - } - } - - /** - * This method returns a bitwise flag describing what features of the blend file will be included in the result. - * @return bitwise mask of features that are to be loaded - * @see FeaturesToLoad FeaturesToLoad - */ - public int getLoadedFeatures() { - return featuresToLoad; - } - - /** - * This method adds a scene to the result set. - * @param scene - * scene to be added to the result set - */ - public void addScene(Node scene) { - if (scenes != null) { - scenes.add(scene); - } - } - - /** - * This method adds an object to the result set. - * @param object - * object to be added to the result set - */ - public void addObject(Node object) { - if (objects != null) { - objects.add(object); - } - } - - /** - * This method adds a material to the result set. - * @param material - * material to be added to the result set - */ - public void addMaterial(Material material) { - if (materials != null) { - materials.add(material); - } - } - - /** - * This method adds a texture to the result set. - * @param texture - * texture to be added to the result set - */ - public void addTexture(Texture texture) { - if (textures != null) { - textures.add(texture); - } - } - - /** - * This method adds a camera to the result set. - * @param camera - * camera to be added to the result set - */ - public void addCamera(CameraNode camera) { - if (cameras != null) { - cameras.add(camera); - } - } - - /** - * This method adds a light to the result set. - * @param light - * light to be added to the result set - */ - public void addLight(LightNode light) { - if (lights != null) { - lights.add(light); - } - } - - /** - * This method sets the sky of the scene. Only one sky can be set. - * @param sky - * the sky to be set - */ - public void setSky(Spatial sky) { - this.sky = sky; - } - - /** - * This method adds a scene filter. Filters are used to load FOG or other - * scene effects that blender can define. - * @param filter - * the filter to be added - */ - public void addFilter(Filter filter) { - if (filter != null) { - if (filters == null) { - filters = new ArrayList(5); - } - filters.add(filter); - } - } - - /** - * @param backgroundColor - * the background color - */ - public void setBackgroundColor(ColorRGBA backgroundColor) { - this.backgroundColor = backgroundColor; - } - - /** - * @return all loaded scenes - */ - public List getScenes() { - return scenes; - } - - /** - * @return all loaded objects - */ - public List getObjects() { - return objects; - } - - /** - * @return all loaded materials - */ - public List getMaterials() { - return materials; - } - - /** - * @return all loaded textures - */ - public List getTextures() { - return textures; - } - - /** - * @return all loaded animations - */ - public List getAnimations() { - return animations; - } - - /** - * @return all loaded cameras - */ - public List getCameras() { - return cameras; - } - - /** - * @return all loaded lights - */ - public List getLights() { - return lights; - } - - /** - * @return the scene's sky - */ - public Spatial getSky() { - return sky; - } - - /** - * @return scene filters - */ - public List getFilters() { - return filters; - } - - /** - * @return the background color - */ - public ColorRGBA getBackgroundColor() { - return backgroundColor; - } - - @Override - public int collideWith(Collidable other, CollisionResults results) throws UnsupportedCollisionException { - return 0; - } - - @Override - public void updateModelBound() { - } - - @Override - public void setModelBound(BoundingVolume modelBound) { - } - - @Override - public int getVertexCount() { - return 0; - } - - @Override - public int getTriangleCount() { - return 0; - } - - @Override - public Spatial deepClone() { - return null; - } - - @Override - public void depthFirstTraversal(SceneGraphVisitor visitor) { - } - - @Override - protected void breadthFirstTraversal(SceneGraphVisitor visitor, Queue queue) { - } - } } diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/AbstractBlenderHelper.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/AbstractBlenderHelper.java index eff993f76..e11101c14 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/AbstractBlenderHelper.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/AbstractBlenderHelper.java @@ -31,17 +31,34 @@ */ package com.jme3.scene.plugins.blender; +import java.io.File; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.logging.Level; +import java.util.logging.Logger; +import com.jme3.animation.Animation; +import com.jme3.asset.AssetNotFoundException; +import com.jme3.asset.BlenderKey; import com.jme3.export.Savable; +import com.jme3.light.Light; import com.jme3.math.FastMath; import com.jme3.math.Quaternion; +import com.jme3.post.Filter; +import com.jme3.renderer.Camera; +import com.jme3.scene.Node; import com.jme3.scene.Spatial; +import com.jme3.scene.plugins.blender.BlenderContext.LoadedDataType; import com.jme3.scene.plugins.blender.file.BlenderFileException; import com.jme3.scene.plugins.blender.file.Pointer; import com.jme3.scene.plugins.blender.file.Structure; +import com.jme3.scene.plugins.blender.materials.MaterialContext; +import com.jme3.scene.plugins.blender.meshes.TemporalMesh; import com.jme3.scene.plugins.blender.objects.Properties; +import com.jme3.texture.Texture; /** * A purpose of the helper class is to split calculation code into several classes. Each helper after use should be cleared because it can @@ -49,14 +66,16 @@ import com.jme3.scene.plugins.blender.objects.Properties; * @author Marcin Roguski */ public abstract class AbstractBlenderHelper { + private static final Logger LOGGER = Logger.getLogger(AbstractBlenderHelper.class.getName()); + /** The blender context. */ - protected BlenderContext blenderContext; + protected BlenderContext blenderContext; /** The version of the blend file. */ - protected final int blenderVersion; + protected final int blenderVersion; /** This variable indicates if the Y asxis is the UP axis or not. */ - protected boolean fixUpAxis; + protected boolean fixUpAxis; /** Quaternion used to rotate data when Y is up axis. */ - protected Quaternion upAxisRotationQuaternion; + protected Quaternion upAxisRotationQuaternion; /** * This constructor parses the given blender version and stores the result. Some functionalities may differ in different blender @@ -129,4 +148,115 @@ public abstract class AbstractBlenderHelper { } } } + + /** + * The method loads library of a given ID from linked blender file. + * @param id + * the ID of the linked feature (it contains its name and blender path) + * @return loaded feature or null if none was found + * @throws BlenderFileException + * and exception is throw when problems with reading a blend file occur + */ + @SuppressWarnings("unchecked") + protected Object loadLibrary(Structure id) throws BlenderFileException { + Pointer pLib = (Pointer) id.getFieldValue("lib"); + if (pLib.isNotNull()) { + String fullName = id.getFieldValue("name").toString();// we need full name with the prefix + String nameOfFeatureToLoad = id.getName(); + Structure library = pLib.fetchData().get(0); + String path = library.getFieldValue("filepath").toString(); + + if (!blenderContext.getLinkedFeatures().keySet().contains(path)) { + File file = new File(path); + List pathsToCheck = new ArrayList(); + String currentPath = file.getName(); + do { + pathsToCheck.add(currentPath); + file = file.getParentFile(); + if (file != null) { + currentPath = file.getName() + '/' + currentPath; + } + } while (file != null); + + Spatial loadedAsset = null; + BlenderKey blenderKey = null; + for (String p : pathsToCheck) { + blenderKey = new BlenderKey(p); + blenderKey.setLoadUnlinkedAssets(true); + try { + loadedAsset = blenderContext.getAssetManager().loadAsset(blenderKey); + break;// break if no exception was thrown + } catch (AssetNotFoundException e) { + LOGGER.log(Level.FINEST, "Cannot locate linked resource at path: {0}.", p); + } + } + + if (loadedAsset != null) { + Map> linkedData = loadedAsset.getUserData("linkedData"); + for (Entry> entry : linkedData.entrySet()) { + String linkedDataFilePath = "this".equals(entry.getKey()) ? path : entry.getKey(); + + List scenes = (List) entry.getValue().get("scenes"); + for (Node scene : scenes) { + blenderContext.addLinkedFeature(linkedDataFilePath, "SC" + scene.getName(), scene); + } + List objects = (List) entry.getValue().get("objects"); + for (Node object : objects) { + blenderContext.addLinkedFeature(linkedDataFilePath, "OB" + object.getName(), object); + } + List meshes = (List) entry.getValue().get("meshes"); + for (TemporalMesh mesh : meshes) { + blenderContext.addLinkedFeature(linkedDataFilePath, "ME" + mesh.getName(), mesh); + } + List materials = (List) entry.getValue().get("materials"); + for (MaterialContext materialContext : materials) { + blenderContext.addLinkedFeature(linkedDataFilePath, "MA" + materialContext.getName(), materialContext); + } + List textures = (List) entry.getValue().get("textures"); + for (Texture texture : textures) { + blenderContext.addLinkedFeature(linkedDataFilePath, "TE" + texture.getName(), texture); + } + List images = (List) entry.getValue().get("images"); + for (Texture image : images) { + blenderContext.addLinkedFeature(linkedDataFilePath, "IM" + image.getName(), image); + } + List animations = (List) entry.getValue().get("animations"); + for (Animation animation : animations) { + blenderContext.addLinkedFeature(linkedDataFilePath, "AC" + animation.getName(), animation); + } + List cameras = (List) entry.getValue().get("cameras"); + for (Camera camera : cameras) { + blenderContext.addLinkedFeature(linkedDataFilePath, "CA" + camera.getName(), camera); + } + List lights = (List) entry.getValue().get("lights"); + for (Light light : lights) { + blenderContext.addLinkedFeature(linkedDataFilePath, "LA" + light.getName(), light); + } + Spatial sky = (Spatial) entry.getValue().get("sky"); + if (sky != null) { + blenderContext.addLinkedFeature(linkedDataFilePath, sky.getName(), sky); + } + List filters = (List) entry.getValue().get("filters"); + for (Filter filter : filters) { + blenderContext.addLinkedFeature(linkedDataFilePath, filter.getName(), filter); + } + } + } else { + LOGGER.log(Level.WARNING, "No features loaded from path: {0}.", path); + } + } + + Object result = blenderContext.getLinkedFeature(path, fullName); + if (result == null) { + LOGGER.log(Level.WARNING, "Could NOT find asset named {0} in the library of path: {1}.", new Object[] { nameOfFeatureToLoad, path }); + } else { + blenderContext.addLoadedFeatures(id.getOldMemoryAddress(), LoadedDataType.STRUCTURE, id); + blenderContext.addLoadedFeatures(id.getOldMemoryAddress(), LoadedDataType.FEATURE, result); + } + return result; + } else { + LOGGER.warning("Library link points to nothing!"); + } + return null; + } } diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/BlenderContext.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/BlenderContext.java index cde38e327..6e8042b09 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/BlenderContext.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/BlenderContext.java @@ -53,6 +53,7 @@ import com.jme3.scene.plugins.blender.constraints.Constraint; import com.jme3.scene.plugins.blender.file.BlenderInputStream; import com.jme3.scene.plugins.blender.file.DnaBlockData; import com.jme3.scene.plugins.blender.file.FileBlockHeader; +import com.jme3.scene.plugins.blender.file.FileBlockHeader.BlockCode; import com.jme3.scene.plugins.blender.file.Structure; /** @@ -64,49 +65,51 @@ import com.jme3.scene.plugins.blender.file.Structure; */ public class BlenderContext { /** The blender file version. */ - private int blenderVersion; + private int blenderVersion; /** The blender key. */ - private BlenderKey blenderKey; + private BlenderKey blenderKey; /** The header of the file block. */ - private DnaBlockData dnaBlockData; + private DnaBlockData dnaBlockData; /** The scene structure. */ - private Structure sceneStructure; + private Structure sceneStructure; /** The input stream of the blend file. */ - private BlenderInputStream inputStream; + private BlenderInputStream inputStream; /** The asset manager. */ - private AssetManager assetManager; + private AssetManager assetManager; /** The blocks read from the file. */ - protected List blocks; + protected List blocks; /** * A map containing the file block headers. The key is the old memory address. */ - private Map fileBlockHeadersByOma = new HashMap(); + private Map fileBlockHeadersByOma = new HashMap(); /** A map containing the file block headers. The key is the block code. */ - private Map> fileBlockHeadersByCode = new HashMap>(); + private Map> fileBlockHeadersByCode = new HashMap>(); /** * This map stores the loaded features by their old memory address. The * first object in the value table is the loaded structure and the second - * the structure already converted into proper data. */ - private Map> loadedFeatures = new HashMap>(); + private Map> loadedFeatures = new HashMap>(); + /** Features loaded from external blender files. The key is the file path and the value is a map between feature name and loaded feature. */ + private Map> linkedFeatures = new HashMap>(); /** A stack that hold the parent structure of currently loaded feature. */ - private Stack parentStack = new Stack(); + private Stack parentStack = new Stack(); /** A list of constraints for the specified object. */ - protected Map> constraints = new HashMap>(); + protected Map> constraints = new HashMap>(); /** Animations loaded for features. */ - private Map> animations = new HashMap>(); + private Map> animations = new HashMap>(); /** Loaded skeletons. */ - private Map skeletons = new HashMap(); + private Map skeletons = new HashMap(); /** A map between skeleton and node it modifies. */ - private Map nodesWithSkeletons = new HashMap(); + private Map nodesWithSkeletons = new HashMap(); /** A map of bone contexts. */ - protected Map boneContexts = new HashMap(); + protected Map boneContexts = new HashMap(); /** A map og helpers that perform loading. */ - private Map helpers = new HashMap(); + private Map helpers = new HashMap(); /** Markers used by loading classes to store some custom data. This is made to avoid putting this data into user properties. */ - private Map> markers = new HashMap>(); + private Map> markers = new HashMap>(); /** A map of blender actions. The key is the action name and the value is the action itself. */ - private Map actions = new HashMap(); + private Map actions = new HashMap(); /** * This method sets the blender file version. @@ -231,10 +234,10 @@ public class BlenderContext { */ public void addFileBlockHeader(Long oldMemoryAddress, FileBlockHeader fileBlockHeader) { fileBlockHeadersByOma.put(oldMemoryAddress, fileBlockHeader); - List headers = fileBlockHeadersByCode.get(Integer.valueOf(fileBlockHeader.getCode())); + List headers = fileBlockHeadersByCode.get(fileBlockHeader.getCode()); if (headers == null) { headers = new ArrayList(); - fileBlockHeadersByCode.put(Integer.valueOf(fileBlockHeader.getCode()), headers); + fileBlockHeadersByCode.put(fileBlockHeader.getCode(), headers); } headers.add(fileBlockHeader); } @@ -258,7 +261,7 @@ public class BlenderContext { * the code of file blocks * @return a list of file blocks' headers of a specified code */ - public List getFileBlocks(Integer code) { + public List getFileBlocks(BlockCode code) { return fileBlockHeadersByCode.get(code); } @@ -299,7 +302,7 @@ public class BlenderContext { throw new IllegalArgumentException("One of the given arguments is null!"); } Map map = loadedFeatures.get(oldMemoryAddress); - if(map == null) { + if (map == null) { map = new HashMap(); loadedFeatures.put(oldMemoryAddress, map); } @@ -325,6 +328,48 @@ public class BlenderContext { return null; } + /** + * The method adds linked content to the blender context. + * @param blenderFilePath + * the path of linked blender file + * @param featureName + * the linked feature name + * @param feature + * the linked feature + */ + public void addLinkedFeature(String blenderFilePath, String featureName, Object feature) { + if (feature != null) { + Map linkedFeatures = this.linkedFeatures.get(blenderFilePath); + if (linkedFeatures == null) { + linkedFeatures = new HashMap(); + this.linkedFeatures.put(blenderFilePath, linkedFeatures); + } + if (!linkedFeatures.containsKey(featureName)) { + linkedFeatures.put(featureName, feature); + } + } + } + + /** + * The method returns linked feature of a given name from the specified blender path. + * @param blenderFilePath + * the blender file path + * @param featureName + * the feature name we want to get + * @return linked feature or null if none was found + */ + public Object getLinkedFeature(String blenderFilePath, String featureName) { + Map linkedFeatures = this.linkedFeatures.get(blenderFilePath); + return linkedFeatures != null ? linkedFeatures.get(featureName) : null; + } + + /** + * @return all linked features for the current blend file + */ + public Map> getLinkedFeatures() { + return linkedFeatures; + } + /** * This method adds the structure to the parent stack. * diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/BlenderLoader.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/BlenderLoader.java index 200f83b39..dd0160063 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/BlenderLoader.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/BlenderLoader.java @@ -33,17 +33,21 @@ package com.jme3.scene.plugins.blender; import java.io.IOException; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; +import com.jme3.animation.Animation; import com.jme3.asset.AssetInfo; import com.jme3.asset.AssetLoader; import com.jme3.asset.BlenderKey; -import com.jme3.asset.BlenderKey.FeaturesToLoad; -import com.jme3.asset.BlenderKey.LoadingResults; import com.jme3.asset.ModelKey; import com.jme3.light.Light; +import com.jme3.math.ColorRGBA; +import com.jme3.post.Filter; +import com.jme3.renderer.Camera; import com.jme3.scene.CameraNode; import com.jme3.scene.LightNode; import com.jme3.scene.Node; @@ -55,16 +59,20 @@ import com.jme3.scene.plugins.blender.curves.CurvesHelper; import com.jme3.scene.plugins.blender.file.BlenderFileException; import com.jme3.scene.plugins.blender.file.BlenderInputStream; import com.jme3.scene.plugins.blender.file.FileBlockHeader; +import com.jme3.scene.plugins.blender.file.FileBlockHeader.BlockCode; import com.jme3.scene.plugins.blender.file.Pointer; import com.jme3.scene.plugins.blender.file.Structure; import com.jme3.scene.plugins.blender.landscape.LandscapeHelper; import com.jme3.scene.plugins.blender.lights.LightHelper; +import com.jme3.scene.plugins.blender.materials.MaterialContext; import com.jme3.scene.plugins.blender.materials.MaterialHelper; import com.jme3.scene.plugins.blender.meshes.MeshHelper; +import com.jme3.scene.plugins.blender.meshes.TemporalMesh; import com.jme3.scene.plugins.blender.modifiers.ModifierHelper; import com.jme3.scene.plugins.blender.objects.ObjectHelper; import com.jme3.scene.plugins.blender.particles.ParticlesHelper; import com.jme3.scene.plugins.blender.textures.TextureHelper; +import com.jme3.texture.Texture; /** * This is the main loading class. Have in notice that asset manager needs to have loaders for resources like textures. @@ -83,72 +91,130 @@ public class BlenderLoader implements AssetLoader { try { this.setup(assetInfo); - List sceneBlocks = new ArrayList(); - BlenderKey blenderKey = blenderContext.getBlenderKey(); - LoadingResults loadingResults = blenderKey.prepareLoadingResults(); - AnimationHelper animationHelper = blenderContext.getHelper(AnimationHelper.class); animationHelper.loadAnimations(); - + + BlenderKey blenderKey = blenderContext.getBlenderKey(); + LoadedFeatures loadedFeatures = new LoadedFeatures(); for (FileBlockHeader block : blocks) { switch (block.getCode()) { - case FileBlockHeader.BLOCK_OB00:// Object + case BLOCK_OB00: ObjectHelper objectHelper = blenderContext.getHelper(ObjectHelper.class); - Object object = objectHelper.toObject(block.getStructure(blenderContext), blenderContext); - if (object instanceof LightNode) { - loadingResults.addLight((LightNode) object); - } else if (object instanceof CameraNode) { - loadingResults.addCamera((CameraNode) object); - } else if (object instanceof Node) { - if (LOGGER.isLoggable(Level.FINE)) { - LOGGER.log(Level.FINE, "{0}: {1}--> {2}", new Object[] { ((Node) object).getName(), ((Node) object).getLocalTranslation().toString(), ((Node) object).getParent() == null ? "null" : ((Node) object).getParent().getName() }); - } - if (this.isRootObject(loadingResults, (Node) object)) { - loadingResults.addObject((Node) object); - } + Node object = (Node) objectHelper.toObject(block.getStructure(blenderContext), blenderContext); + if (LOGGER.isLoggable(Level.FINE)) { + LOGGER.log(Level.FINE, "{0}: {1}--> {2}", new Object[] { object.getName(), object.getLocalTranslation().toString(), object.getParent() == null ? "null" : object.getParent().getName() }); } + if (object.getParent() == null) { + loadedFeatures.objects.add(object); + } + if (object instanceof LightNode && ((LightNode) object).getLight() != null) { + loadedFeatures.lights.add(((LightNode) object).getLight()); + } else if (object instanceof CameraNode && ((CameraNode) object).getCamera() != null) { + loadedFeatures.cameras.add(((CameraNode) object).getCamera()); + } + break; + case BLOCK_SC00:// Scene + loadedFeatures.sceneBlocks.add(block); break; -// case FileBlockHeader.BLOCK_MA00:// Material -// MaterialHelper materialHelper = blenderContext.getHelper(MaterialHelper.class); -// MaterialContext materialContext = materialHelper.toMaterialContext(block.getStructure(blenderContext), blenderContext); -// if (blenderKey.isLoadUnlinkedAssets() && blenderKey.shouldLoad(FeaturesToLoad.MATERIALS)) { -// loadingResults.addMaterial(this.toMaterial(block.getStructure(blenderContext))); -// } -// break; - case FileBlockHeader.BLOCK_SC00:// Scene - if (blenderKey.shouldLoad(FeaturesToLoad.SCENES)) { - sceneBlocks.add(block); + case BLOCK_MA00:// Material + MaterialHelper materialHelper = blenderContext.getHelper(MaterialHelper.class); + MaterialContext materialContext = materialHelper.toMaterialContext(block.getStructure(blenderContext), blenderContext); + loadedFeatures.materials.add(materialContext); + break; + case BLOCK_ME00:// Mesh + MeshHelper meshHelper = blenderContext.getHelper(MeshHelper.class); + TemporalMesh temporalMesh = meshHelper.toTemporalMesh(block.getStructure(blenderContext), blenderContext); + loadedFeatures.meshes.add(temporalMesh); + break; + case BLOCK_IM00:// Image + TextureHelper textureHelper = blenderContext.getHelper(TextureHelper.class); + Texture image = textureHelper.loadImageAsTexture(block.getStructure(blenderContext), 0, blenderContext); + if (image != null && image.getImage() != null) {// render results are stored as images but are not being loaded + loadedFeatures.images.add(image); } break; - case FileBlockHeader.BLOCK_WO00:// World - if (blenderKey.shouldLoad(FeaturesToLoad.WORLD)) { - Structure worldStructure = block.getStructure(blenderContext); - String worldName = worldStructure.getName(); - if (blenderKey.getUsedWorld() == null || blenderKey.getUsedWorld().equals(worldName)) { - LandscapeHelper landscapeHelper = blenderContext.getHelper(LandscapeHelper.class); - Light ambientLight = landscapeHelper.toAmbientLight(worldStructure); - if(ambientLight != null) { - loadingResults.addLight(new LightNode(null, ambientLight)); - } - loadingResults.setSky(landscapeHelper.toSky(worldStructure)); - loadingResults.addFilter(landscapeHelper.toFog(worldStructure)); - loadingResults.setBackgroundColor(landscapeHelper.toBackgroundColor(worldStructure)); + case BLOCK_TE00: + Structure textureStructure = block.getStructure(blenderContext); + int type = ((Number) textureStructure.getFieldValue("type")).intValue(); + if (type == TextureHelper.TEX_IMAGE) { + TextureHelper texHelper = blenderContext.getHelper(TextureHelper.class); + Texture texture = texHelper.getTexture(textureStructure, null, blenderContext); + if (texture != null) {// null is returned when texture has no image + loadedFeatures.textures.add(texture); } + } else { + LOGGER.fine("Only image textures can be loaded as unlinked assets. Generated textures will be applied to an existing object."); } break; + case BLOCK_WO00:// World + LandscapeHelper landscapeHelper = blenderContext.getHelper(LandscapeHelper.class); + Structure worldStructure = block.getStructure(blenderContext); + + String worldName = worldStructure.getName(); + if (blenderKey.getUsedWorld() == null || blenderKey.getUsedWorld().equals(worldName)) { + + Light ambientLight = landscapeHelper.toAmbientLight(worldStructure); + if (ambientLight != null) { + loadedFeatures.objects.add(new LightNode(null, ambientLight)); + loadedFeatures.lights.add(ambientLight); + } + loadedFeatures.sky = landscapeHelper.toSky(worldStructure); + loadedFeatures.backgroundColor = landscapeHelper.toBackgroundColor(worldStructure); + + Filter fogFilter = landscapeHelper.toFog(worldStructure); + if (fogFilter != null) { + loadedFeatures.filters.add(landscapeHelper.toFog(worldStructure)); + } + } + break; + case BLOCK_AC00: + LOGGER.fine("Loading unlinked animations is not yet supported!"); + break; + default: + LOGGER.log(Level.FINEST, "Ommiting the block: {0}.", block.getCode()); } } - // bake constraints after everything is loaded + LOGGER.fine("Baking constraints after every feature is loaded."); ConstraintHelper constraintHelper = blenderContext.getHelper(ConstraintHelper.class); constraintHelper.bakeConstraints(blenderContext); - // load the scene at the very end so that the root nodes have no parent during loading or constraints applying - for (FileBlockHeader sceneBlock : sceneBlocks) { - loadingResults.addScene(this.toScene(sceneBlock.getStructure(blenderContext))); + LOGGER.fine("Loading scenes and attaching them to the root object."); + for (FileBlockHeader sceneBlock : loadedFeatures.sceneBlocks) { + loadedFeatures.scenes.add(this.toScene(sceneBlock.getStructure(blenderContext))); + } + + LOGGER.fine("Creating the root node of the model and applying loaded nodes of the scene and loaded features to it."); + Node modelRoot = new Node(blenderKey.getName()); + for (Node scene : loadedFeatures.scenes) { + modelRoot.attachChild(scene); } - return loadingResults; + if (blenderKey.isLoadUnlinkedAssets()) { + LOGGER.fine("Setting loaded content as user data in resulting sptaial."); + Map> linkedData = new HashMap>(); + + Map thisFileData = new HashMap(); + thisFileData.put("scenes", loadedFeatures.scenes == null ? new ArrayList() : loadedFeatures.scenes); + thisFileData.put("objects", loadedFeatures.objects == null ? new ArrayList() : loadedFeatures.objects); + thisFileData.put("meshes", loadedFeatures.meshes == null ? new ArrayList() : loadedFeatures.meshes); + thisFileData.put("materials", loadedFeatures.materials == null ? new ArrayList() : loadedFeatures.materials); + thisFileData.put("textures", loadedFeatures.textures == null ? new ArrayList() : loadedFeatures.textures); + thisFileData.put("images", loadedFeatures.images == null ? new ArrayList() : loadedFeatures.images); + thisFileData.put("animations", loadedFeatures.animations == null ? new ArrayList() : loadedFeatures.animations); + thisFileData.put("cameras", loadedFeatures.cameras == null ? new ArrayList() : loadedFeatures.cameras); + thisFileData.put("lights", loadedFeatures.lights == null ? new ArrayList() : loadedFeatures.lights); + thisFileData.put("filters", loadedFeatures.filters == null ? new ArrayList() : loadedFeatures.filters); + thisFileData.put("backgroundColor", loadedFeatures.backgroundColor); + thisFileData.put("sky", loadedFeatures.sky); + + linkedData.put("this", thisFileData); + linkedData.putAll(blenderContext.getLinkedFeatures()); + + modelRoot.setUserData("linkedData", linkedData); + } + + return modelRoot; } catch (BlenderFileException e) { throw new IOException(e.getLocalizedMessage(), e); } catch (Exception e) { @@ -158,62 +224,36 @@ public class BlenderLoader implements AssetLoader { } } - /** - * This method indicates if the given spatial is a root object. It means it - * has no parent or is directly attached to one of the already loaded scene - * nodes. - * - * @param loadingResults - * loading results containing the scene nodes - * @param spatial - * spatial object - * @return true if the given spatial is a root object and - * false otherwise - */ - protected boolean isRootObject(LoadingResults loadingResults, Spatial spatial) { - if (spatial.getParent() == null) { - return true; - } - for (Node scene : loadingResults.getScenes()) { - if (spatial.getParent().equals(scene)) { - return true; - } - } - return false; - } - /** * This method converts the given structure to a scene node. * @param structure * structure of a scene * @return scene's node + * @throws BlenderFileException + * an exception throw when problems with blender file occur */ - private Node toScene(Structure structure) { + private Node toScene(Structure structure) throws BlenderFileException { ObjectHelper objectHelper = blenderContext.getHelper(ObjectHelper.class); Node result = new Node(structure.getName()); - try { - List base = ((Structure) structure.getFieldValue("base")).evaluateListBase(); - for (Structure b : base) { - Pointer pObject = (Pointer) b.getFieldValue("object"); - if (pObject.isNotNull()) { - Structure objectStructure = pObject.fetchData().get(0); + List base = ((Structure) structure.getFieldValue("base")).evaluateListBase(); + for (Structure b : base) { + Pointer pObject = (Pointer) b.getFieldValue("object"); + if (pObject.isNotNull()) { + Structure objectStructure = pObject.fetchData().get(0); - Object object = objectHelper.toObject(objectStructure, blenderContext); - if (object instanceof LightNode) { - result.addLight(((LightNode) object).getLight()); - result.attachChild((LightNode) object); - } else if (object instanceof Node) { - if (LOGGER.isLoggable(Level.FINE)) { - LOGGER.log(Level.FINE, "{0}: {1}--> {2}", new Object[] { ((Node) object).getName(), ((Node) object).getLocalTranslation().toString(), ((Node) object).getParent() == null ? "null" : ((Node) object).getParent().getName() }); - } - if (((Node) object).getParent() == null) { - result.attachChild((Spatial) object); - } + Object object = objectHelper.toObject(objectStructure, blenderContext); + if (object instanceof LightNode) { + result.addLight(((LightNode) object).getLight());// FIXME: check if this is needed !!! + result.attachChild((LightNode) object); + } else if (object instanceof Node) { + if (LOGGER.isLoggable(Level.FINE)) { + LOGGER.log(Level.FINE, "{0}: {1}--> {2}", new Object[] { ((Node) object).getName(), ((Node) object).getLocalTranslation().toString(), ((Node) object).getParent() == null ? "null" : ((Node) object).getParent().getName() }); + } + if (((Node) object).getParent() == null) { + result.attachChild((Spatial) object); } } } - } catch (BlenderFileException e) { - LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e); } return result; } @@ -261,7 +301,7 @@ public class BlenderLoader implements AssetLoader { blenderContext.putHelper(ConstraintHelper.class, new ConstraintHelper(inputStream.getVersionNumber(), blenderContext)); blenderContext.putHelper(ParticlesHelper.class, new ParticlesHelper(inputStream.getVersionNumber(), blenderContext)); blenderContext.putHelper(LandscapeHelper.class, new LandscapeHelper(inputStream.getVersionNumber(), blenderContext)); - + // reading the blocks (dna block is automatically saved in the blender context when found) FileBlockHeader sceneFileBlock = null; do { @@ -269,7 +309,7 @@ public class BlenderLoader implements AssetLoader { if (!fileBlock.isDnaBlock()) { blocks.add(fileBlock); // save the scene's file block - if (fileBlock.getCode() == FileBlockHeader.BLOCK_SC00) { + if (fileBlock.getCode() == BlockCode.BLOCK_SC00) { sceneFileBlock = fileBlock; } } @@ -287,4 +327,39 @@ public class BlenderLoader implements AssetLoader { blenderContext = null; blocks = null; } + + /** + * This class holds the loading results according to the given loading flag. + * @author Marcin Roguski (Kaelthas) + */ + private static class LoadedFeatures { + private List sceneBlocks = new ArrayList(); + /** The scenes from the file. */ + private List scenes = new ArrayList(); + /** Objects from all scenes. */ + private List objects = new ArrayList(); + /** All meshes. */ + private List meshes = new ArrayList(); + /** Materials from all objects. */ + private List materials = new ArrayList(); + /** Textures from all objects. */ + private List textures = new ArrayList(); + /** The images stored in the blender file. */ + private List images = new ArrayList(); + /** Animations of all objects. */ + private List animations = new ArrayList(); + /** All cameras from the file. */ + private List cameras = new ArrayList(); + /** All lights from the file. */ + private List lights = new ArrayList(); + /** Loaded sky. */ + private Spatial sky; + /** Scene filters (ie. FOG). */ + private List filters = new ArrayList(); + /** + * The background color of the render loaded from the horizon color of the world. If no world is used than the gray color + * is set to default (as in blender editor. + */ + private ColorRGBA backgroundColor = ColorRGBA.Gray; + } } diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/BlenderModelLoader.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/BlenderModelLoader.java index 021a6082f..eae047421 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/BlenderModelLoader.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/BlenderModelLoader.java @@ -31,79 +31,10 @@ */ package com.jme3.scene.plugins.blender; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.jme3.asset.AssetInfo; -import com.jme3.asset.BlenderKey; -import com.jme3.asset.BlenderKey.FeaturesToLoad; -import com.jme3.scene.LightNode; -import com.jme3.scene.Node; -import com.jme3.scene.Spatial; -import com.jme3.scene.plugins.blender.animations.AnimationHelper; -import com.jme3.scene.plugins.blender.constraints.ConstraintHelper; -import com.jme3.scene.plugins.blender.file.BlenderFileException; -import com.jme3.scene.plugins.blender.file.FileBlockHeader; -import com.jme3.scene.plugins.blender.objects.ObjectHelper; - /** * This is the main loading class. Have in notice that asset manager needs to have loaders for resources like textures. - * + * @deprecated this class is deprecated; use BlenderLoader instead * @author Marcin Roguski (Kaelthas) */ public class BlenderModelLoader extends BlenderLoader { - - private static final Logger LOGGER = Logger.getLogger(BlenderModelLoader.class.getName()); - - @Override - public Spatial load(AssetInfo assetInfo) throws IOException { - try { - this.setup(assetInfo); - - AnimationHelper animationHelper = blenderContext.getHelper(AnimationHelper.class); - animationHelper.loadAnimations(); - - BlenderKey blenderKey = blenderContext.getBlenderKey(); - List rootObjects = new ArrayList(); - for (FileBlockHeader block : blocks) { - if (block.getCode() == FileBlockHeader.BLOCK_OB00) { - ObjectHelper objectHelper = blenderContext.getHelper(ObjectHelper.class); - Object object = objectHelper.toObject(block.getStructure(blenderContext), blenderContext); - if (object instanceof LightNode && (blenderKey.getFeaturesToLoad() & FeaturesToLoad.LIGHTS) != 0) { - rootObjects.add((LightNode) object); - } else if (object instanceof Node && (blenderKey.getFeaturesToLoad() & FeaturesToLoad.OBJECTS) != 0) { - LOGGER.log(Level.FINE, "{0}: {1}--> {2}", new Object[] { ((Node) object).getName(), ((Node) object).getLocalTranslation().toString(), ((Node) object).getParent() == null ? "null" : ((Node) object).getParent().getName() }); - if (((Node) object).getParent() == null) { - rootObjects.add((Node) object); - } - } - } - } - - // bake constraints after everything is loaded - ConstraintHelper constraintHelper = blenderContext.getHelper(ConstraintHelper.class); - constraintHelper.bakeConstraints(blenderContext); - - // attach the nodes to the root node at the very end so that the root objects have no parents during constraint applying - LOGGER.fine("Creating the root node of the model and applying loaded nodes of the scene to it."); - Node modelRoot = new Node(blenderKey.getName()); - for (Node node : rootObjects) { - if (node instanceof LightNode) { - modelRoot.addLight(((LightNode) node).getLight()); - } - modelRoot.attachChild(node); - } - - return modelRoot; - } catch (BlenderFileException e) { - throw new IOException(e.getLocalizedMessage(), e); - } catch (Exception e) { - throw new IOException("Unexpected importer exception occured: " + e.getLocalizedMessage(), e); - } finally { - this.clear(); - } - } } diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/animations/AnimationHelper.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/animations/AnimationHelper.java index 1b5a40e79..1d889f992 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/animations/AnimationHelper.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/animations/AnimationHelper.java @@ -25,6 +25,7 @@ import com.jme3.scene.plugins.blender.curves.BezierCurve; import com.jme3.scene.plugins.blender.file.BlenderFileException; import com.jme3.scene.plugins.blender.file.BlenderInputStream; import com.jme3.scene.plugins.blender.file.FileBlockHeader; +import com.jme3.scene.plugins.blender.file.FileBlockHeader.BlockCode; import com.jme3.scene.plugins.blender.file.Pointer; import com.jme3.scene.plugins.blender.file.Structure; import com.jme3.scene.plugins.blender.objects.ObjectHelper; @@ -48,7 +49,7 @@ public class AnimationHelper extends AbstractBlenderHelper { */ public void loadAnimations() throws BlenderFileException { LOGGER.info("Loading animations that will be later applied to scene features."); - List actionHeaders = blenderContext.getFileBlocks(Integer.valueOf(FileBlockHeader.BLOCK_AC00)); + List actionHeaders = blenderContext.getFileBlocks(BlockCode.BLOCK_AC00); if (actionHeaders != null) { for (FileBlockHeader header : actionHeaders) { Structure actionStructure = header.getStructure(blenderContext); @@ -70,7 +71,7 @@ public class AnimationHelper extends AbstractBlenderHelper { if (actions.size() > 0) { List animations = new ArrayList(); for (BlenderAction action : actions) { - SpatialTrack[] tracks = action.toTracks(node); + SpatialTrack[] tracks = action.toTracks(node, blenderContext); if (tracks != null && tracks.length > 0) { Animation spatialAnimation = new Animation(action.getName(), action.getAnimationTime()); spatialAnimation.setTracks(tracks); @@ -109,7 +110,7 @@ public class AnimationHelper extends AbstractBlenderHelper { if (actions.size() > 0) { List animations = new ArrayList(); for (BlenderAction action : actions) { - BoneTrack[] tracks = action.toTracks(skeleton); + BoneTrack[] tracks = action.toTracks(skeleton, blenderContext); if (tracks != null && tracks.length > 0) { Animation boneAnimation = new Animation(action.getName(), action.getAnimationTime()); boneAnimation.setTracks(tracks); diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/animations/BlenderAction.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/animations/BlenderAction.java index aa36c918e..38a437ba0 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/animations/BlenderAction.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/animations/BlenderAction.java @@ -10,9 +10,8 @@ import java.util.Map.Entry; import com.jme3.animation.BoneTrack; import com.jme3.animation.Skeleton; import com.jme3.animation.SpatialTrack; -import com.jme3.math.Quaternion; -import com.jme3.math.Vector3f; import com.jme3.scene.Node; +import com.jme3.scene.plugins.blender.BlenderContext; /** * An abstract representation of animation. The data stored here is mainly a @@ -69,10 +68,10 @@ public class BlenderAction implements Cloneable { * the node that will be animated * @return the spatial tracks for the node */ - public SpatialTrack[] toTracks(Node node) { + public SpatialTrack[] toTracks(Node node, BlenderContext blenderContext) { List tracks = new ArrayList(featuresTracks.size()); for (Entry entry : featuresTracks.entrySet()) { - tracks.add((SpatialTrack) entry.getValue().calculateTrack(0, node.getLocalTranslation(), node.getLocalRotation(), node.getLocalScale(), 1, stopFrame, fps, true)); + tracks.add((SpatialTrack) entry.getValue().calculateTrack(0, null, node.getLocalTranslation(), node.getLocalRotation(), node.getLocalScale(), 1, stopFrame, fps, true)); } return tracks.toArray(new SpatialTrack[tracks.size()]); } @@ -84,11 +83,12 @@ public class BlenderAction implements Cloneable { * the skeleton that will be animated * @return the bone tracks for the node */ - public BoneTrack[] toTracks(Skeleton skeleton) { + public BoneTrack[] toTracks(Skeleton skeleton, BlenderContext blenderContext) { List tracks = new ArrayList(featuresTracks.size()); for (Entry entry : featuresTracks.entrySet()) { int boneIndex = skeleton.getBoneIndex(entry.getKey()); - tracks.add((BoneTrack) entry.getValue().calculateTrack(boneIndex, Vector3f.ZERO, Quaternion.IDENTITY, Vector3f.UNIT_XYZ, 1, stopFrame, fps, false)); + BoneContext boneContext = blenderContext.getBoneContext(skeleton.getBone(boneIndex)); + tracks.add((BoneTrack) entry.getValue().calculateTrack(boneIndex, boneContext, boneContext.getBone().getBindPosition(), boneContext.getBone().getBindRotation(), boneContext.getBone().getBindScale(), 1, stopFrame, fps, false)); } return tracks.toArray(new BoneTrack[tracks.size()]); } diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/animations/BoneContext.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/animations/BoneContext.java index 0eb50fb65..adc0a5c4c 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/animations/BoneContext.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/animations/BoneContext.java @@ -25,10 +25,13 @@ import com.jme3.scene.plugins.blender.objects.ObjectHelper; */ public class BoneContext { // the flags of the bone - public static final int SELECTED = 0x0001; - public static final int CONNECTED_TO_PARENT = 0x0010; - public static final int DEFORM = 0x1000; - + public static final int SELECTED = 0x000001; + public static final int CONNECTED_TO_PARENT = 0x000010; + public static final int DEFORM = 0x001000; + public static final int NO_LOCAL_LOCATION = 0x400000; + public static final int NO_INHERIT_SCALE = 0x008000; + public static final int NO_INHERIT_ROTATION = 0x000200; + /** * The bones' matrices have, unlike objects', the coordinate system identical to JME's (Y axis is UP, X to the right and Z toward us). * So in order to have them loaded properly we need to transform their armature matrix (which blender sees as rotated) to make sure we get identical results. diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/animations/Ipo.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/animations/Ipo.java index f388b703f..f5113129f 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/animations/Ipo.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/animations/Ipo.java @@ -137,7 +137,7 @@ public class Ipo { * as jme while other features have different one (Z is UP) * @return bone track for the specified bone */ - public Track calculateTrack(int targetIndex, Vector3f localTranslation, Quaternion localRotation, Vector3f localScale, int startFrame, int stopFrame, int fps, boolean spatialTrack) { + public Track calculateTrack(int targetIndex, BoneContext boneContext, Vector3f localTranslation, Quaternion localRotation, Vector3f localScale, int startFrame, int stopFrame, int fps, boolean spatialTrack) { if (calculatedTrack == null) { // preparing data for track int framesAmount = stopFrame - startFrame; @@ -236,6 +236,15 @@ public class Ipo { } } translations[index] = localRotation.multLocal(new Vector3f(translation[0], translation[1], translation[2])); + + if(boneContext != null) { + if(boneContext.getBone().getParent() == null && boneContext.is(BoneContext.NO_LOCAL_LOCATION)) { + float temp = translations[index].z; + translations[index].z = -translations[index].y; + translations[index].y = temp; + } + } + if (queternionRotationUsed) { rotations[index] = new Quaternion(quaternionRotation[0], quaternionRotation[1], quaternionRotation[2], quaternionRotation[3]); } else { @@ -292,7 +301,7 @@ public class Ipo { } @Override - public BoneTrack calculateTrack(int boneIndex, Vector3f localTranslation, Quaternion localRotation, Vector3f localScale, int startFrame, int stopFrame, int fps, boolean boneTrack) { + public BoneTrack calculateTrack(int boneIndex, BoneContext boneContext, Vector3f localTranslation, Quaternion localRotation, Vector3f localScale, int startFrame, int stopFrame, int fps, boolean boneTrack) { throw new IllegalStateException("Constatnt ipo object cannot be used for calculating bone tracks!"); } } diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/cameras/CameraHelper.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/cameras/CameraHelper.java index c5e1f0192..70cb09b1f 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/cameras/CameraHelper.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/cameras/CameraHelper.java @@ -5,7 +5,6 @@ import java.util.logging.Logger; import com.jme3.math.FastMath; import com.jme3.renderer.Camera; -import com.jme3.scene.CameraNode; import com.jme3.scene.plugins.blender.AbstractBlenderHelper; import com.jme3.scene.plugins.blender.BlenderContext; import com.jme3.scene.plugins.blender.file.BlenderFileException; @@ -43,7 +42,7 @@ public class CameraHelper extends AbstractBlenderHelper { * an exception is thrown when there are problems with the * blender file */ - public CameraNode toCamera(Structure structure, BlenderContext blenderContext) throws BlenderFileException { + public Camera toCamera(Structure structure, BlenderContext blenderContext) throws BlenderFileException { if (blenderVersion >= 250) { return this.toCamera250(structure, blenderContext.getSceneStructure()); } else { @@ -63,7 +62,7 @@ public class CameraHelper extends AbstractBlenderHelper { * an exception is thrown when there are problems with the * blender file */ - private CameraNode toCamera250(Structure structure, Structure sceneStructure) throws BlenderFileException { + private Camera toCamera250(Structure structure, Structure sceneStructure) throws BlenderFileException { int width = DEFAULT_CAM_WIDTH; int height = DEFAULT_CAM_HEIGHT; if (sceneStructure != null) { @@ -99,7 +98,7 @@ public class CameraHelper extends AbstractBlenderHelper { sensor = ((Number) structure.getFieldValue(sensorName)).floatValue(); } float focalLength = ((Number) structure.getFieldValue("lens")).floatValue(); - float fov = 2.0f * FastMath.atan((sensor / 2.0f) / focalLength); + float fov = 2.0f * FastMath.atan(sensor / 2.0f / focalLength); if (sensorVertical) { fovY = fov * FastMath.RAD_TO_DEG; } else { @@ -111,7 +110,8 @@ public class CameraHelper extends AbstractBlenderHelper { fovY = ((Number) structure.getFieldValue("ortho_scale")).floatValue(); } camera.setFrustumPerspective(fovY, aspect, clipsta, clipend); - return new CameraNode(null, camera); + camera.setName(structure.getName()); + return camera; } /** @@ -124,7 +124,7 @@ public class CameraHelper extends AbstractBlenderHelper { * an exception is thrown when there are problems with the * blender file */ - private CameraNode toCamera249(Structure structure) throws BlenderFileException { + private Camera toCamera249(Structure structure) throws BlenderFileException { Camera camera = new Camera(DEFAULT_CAM_WIDTH, DEFAULT_CAM_HEIGHT); int type = ((Number) structure.getFieldValue("type")).intValue(); if (type != 0 && type != 1) { @@ -142,6 +142,7 @@ public class CameraHelper extends AbstractBlenderHelper { aspect = ((Number) structure.getFieldValue("ortho_scale")).floatValue(); } camera.setFrustumPerspective(aspect, camera.getWidth() / camera.getHeight(), clipsta, clipend); - return new CameraNode(null, camera); + camera.setName(structure.getName()); + return camera; } } diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/constraints/Constraint.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/constraints/Constraint.java index 91cfd2f3f..f2268199c 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/constraints/Constraint.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/constraints/Constraint.java @@ -64,7 +64,7 @@ public abstract class Constraint { Pointer pData = (Pointer) constraintStructure.getFieldValue("data"); if (pData.isNotNull()) { Structure data = pData.fetchData().get(0); - constraintDefinition = ConstraintDefinitionFactory.createConstraintDefinition(data, ownerOMA, blenderContext); + constraintDefinition = ConstraintDefinitionFactory.createConstraintDefinition(data, name, ownerOMA, blenderContext); Pointer pTar = (Pointer) data.getFieldValue("tar"); if (pTar != null && pTar.isNotNull()) { targetOMA = pTar.getOldMemoryAddress(); @@ -77,7 +77,7 @@ public abstract class Constraint { } } else { // Null constraint has no data, so create it here - constraintDefinition = ConstraintDefinitionFactory.createConstraintDefinition(null, null, blenderContext); + constraintDefinition = ConstraintDefinitionFactory.createConstraintDefinition(null, name, null, blenderContext); } ownerSpace = Space.valueOf(((Number) constraintStructure.getFieldValue("ownspace")).byteValue()); ipo = influenceIpo; diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/constraints/SimulationNode.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/constraints/SimulationNode.java index 031676b94..711e0a338 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/constraints/SimulationNode.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/constraints/SimulationNode.java @@ -7,6 +7,7 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; +import java.util.Stack; import java.util.logging.Logger; import com.jme3.animation.AnimChannel; @@ -38,9 +39,9 @@ import com.jme3.util.TempVars; * @author Marcin Roguski (Kaelthas) */ public class SimulationNode { - private static final Logger LOGGER = Logger.getLogger(SimulationNode.class.getName()); + private static final Logger LOGGER = Logger.getLogger(SimulationNode.class.getName()); - private Long featureOMA; + private Long featureOMA; /** The blender context. */ private BlenderContext blenderContext; /** The name of the node (for debugging purposes). */ @@ -51,11 +52,11 @@ public class SimulationNode { private List animations; /** The nodes spatial (if null then the boneContext should be set). */ - private Spatial spatial; + private Spatial spatial; /** The skeleton of the bone (not null if the node simulated the bone). */ - private Skeleton skeleton; + private Skeleton skeleton; /** Animation controller for the node's feature. */ - private AnimControl animControl; + private AnimControl animControl; /** * The star transform of a spatial. Needed to properly reset the spatial to @@ -64,7 +65,7 @@ public class SimulationNode { private Transform spatialStartTransform; /** Star transformations for bones. Needed to properly reset the bones. */ private Map boneStartTransforms; - + /** * Builds the nodes tree for the given feature. The feature (bone or * spatial) is found by its OMA. The feature must be a root bone or a root @@ -208,8 +209,7 @@ public class SimulationNode { if (animations != null) { TempVars vars = TempVars.get(); AnimChannel animChannel = animControl.createChannel(); - - // List bonesWithConstraints = this.collectBonesWithConstraints(skeleton); + for (Animation animation : animations) { float[] animationTimeBoundaries = this.computeAnimationTimeBoundaries(animation); int maxFrame = (int) animationTimeBoundaries[0]; @@ -233,7 +233,7 @@ public class SimulationNode { for (Bone rootBone : skeleton.getRoots()) { // ignore the 0-indexed bone if (skeleton.getBoneIndex(rootBone) > 0) { - this.applyConstraints(rootBone, alteredOmas, applied, frame); + this.applyConstraints(rootBone, alteredOmas, applied, frame, new Stack()); } } @@ -294,34 +294,39 @@ public class SimulationNode { * the set of OMAS of the altered bones (is populated if necessary) * @param frame * the current frame of the animation + * @param bonesStack + * the stack of bones used to avoid infinite loops while applying constraints */ - private void applyConstraints(Bone bone, Set alteredOmas, Set applied, int frame) { - BoneContext boneContext = blenderContext.getBoneContext(bone); - if(!applied.contains(boneContext.getBoneOma())) { - List constraints = this.findConstraints(boneContext.getBoneOma(), blenderContext); - if (constraints != null && constraints.size() > 0) { - // TODO: BEWARE OF INFINITE LOOPS !!!!!!!!!!!!!!!!!!!!!!!!!! - for (Constraint constraint : constraints) { - if (constraint.getTargetOMA() != null && constraint.getTargetOMA() > 0L) { - // first apply constraints of the target bone - BoneContext targetBone = blenderContext.getBoneContext(constraint.getTargetOMA()); - this.applyConstraints(targetBone.getBone(), alteredOmas, applied, frame); - } - constraint.apply(frame); - if (constraint.getAlteredOmas() != null) { - alteredOmas.addAll(constraint.getAlteredOmas()); + private void applyConstraints(Bone bone, Set alteredOmas, Set applied, int frame, Stack bonesStack) { + if (!bonesStack.contains(bone)) { + bonesStack.push(bone); + BoneContext boneContext = blenderContext.getBoneContext(bone); + if (!applied.contains(boneContext.getBoneOma())) { + List constraints = this.findConstraints(boneContext.getBoneOma(), blenderContext); + if (constraints != null && constraints.size() > 0) { + for (Constraint constraint : constraints) { + if (constraint.getTargetOMA() != null && constraint.getTargetOMA() > 0L) { + // first apply constraints of the target bone + BoneContext targetBone = blenderContext.getBoneContext(constraint.getTargetOMA()); + this.applyConstraints(targetBone.getBone(), alteredOmas, applied, frame, bonesStack); + } + constraint.apply(frame); + if (constraint.getAlteredOmas() != null) { + alteredOmas.addAll(constraint.getAlteredOmas()); + } + alteredOmas.add(boneContext.getBoneOma()); } - alteredOmas.add(boneContext.getBoneOma()); } + applied.add(boneContext.getBoneOma()); } - applied.add(boneContext.getBoneOma()); - } - - List children = bone.getChildren(); - if (children != null && children.size() > 0) { - for (Bone child : bone.getChildren()) { - this.applyConstraints(child, alteredOmas, applied, frame); + + List children = bone.getChildren(); + if (children != null && children.size() > 0) { + for (Bone child : bone.getChildren()) { + this.applyConstraints(child, alteredOmas, applied, frame, bonesStack); + } } + bonesStack.pop(); } } diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/constraints/definitions/ConstraintDefinition.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/constraints/definitions/ConstraintDefinition.java index 346554052..a1f3a7316 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/constraints/definitions/ConstraintDefinition.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/constraints/definitions/ConstraintDefinition.java @@ -30,6 +30,8 @@ public abstract class ConstraintDefinition { protected Set alteredOmas; /** The variable that determines if the constraint will alter the track in any way. */ protected boolean trackToBeChanged = true; + /** The name of the constraint. */ + protected String constraintName; /** * Loads a constraint definition based on the constraint definition @@ -53,6 +55,10 @@ public abstract class ConstraintDefinition { constraintHelper = (ConstraintHelper) (blenderContext == null ? null : blenderContext.getHelper(ConstraintHelper.class)); this.ownerOMA = ownerOMA; } + + public void setConstraintName(String constraintName) { + this.constraintName = constraintName; + } /** * @return determines if the definition of the constraint will change the bone in any way; in most cases diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/constraints/definitions/ConstraintDefinitionFactory.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/constraints/definitions/ConstraintDefinitionFactory.java index cbf727290..c1d69fe06 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/constraints/definitions/ConstraintDefinitionFactory.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/constraints/definitions/ConstraintDefinitionFactory.java @@ -92,7 +92,7 @@ public class ConstraintDefinitionFactory { * this exception is thrown when the blender file is somehow * corrupted */ - public static ConstraintDefinition createConstraintDefinition(Structure constraintStructure, Long ownerOMA, BlenderContext blenderContext) throws BlenderFileException { + public static ConstraintDefinition createConstraintDefinition(Structure constraintStructure, String constraintName, Long ownerOMA, BlenderContext blenderContext) throws BlenderFileException { if (constraintStructure == null) { return new ConstraintDefinitionNull(null, ownerOMA, blenderContext); } @@ -100,7 +100,9 @@ public class ConstraintDefinitionFactory { Class constraintDefinitionClass = CONSTRAINT_CLASSES.get(constraintClassName); if (constraintDefinitionClass != null) { try { - return (ConstraintDefinition) constraintDefinitionClass.getDeclaredConstructors()[0].newInstance(constraintStructure, ownerOMA, blenderContext); + ConstraintDefinition def = (ConstraintDefinition) constraintDefinitionClass.getDeclaredConstructors()[0].newInstance(constraintStructure, ownerOMA, blenderContext); + def.setConstraintName(constraintName); + return def; } catch (IllegalArgumentException e) { throw new BlenderFileException(e.getLocalizedMessage(), e); } catch (SecurityException e) { @@ -113,9 +115,9 @@ public class ConstraintDefinitionFactory { throw new BlenderFileException(e.getLocalizedMessage(), e); } } else { - String constraintName = UNSUPPORTED_CONSTRAINTS.get(constraintClassName); - if (constraintName != null) { - return new UnsupportedConstraintDefinition(constraintName); + String unsupportedConstraintClassName = UNSUPPORTED_CONSTRAINTS.get(constraintClassName); + if (unsupportedConstraintClassName != null) { + return new UnsupportedConstraintDefinition(unsupportedConstraintClassName); } else { throw new BlenderFileException("Unknown constraint type: " + constraintClassName); } diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/constraints/definitions/ConstraintDefinitionIK.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/constraints/definitions/ConstraintDefinitionIK.java index 1d6139e04..69e087a28 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/constraints/definitions/ConstraintDefinitionIK.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/constraints/definitions/ConstraintDefinitionIK.java @@ -1,40 +1,44 @@ package com.jme3.scene.plugins.blender.constraints.definitions; import java.util.ArrayList; -import java.util.Collections; +import java.util.Collection; import java.util.HashSet; import java.util.List; +import org.ejml.simple.SimpleMatrix; + import com.jme3.animation.Bone; import com.jme3.math.Transform; -import com.jme3.math.Vector3f; import com.jme3.scene.plugins.blender.BlenderContext; import com.jme3.scene.plugins.blender.animations.BoneContext; +import com.jme3.scene.plugins.blender.constraints.ConstraintHelper; import com.jme3.scene.plugins.blender.constraints.ConstraintHelper.Space; import com.jme3.scene.plugins.blender.file.Structure; import com.jme3.scene.plugins.blender.math.DQuaternion; import com.jme3.scene.plugins.blender.math.DTransform; +import com.jme3.scene.plugins.blender.math.Matrix; import com.jme3.scene.plugins.blender.math.Vector3d; /** - * The Inverse Kinematics constraint. + * A definiotion of a Inverse Kinematics constraint. This implementation uses Jacobian pseudoinverse algorithm. * - * @author Wesley Shillingford (wezrule) * @author Marcin Roguski (Kaelthas) */ public class ConstraintDefinitionIK extends ConstraintDefinition { - private static final float MIN_DISTANCE = 0.0001f; - private static final int FLAG_USE_TAIL = 0x01; - private static final int FLAG_POSITION = 0x20; + private static final float MIN_DISTANCE = 0.001f; + private static final float MIN_ANGLE_CHANGE = 0.001f; + private static final int FLAG_USE_TAIL = 0x01; + private static final int FLAG_POSITION = 0x20; + private BonesChain bones; /** The number of affected bones. Zero means that all parent bones of the current bone should take part in baking. */ - private int bonesAffected; - /** The total length of the bone chain. Useful for optimisation of computations speed in some cases. */ - private double chainLength; + private int bonesAffected; /** Indicates if the tail of the bone should be used or not. */ - private boolean useTail; + private boolean useTail; /** The amount of iterations of the algorithm. */ - private int iterations; + private int iterations; + /** The count of bones' chain. */ + private int bonesCount = -1; public ConstraintDefinitionIK(Structure constraintData, Long ownerOMA, BlenderContext blenderContext) { super(constraintData, ownerOMA, blenderContext); @@ -51,101 +55,104 @@ public class ConstraintDefinitionIK extends ConstraintDefinition { } } + /** + * Below are the variables that only need to be allocated once for IK constraint instance. + */ + /** Temporal quaternion. */ + private DQuaternion tempDQuaternion = new DQuaternion(); + /** Temporal matrix column. */ + private Vector3d col = new Vector3d(); + /** Effector's position change. */ + private Matrix deltaP = new Matrix(3, 1); + /** The current target position. */ + private Vector3d target = new Vector3d(); + /** Rotation vectors for each joint (allocated when we know the size of a bones' chain. */ + private Vector3d[] rotationVectors; + /** The Jacobian matrix. Allocated when the bones' chain size is known. */ + private Matrix J; + @Override public void bake(Space ownerSpace, Space targetSpace, Transform targetTransform, float influence) { - if (influence == 0 || !trackToBeChanged || targetTransform == null) { + if (influence == 0 || !trackToBeChanged || targetTransform == null || bonesCount == 0) { return;// no need to do anything } - DQuaternion q = new DQuaternion(); - Vector3d t = new Vector3d(targetTransform.getTranslation()); - List bones = this.loadBones(); + + if (bones == null) { + bones = new BonesChain((Bone) this.getOwner(), useTail, bonesAffected, alteredOmas, blenderContext); + } if (bones.size() == 0) { + bonesCount = 0; return;// no need to do anything } double distanceFromTarget = Double.MAX_VALUE; + target.set(targetTransform.getTranslation().x, targetTransform.getTranslation().y, targetTransform.getTranslation().z); - int iterations = this.iterations; - if (bones.size() == 1) { - iterations = 1;// if only one bone is in the chain then only one iteration that will properly rotate it will be needed - } else { - // if the target cannot be rached by the bones' chain then the chain will become straight and point towards the target - // in this case only one iteration will be needed, computed from the root to top bone - BoneContext rootBone = bones.get(bones.size() - 1); - Transform rootBoneTransform = constraintHelper.getTransform(rootBone.getArmatureObjectOMA(), rootBone.getBone().getName(), Space.CONSTRAINT_SPACE_WORLD); - if (t.distance(new Vector3d(rootBoneTransform.getTranslation())) >= chainLength) { - Collections.reverse(bones); - - for (BoneContext boneContext : bones) { - Bone bone = boneContext.getBone(); - DTransform boneTransform = new DTransform(constraintHelper.getTransform(boneContext.getArmatureObjectOMA(), bone.getName(), Space.CONSTRAINT_SPACE_WORLD)); - - Vector3d e = boneTransform.getTranslation().add(boneTransform.getRotation().mult(Vector3d.UNIT_Y).multLocal(boneContext.getLength()));// effector - Vector3d j = boneTransform.getTranslation(); // current join position - - Vector3d currentDir = e.subtractLocal(j).normalizeLocal(); - Vector3d target = t.subtract(j).normalizeLocal(); - double angle = currentDir.angleBetween(target); - if (angle != 0) { - Vector3d cross = currentDir.crossLocal(target).normalizeLocal(); - q.fromAngleAxis(angle, cross); - if (boneContext.isLockX()) { - q.set(0, q.getY(), q.getZ(), q.getW()); - } - if (boneContext.isLockY()) { - q.set(q.getX(), 0, q.getZ(), q.getW()); - } - if (boneContext.isLockZ()) { - q.set(q.getX(), q.getY(), 0, q.getW()); - } - - boneTransform.getRotation().set(q.multLocal(boneTransform.getRotation())); - constraintHelper.applyTransform(boneContext.getArmatureObjectOMA(), bone.getName(), Space.CONSTRAINT_SPACE_WORLD, boneTransform.toTransform()); - } - } - - iterations = 0; + if (bonesCount < 0) { + bonesCount = bones.size(); + rotationVectors = new Vector3d[bonesCount]; + for (int i = 0; i < bonesCount; ++i) { + rotationVectors[i] = new Vector3d(); } + J = new Matrix(3, bonesCount); } BoneContext topBone = bones.get(0); - for (int i = 0; i < iterations && distanceFromTarget > MIN_DISTANCE; ++i) { - for (BoneContext boneContext : bones) { - Bone bone = boneContext.getBone(); - DTransform topBoneTransform = new DTransform(constraintHelper.getTransform(topBone.getArmatureObjectOMA(), topBone.getBone().getName(), Space.CONSTRAINT_SPACE_WORLD)); - DTransform boneWorldTransform = new DTransform(constraintHelper.getTransform(boneContext.getArmatureObjectOMA(), bone.getName(), Space.CONSTRAINT_SPACE_WORLD)); + for (int i = 0; i < iterations; ++i) { + DTransform topBoneTransform = bones.getWorldTransform(topBone); + Vector3d e = topBoneTransform.getTranslation().add(topBoneTransform.getRotation().mult(Vector3d.UNIT_Y).multLocal(topBone.getLength()));// effector + distanceFromTarget = e.distance(target); + if (distanceFromTarget <= MIN_DISTANCE) { + break; + } - Vector3d e = topBoneTransform.getTranslation().addLocal(topBoneTransform.getRotation().mult(Vector3d.UNIT_Y).multLocal(topBone.getLength()));// effector + deltaP.setColumn(0, 0, target.x - e.x, target.y - e.y, target.z - e.z); + int column = 0; + for (BoneContext boneContext : bones) { + DTransform boneWorldTransform = bones.getWorldTransform(boneContext); Vector3d j = boneWorldTransform.getTranslation(); // current join position + Vector3d vectorFromJointToEffector = e.subtract(j); + vectorFromJointToEffector.cross(target.subtract(j), rotationVectors[column]).normalizeLocal(); + rotationVectors[column].cross(vectorFromJointToEffector, col); + J.setColumn(col, column++); + } + Matrix J_1 = J.pseudoinverse(); - Vector3d currentDir = e.subtractLocal(j).normalizeLocal(); - Vector3d target = t.subtract(j).normalizeLocal(); - double angle = currentDir.angleBetween(target); - if (angle != 0) { - Vector3d cross = currentDir.crossLocal(target).normalizeLocal(); - q.fromAngleAxis(angle, cross); + SimpleMatrix deltaThetas = J_1.mult(deltaP); + if (deltaThetas.elementMaxAbs() < MIN_ANGLE_CHANGE) { + break; + } + for (int j = 0; j < deltaThetas.numRows(); ++j) { + double angle = deltaThetas.get(j, 0); + Vector3d rotationVector = rotationVectors[j]; + tempDQuaternion.fromAngleAxis(angle, rotationVector); + BoneContext boneContext = bones.get(j); + Bone bone = boneContext.getBone(); + if (bone.equals(this.getOwner())) { if (boneContext.isLockX()) { - q.set(0, q.getY(), q.getZ(), q.getW()); + tempDQuaternion.set(0, tempDQuaternion.getY(), tempDQuaternion.getZ(), tempDQuaternion.getW()); } if (boneContext.isLockY()) { - q.set(q.getX(), 0, q.getZ(), q.getW()); + tempDQuaternion.set(tempDQuaternion.getX(), 0, tempDQuaternion.getZ(), tempDQuaternion.getW()); } if (boneContext.isLockZ()) { - q.set(q.getX(), q.getY(), 0, q.getW()); + tempDQuaternion.set(tempDQuaternion.getX(), tempDQuaternion.getY(), 0, tempDQuaternion.getW()); } - - boneWorldTransform.getRotation().set(q.multLocal(boneWorldTransform.getRotation())); - constraintHelper.applyTransform(boneContext.getArmatureObjectOMA(), bone.getName(), Space.CONSTRAINT_SPACE_WORLD, boneWorldTransform.toTransform()); - } else { - iterations = 0; - break; } + + DTransform boneTransform = bones.getWorldTransform(boneContext); + boneTransform.getRotation().set(tempDQuaternion.mult(boneTransform.getRotation())); + bones.setWorldTransform(boneContext, boneTransform); } + } - DTransform topBoneTransform = new DTransform(constraintHelper.getTransform(topBone.getArmatureObjectOMA(), topBone.getBone().getName(), Space.CONSTRAINT_SPACE_WORLD)); - Vector3d e = topBoneTransform.getTranslation().addLocal(topBoneTransform.getRotation().mult(Vector3d.UNIT_Y).multLocal(topBone.getLength()));// effector - distanceFromTarget = e.distance(t); + // applying the results + for (int i = bonesCount - 1; i >= 0; --i) { + BoneContext boneContext = bones.get(i); + DTransform transform = bones.getWorldTransform(boneContext); + constraintHelper.applyTransform(boneContext.getArmatureObjectOMA(), boneContext.getBone().getName(), Space.CONSTRAINT_SPACE_WORLD, transform.toTransform()); } + bones = null;// need to reload them again } @Override @@ -153,56 +160,68 @@ public class ConstraintDefinitionIK extends ConstraintDefinition { return "Inverse kinematics"; } + @Override + public boolean isTargetRequired() { + return true; + } + /** - * @return the bone contexts of all bones that will be used in this constraint computations + * Loaded bones' chain. This class allows to operate on transform matrices that use double precision in computations. + * Only the final result is being transformed to single precision numbers. + * + * @author Marcin Roguski (Kaelthas) */ - private List loadBones() { - List bones = new ArrayList(); - Bone bone = (Bone) this.getOwner(); - if (bone == null) { - return bones; - } - if (!useTail) { - bone = bone.getParent(); - } - chainLength = 0; - while (bone != null) { - BoneContext boneContext = blenderContext.getBoneContext(bone); - chainLength += boneContext.getLength(); - bones.add(boneContext); - alteredOmas.add(boneContext.getBoneOma()); - if (bonesAffected != 0 && bones.size() >= bonesAffected) { - break; - } - // need to add spaces between bones to the chain length - Transform boneWorldTransform = constraintHelper.getTransform(boneContext.getArmatureObjectOMA(), boneContext.getBone().getName(), Space.CONSTRAINT_SPACE_WORLD); - Vector3f boneWorldTranslation = boneWorldTransform.getTranslation(); + private static class BonesChain extends ArrayList { + private static final long serialVersionUID = -1850524345643600718L; - bone = bone.getParent(); + private List bonesMatrices = new ArrayList(); + public BonesChain(Bone bone, boolean useTail, int bonesAffected, Collection alteredOmas, BlenderContext blenderContext) { if (bone != null) { - boneContext = blenderContext.getBoneContext(bone); - Transform parentWorldTransform = constraintHelper.getTransform(boneContext.getArmatureObjectOMA(), boneContext.getBone().getName(), Space.CONSTRAINT_SPACE_WORLD); - Vector3f parentWorldTranslation = parentWorldTransform.getTranslation(); - chainLength += boneWorldTranslation.distance(parentWorldTranslation); + ConstraintHelper constraintHelper = blenderContext.getHelper(ConstraintHelper.class); + if (!useTail) { + bone = bone.getParent(); + } + while (bone != null && (bonesAffected <= 0 || this.size() < bonesAffected)) { + BoneContext boneContext = blenderContext.getBoneContext(bone); + this.add(boneContext); + alteredOmas.add(boneContext.getBoneOma()); + + Space space = this.size() < bonesAffected ? Space.CONSTRAINT_SPACE_LOCAL : Space.CONSTRAINT_SPACE_WORLD; + Transform transform = constraintHelper.getTransform(boneContext.getArmatureObjectOMA(), boneContext.getBone().getName(), space); + bonesMatrices.add(new DTransform(transform).toMatrix()); + + bone = bone.getParent(); + } } } - return bones; - } - @Override - public boolean isTrackToBeChanged() { - if (trackToBeChanged) { - // need to check the bone structure too (when constructor was called not all of the bones might have been loaded yet) - // that is why it is also checked here - List bones = this.loadBones(); - trackToBeChanged = bones.size() > 0; + public DTransform getWorldTransform(BoneContext bone) { + int index = this.indexOf(bone); + return this.getWorldMatrix(index).toTransform(); } - return trackToBeChanged; - } - @Override - public boolean isTargetRequired() { - return true; + public void setWorldTransform(BoneContext bone, DTransform transform) { + int index = this.indexOf(bone); + Matrix boneMatrix = transform.toMatrix(); + + if (index < this.size() - 1) { + // computing the current bone local transform + Matrix parentWorldMatrix = this.getWorldMatrix(index + 1); + SimpleMatrix m = parentWorldMatrix.invert().mult(boneMatrix); + boneMatrix = new Matrix(m); + } + bonesMatrices.set(index, boneMatrix); + } + + public Matrix getWorldMatrix(int index) { + if (index == this.size() - 1) { + return new Matrix(bonesMatrices.get(this.size() - 1)); + } + + SimpleMatrix result = this.getWorldMatrix(index + 1); + result = result.mult(bonesMatrices.get(index)); + return new Matrix(result); + } } } diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/curves/BezierCurve.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/curves/BezierCurve.java index 9876702c8..96a91335d 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/curves/BezierCurve.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/curves/BezierCurve.java @@ -1,10 +1,11 @@ package com.jme3.scene.plugins.blender.curves; +import java.util.ArrayList; +import java.util.List; + import com.jme3.math.Vector3f; import com.jme3.scene.plugins.blender.file.DynamicArray; import com.jme3.scene.plugins.blender.file.Structure; -import java.util.ArrayList; -import java.util.List; /** * A class that helps to calculate the bezier curves calues. It uses doubles for performing calculations to minimize @@ -12,21 +13,26 @@ import java.util.List; * @author Marcin Roguski (Kaelthas) */ public class BezierCurve { + private static final int IPO_CONSTANT = 0; + private static final int IPO_LINEAR = 1; + private static final int IPO_BEZIER = 2; - public static final int X_VALUE = 0; - public static final int Y_VALUE = 1; - public static final int Z_VALUE = 2; + public static final int X_VALUE = 0; + public static final int Y_VALUE = 1; + public static final int Z_VALUE = 2; /** * The type of the curve. Describes the data it modifies. * Used in ipos calculations. */ - private int type; + private int type; /** The dimension of the curve. */ - private int dimension; + private int dimension; /** A table of the bezier points. */ - private double[][][] bezierPoints; + private double[][][] bezierPoints; /** Array that stores a radius for each bezier triple. */ - private double[] radiuses; + private double[] radiuses; + /** Interpolation types of the bezier triples. */ + private int[] interpolations; public BezierCurve(final int type, final List bezTriples, final int dimension) { this(type, bezTriples, dimension, false); @@ -44,6 +50,7 @@ public class BezierCurve { // the third index specifies the coordinates of the specific point in a bezier triple bezierPoints = new double[bezTriples.size()][3][dimension]; radiuses = new double[bezTriples.size()]; + interpolations = new int[bezTriples.size()]; int i = 0, j, k; for (Structure bezTriple : bezTriples) { DynamicArray vec = (DynamicArray) bezTriple.getFieldValue("vec"); @@ -57,7 +64,8 @@ public class BezierCurve { bezierPoints[i][j][1] = temp; } } - radiuses[i++] = ((Number) bezTriple.getFieldValue("radius")).floatValue(); + radiuses[i] = ((Number) bezTriple.getFieldValue("radius")).floatValue(); + interpolations[i++] = ((Number) bezTriple.getFieldValue("ipo", IPO_BEZIER)).intValue(); } } @@ -75,10 +83,19 @@ public class BezierCurve { for (int i = 0; i < bezierPoints.length - 1; ++i) { if (frame >= bezierPoints[i][1][0] && frame <= bezierPoints[i + 1][1][0]) { double t = (frame - bezierPoints[i][1][0]) / (bezierPoints[i + 1][1][0] - bezierPoints[i][1][0]); - double oneMinusT = 1.0f - t; - double oneMinusT2 = oneMinusT * oneMinusT; - double t2 = t * t; - return bezierPoints[i][1][valuePart] * oneMinusT2 * oneMinusT + 3.0f * bezierPoints[i][2][valuePart] * t * oneMinusT2 + 3.0f * bezierPoints[i + 1][0][valuePart] * t2 * oneMinusT + bezierPoints[i + 1][1][valuePart] * t2 * t; + switch (interpolations[i]) { + case IPO_BEZIER: + double oneMinusT = 1.0f - t; + double oneMinusT2 = oneMinusT * oneMinusT; + double t2 = t * t; + return bezierPoints[i][1][valuePart] * oneMinusT2 * oneMinusT + 3.0f * bezierPoints[i][2][valuePart] * t * oneMinusT2 + 3.0f * bezierPoints[i + 1][0][valuePart] * t2 * oneMinusT + bezierPoints[i + 1][1][valuePart] * t2 * t; + case IPO_LINEAR: + return (1f - t) * bezierPoints[i][1][valuePart] + t * bezierPoints[i + 1][1][valuePart]; + case IPO_CONSTANT: + return bezierPoints[i][1][valuePart]; + default: + throw new IllegalStateException("Unknown interpolation type for curve: " + interpolations[i]); + } } } if (frame < bezierPoints[0][1][0]) { diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/file/FileBlockHeader.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/file/FileBlockHeader.java index 7bd634254..6a5222a9c 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/file/FileBlockHeader.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/file/FileBlockHeader.java @@ -31,6 +31,9 @@ */ package com.jme3.scene.plugins.blender.file; +import java.util.logging.Level; +import java.util.logging.Logger; + import com.jme3.scene.plugins.blender.BlenderContext; /** @@ -39,39 +42,23 @@ import com.jme3.scene.plugins.blender.BlenderContext; * @author Marcin Roguski */ public class FileBlockHeader { + private static final Logger LOGGER = Logger.getLogger(FileBlockHeader.class.getName()); - public static final int BLOCK_TE00 = 'T' << 24 | 'E' << 16; // TE00 - public static final int BLOCK_ME00 = 'M' << 24 | 'E' << 16; // ME00 - public static final int BLOCK_SR00 = 'S' << 24 | 'R' << 16; // SR00 - public static final int BLOCK_CA00 = 'C' << 24 | 'A' << 16; // CA00 - public static final int BLOCK_LA00 = 'L' << 24 | 'A' << 16; // LA00 - public static final int BLOCK_OB00 = 'O' << 24 | 'B' << 16; // OB00 - public static final int BLOCK_MA00 = 'M' << 24 | 'A' << 16; // MA00 - public static final int BLOCK_SC00 = 'S' << 24 | 'C' << 16; // SC00 - public static final int BLOCK_WO00 = 'W' << 24 | 'O' << 16; // WO00 - public static final int BLOCK_TX00 = 'T' << 24 | 'X' << 16; // TX00 - public static final int BLOCK_IP00 = 'I' << 24 | 'P' << 16; // IP00 - public static final int BLOCK_AC00 = 'A' << 24 | 'C' << 16; // AC00 - public static final int BLOCK_GLOB = 'G' << 24 | 'L' << 16 | 'O' << 8 | 'B'; // GLOB - public static final int BLOCK_REND = 'R' << 24 | 'E' << 16 | 'N' << 8 | 'D'; // REND - public static final int BLOCK_DATA = 'D' << 24 | 'A' << 16 | 'T' << 8 | 'A'; // DATA - public static final int BLOCK_DNA1 = 'D' << 24 | 'N' << 16 | 'A' << 8 | '1'; // DNA1 - public static final int BLOCK_ENDB = 'E' << 24 | 'N' << 16 | 'D' << 8 | 'B'; // ENDB /** Identifier of the file-block [4 bytes]. */ - private int code; + private BlockCode code; /** Total length of the data after the file-block-header [4 bytes]. */ - private int size; + private int size; /** * Memory address the structure was located when written to disk [4 or 8 bytes (defined in file header as a pointer * size)]. */ - private long oldMemoryAddress; + private long oldMemoryAddress; /** Index of the SDNA structure [4 bytes]. */ - private int sdnaIndex; + private int sdnaIndex; /** Number of structure located in this file-block [4 bytes]. */ - private int count; + private int count; /** Start position of the block's data in the stream. */ - private int blockPosition; + private int blockPosition; /** * Constructor. Loads the block header from the given stream during instance creation. @@ -84,13 +71,13 @@ public class FileBlockHeader { */ public FileBlockHeader(BlenderInputStream inputStream, BlenderContext blenderContext) throws BlenderFileException { inputStream.alignPosition(4); - code = inputStream.readByte() << 24 | inputStream.readByte() << 16 | inputStream.readByte() << 8 | inputStream.readByte(); + code = BlockCode.valueOf(inputStream.readByte() << 24 | inputStream.readByte() << 16 | inputStream.readByte() << 8 | inputStream.readByte()); size = inputStream.readInt(); oldMemoryAddress = inputStream.readPointer(); sdnaIndex = inputStream.readInt(); count = inputStream.readInt(); blockPosition = inputStream.getPosition(); - if (FileBlockHeader.BLOCK_DNA1 == code) { + if (BlockCode.BLOCK_DNA1 == code) { blenderContext.setBlockData(new DnaBlockData(inputStream, blenderContext)); } else { inputStream.setPosition(blockPosition + size); @@ -116,7 +103,7 @@ public class FileBlockHeader { * This method returns the code of this data block. * @return the code of this data block */ - public int getCode() { + public BlockCode getCode() { return code; } @@ -157,7 +144,7 @@ public class FileBlockHeader { * @return true if this block is the last one in the file nad false otherwise */ public boolean isLastBlock() { - return FileBlockHeader.BLOCK_ENDB == code; + return BlockCode.BLOCK_ENDB == code; } /** @@ -165,25 +152,62 @@ public class FileBlockHeader { * @return true if this block is the SDNA block and false otherwise */ public boolean isDnaBlock() { - return FileBlockHeader.BLOCK_DNA1 == code; + return BlockCode.BLOCK_DNA1 == code; } @Override public String toString() { - return "FILE BLOCK HEADER [" + this.codeToString(code) + " : " + size + " : " + oldMemoryAddress + " : " + sdnaIndex + " : " + count + "]"; + return "FILE BLOCK HEADER [" + code.toString() + " : " + size + " : " + oldMemoryAddress + " : " + sdnaIndex + " : " + count + "]"; } - /** - * This method transforms the coded bloch id into a string value. - * @param code - * the id of the block - * @return the string value of the block id - */ - protected String codeToString(int code) { - char c1 = (char) ((code & 0xFF000000) >> 24); - char c2 = (char) ((code & 0xFF0000) >> 16); - char c3 = (char) ((code & 0xFF00) >> 8); - char c4 = (char) (code & 0xFF); - return String.valueOf(c1) + c2 + c3 + c4; + public static enum BlockCode { + BLOCK_ME00('M' << 24 | 'E' << 16), // mesh + BLOCK_CA00('C' << 24 | 'A' << 16), // camera + BLOCK_LA00('L' << 24 | 'A' << 16), // lamp + BLOCK_OB00('O' << 24 | 'B' << 16), // object + BLOCK_MA00('M' << 24 | 'A' << 16), // material + BLOCK_SC00('S' << 24 | 'C' << 16), // scene + BLOCK_WO00('W' << 24 | 'O' << 16), // world + BLOCK_TX00('T' << 24 | 'X' << 16), // texture + BLOCK_IP00('I' << 24 | 'P' << 16), // ipo + BLOCK_AC00('A' << 24 | 'C' << 16), // action + BLOCK_IM00('I' << 24 | 'M' << 16), // image + BLOCK_TE00('T' << 24 | 'E' << 16), + BLOCK_WM00('W' << 24 | 'M' << 16), + BLOCK_SR00('S' << 24 | 'R' << 16), + BLOCK_SN00('S' << 24 | 'N' << 16), + BLOCK_BR00('B' << 24 | 'R' << 16), + BLOCK_LS00('L' << 24 | 'S' << 16), + BLOCK_GR00('G' << 24 | 'R' << 16), + BLOCK_AR00('A' << 24 | 'R' << 16), + BLOCK_GLOB('G' << 24 | 'L' << 16 | 'O' << 8 | 'B'), + BLOCK_REND('R' << 24 | 'E' << 16 | 'N' << 8 | 'D'), + BLOCK_DATA('D' << 24 | 'A' << 16 | 'T' << 8 | 'A'), + BLOCK_DNA1('D' << 24 | 'N' << 16 | 'A' << 8 | '1'), + BLOCK_ENDB('E' << 24 | 'N' << 16 | 'D' << 8 | 'B'), + BLOCK_TEST('T' << 24 | 'E' << 16 | 'S' << 8 | 'T'), + BLOCK_UNKN(0); + + private int code; + + private BlockCode(int code) { + this.code = code; + } + + public static BlockCode valueOf(int code) { + for (BlockCode blockCode : BlockCode.values()) { + if (blockCode.code == code) { + return blockCode; + } + } + byte[] codeBytes = new byte[] { (byte) (code >> 24 & 0xFF), (byte) (code >> 16 & 0xFF), (byte) (code >> 8 & 0xFF), (byte) (code & 0xFF) }; + for (int i = 0; i < codeBytes.length; ++i) { + if (codeBytes[i] == 0) { + codeBytes[i] = '0'; + } + } + LOGGER.log(Level.WARNING, "Unknown block header: {0}", new String(codeBytes)); + return BLOCK_UNKN; + } } } diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/file/Structure.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/file/Structure.java index 4f0de7e04..941c7a8fc 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/file/Structure.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/file/Structure.java @@ -254,7 +254,8 @@ public class Structure implements Cloneable { Structure id = (Structure) fieldValue; return id == null ? null : id.getFieldValue("name").toString().substring(2);// blender adds 2-charactes as a name prefix } - return null; + Object name = this.getFieldValue("name", null); + return name == null ? null : name.toString().substring(2); } @Override diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/landscape/LandscapeHelper.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/landscape/LandscapeHelper.java index c05eed775..8466d5cce 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/landscape/LandscapeHelper.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/landscape/LandscapeHelper.java @@ -208,6 +208,6 @@ public class LandscapeHelper extends AbstractBlenderHelper { } LOGGER.fine("Sky texture created. Creating sky."); - return SkyFactory.createSky(blenderContext.getAssetManager(), texture, false); + return SkyFactory.createSky(blenderContext.getAssetManager(), texture, SkyFactory.EnvMapType.CubeMap); } } diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/lights/LightHelper.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/lights/LightHelper.java index 17e38c92b..3ae866b7c 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/lights/LightHelper.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/lights/LightHelper.java @@ -40,7 +40,6 @@ import com.jme3.light.PointLight; import com.jme3.light.SpotLight; import com.jme3.math.ColorRGBA; import com.jme3.math.FastMath; -import com.jme3.scene.LightNode; import com.jme3.scene.plugins.blender.AbstractBlenderHelper; import com.jme3.scene.plugins.blender.BlenderContext; import com.jme3.scene.plugins.blender.BlenderContext.LoadedDataType; @@ -67,8 +66,8 @@ public class LightHelper extends AbstractBlenderHelper { super(blenderVersion, blenderContext); } - public LightNode toLight(Structure structure, BlenderContext blenderContext) throws BlenderFileException { - LightNode result = (LightNode) blenderContext.getLoadedFeature(structure.getOldMemoryAddress(), LoadedDataType.FEATURE); + public Light toLight(Structure structure, BlenderContext blenderContext) throws BlenderFileException { + Light result = (Light) blenderContext.getLoadedFeature(structure.getOldMemoryAddress(), LoadedDataType.FEATURE); if (result != null) { return result; } @@ -111,6 +110,7 @@ public class LightHelper extends AbstractBlenderHelper { float g = ((Number) structure.getFieldValue("g")).floatValue(); float b = ((Number) structure.getFieldValue("b")).floatValue(); light.setColor(new ColorRGBA(r, g, b, 1.0f)); - return new LightNode(structure.getName(), light); + light.setName(structure.getName()); + return light; } } diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/materials/MaterialContext.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/materials/MaterialContext.java index 6e67da967..51c7072b1 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/materials/MaterialContext.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/materials/MaterialContext.java @@ -1,11 +1,15 @@ package com.jme3.scene.plugins.blender.materials; +import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; +import com.jme3.export.JmeExporter; +import com.jme3.export.JmeImporter; +import com.jme3.export.Savable; import com.jme3.material.Material; import com.jme3.material.RenderState.BlendMode; import com.jme3.material.RenderState.FaceCullMode; @@ -30,7 +34,7 @@ import com.jme3.util.BufferUtils; * This class holds the data about the material. * @author Marcin Roguski (Kaelthas) */ -public final class MaterialContext { +public final class MaterialContext implements Savable { private static final Logger LOGGER = Logger.getLogger(MaterialContext.class.getName()); // texture mapping types @@ -67,7 +71,7 @@ public final class MaterialContext { int diff_shader = ((Number) structure.getFieldValue("diff_shader")).intValue(); diffuseShader = DiffuseShader.values()[diff_shader]; ambientFactor = ((Number) structure.getFieldValue("amb")).floatValue(); - + if (shadeless) { float r = ((Number) structure.getFieldValue("r")).floatValue(); float g = ((Number) structure.getFieldValue("g")).floatValue(); @@ -107,6 +111,13 @@ public final class MaterialContext { this.transparent = transparent; } + /** + * @return the name of the material + */ + public String getName() { + return name; + } + /** * Applies material to a given geometry. * @@ -314,4 +325,14 @@ public final class MaterialContext { float alpha = ((Number) materialStructure.getFieldValue("alpha")).floatValue(); return new ColorRGBA(r, g, b, alpha); } + + @Override + public void write(JmeExporter e) throws IOException { + throw new IOException("Material context is not for saving! It implements savable only to be passed to another blend file as a Savable in user data!"); + } + + @Override + public void read(JmeImporter e) throws IOException { + throw new IOException("Material context is not for loading! It implements savable only to be passed to another blend file as a Savable in user data!"); + } } diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/materials/MaterialHelper.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/materials/MaterialHelper.java index 5fcccc389..885c5850e 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/materials/MaterialHelper.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/materials/MaterialHelper.java @@ -51,6 +51,7 @@ import com.jme3.scene.plugins.blender.file.Structure; import com.jme3.shader.VarType; import com.jme3.texture.Image; import com.jme3.texture.Image.Format; +import com.jme3.texture.image.ColorSpace; import com.jme3.texture.Texture; import com.jme3.util.BufferUtils; @@ -161,12 +162,17 @@ public class MaterialHelper extends AbstractBlenderHelper { * an exception is throw when problems with blend file occur */ public MaterialContext toMaterialContext(Structure structure, BlenderContext blenderContext) throws BlenderFileException { - LOGGER.log(Level.FINE, "Loading material."); MaterialContext result = (MaterialContext) blenderContext.getLoadedFeature(structure.getOldMemoryAddress(), LoadedDataType.FEATURE); if (result != null) { return result; } + if ("ID".equals(structure.getType())) { + LOGGER.fine("Loading material from external blend file."); + return (MaterialContext) this.loadLibrary(structure); + } + + LOGGER.fine("Loading material."); result = new MaterialContext(structure, blenderContext); LOGGER.log(Level.FINE, "Material''s name: {0}", result.name); Long oma = structure.getOldMemoryAddress(); @@ -212,7 +218,7 @@ public class MaterialHelper extends AbstractBlenderHelper { } } - image = new Image(Format.RGBA8, w, h, bb); + image = new Image(Format.RGBA8, w, h, bb, ColorSpace.Linear); texture.setImage(image); result.setTextureParam("Texture", VarType.Texture2D, texture); diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/math/DQuaternion.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/math/DQuaternion.java index 359abf057..9739ccd4b 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/math/DQuaternion.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/math/DQuaternion.java @@ -164,6 +164,134 @@ public final class DQuaternion implements Savable, Cloneable, java.io.Serializab w = 1; } + /** + * norm returns the norm of this quaternion. This is the dot + * product of this quaternion with itself. + * + * @return the norm of the quaternion. + */ + public double norm() { + return w * w + x * x + y * y + z * z; + } + + public DQuaternion fromRotationMatrix(double m00, double m01, double m02, + double m10, double m11, double m12, double m20, double m21, double m22) { + // first normalize the forward (F), up (U) and side (S) vectors of the rotation matrix + // so that the scale does not affect the rotation + double lengthSquared = m00 * m00 + m10 * m10 + m20 * m20; + if (lengthSquared != 1f && lengthSquared != 0f) { + lengthSquared = 1.0 / Math.sqrt(lengthSquared); + m00 *= lengthSquared; + m10 *= lengthSquared; + m20 *= lengthSquared; + } + lengthSquared = m01 * m01 + m11 * m11 + m21 * m21; + if (lengthSquared != 1 && lengthSquared != 0f) { + lengthSquared = 1.0 / Math.sqrt(lengthSquared); + m01 *= lengthSquared; + m11 *= lengthSquared; + m21 *= lengthSquared; + } + lengthSquared = m02 * m02 + m12 * m12 + m22 * m22; + if (lengthSquared != 1f && lengthSquared != 0f) { + lengthSquared = 1.0 / Math.sqrt(lengthSquared); + m02 *= lengthSquared; + m12 *= lengthSquared; + m22 *= lengthSquared; + } + + // Use the Graphics Gems code, from + // ftp://ftp.cis.upenn.edu/pub/graphics/shoemake/quatut.ps.Z + // *NOT* the "Matrix and Quaternions FAQ", which has errors! + + // the trace is the sum of the diagonal elements; see + // http://mathworld.wolfram.com/MatrixTrace.html + double t = m00 + m11 + m22; + + // we protect the division by s by ensuring that s>=1 + if (t >= 0) { // |w| >= .5 + double s = Math.sqrt(t + 1); // |s|>=1 ... + w = 0.5f * s; + s = 0.5f / s; // so this division isn't bad + x = (m21 - m12) * s; + y = (m02 - m20) * s; + z = (m10 - m01) * s; + } else if (m00 > m11 && m00 > m22) { + double s = Math.sqrt(1.0 + m00 - m11 - m22); // |s|>=1 + x = s * 0.5f; // |x| >= .5 + s = 0.5f / s; + y = (m10 + m01) * s; + z = (m02 + m20) * s; + w = (m21 - m12) * s; + } else if (m11 > m22) { + double s = Math.sqrt(1.0 + m11 - m00 - m22); // |s|>=1 + y = s * 0.5f; // |y| >= .5 + s = 0.5f / s; + x = (m10 + m01) * s; + z = (m21 + m12) * s; + w = (m02 - m20) * s; + } else { + double s = Math.sqrt(1.0 + m22 - m00 - m11); // |s|>=1 + z = s * 0.5f; // |z| >= .5 + s = 0.5f / s; + x = (m02 + m20) * s; + y = (m21 + m12) * s; + w = (m10 - m01) * s; + } + + return this; + } + + /** + * toRotationMatrix converts this quaternion to a rotational + * matrix. The result is stored in result. 4th row and 4th column values are + * untouched. Note: the result is created from a normalized version of this quat. + * + * @param result + * The Matrix4f to store the result in. + * @return the rotation matrix representation of this quaternion. + */ + public Matrix toRotationMatrix(Matrix result) { + Vector3d originalScale = new Vector3d(); + + result.toScaleVector(originalScale); + result.setScale(1, 1, 1); + double norm = this.norm(); + // we explicitly test norm against one here, saving a division + // at the cost of a test and branch. Is it worth it? + double s = norm == 1f ? 2f : norm > 0f ? 2f / norm : 0; + + // compute xs/ys/zs first to save 6 multiplications, since xs/ys/zs + // will be used 2-4 times each. + double xs = x * s; + double ys = y * s; + double zs = z * s; + double xx = x * xs; + double xy = x * ys; + double xz = x * zs; + double xw = w * xs; + double yy = y * ys; + double yz = y * zs; + double yw = w * ys; + double zz = z * zs; + double zw = w * zs; + + // using s=2/norm (instead of 1/norm) saves 9 multiplications by 2 here + result.set(0, 0, 1 - (yy + zz)); + result.set(0, 1, xy - zw); + result.set(0, 2, xz + yw); + result.set(1, 0, xy + zw); + result.set(1, 1, 1 - (xx + zz)); + result.set(1, 2, yz - xw); + result.set(2, 0, xz - yw); + result.set(2, 1, yz + xw); + result.set(2, 2, 1 - (xx + yy)); + + result.setScale(originalScale); + + return result; + } + /** * fromAngleAxis sets this quaternion to the values specified * by an angle and an axis of rotation. This method creates an object, so diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/math/DTransform.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/math/DTransform.java index ed31a4c98..28fcda0c7 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/math/DTransform.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/math/DTransform.java @@ -31,11 +31,15 @@ */ package com.jme3.scene.plugins.blender.math; -import com.jme3.export.*; -import com.jme3.math.Transform; - import java.io.IOException; +import com.jme3.export.InputCapsule; +import com.jme3.export.JmeExporter; +import com.jme3.export.JmeImporter; +import com.jme3.export.OutputCapsule; +import com.jme3.export.Savable; +import com.jme3.math.Transform; + /** * Started Date: Jul 16, 2004
*
@@ -57,6 +61,12 @@ public final class DTransform implements Savable, Cloneable, java.io.Serializabl private Vector3d translation; private Vector3d scale; + public DTransform() { + translation = new Vector3d(); + rotation = new DQuaternion(); + scale = new Vector3d(); + } + public DTransform(Transform transform) { translation = new Vector3d(transform.getTranslation()); rotation = new DQuaternion(transform.getRotation()); @@ -66,7 +76,15 @@ public final class DTransform implements Savable, Cloneable, java.io.Serializabl public Transform toTransform() { return new Transform(translation.toVector3f(), rotation.toQuaternion(), scale.toVector3f()); } - + + public Matrix toMatrix() { + Matrix m = Matrix.identity(4); + m.setTranslation(translation); + m.setRotationQuaternion(rotation); + m.setScale(scale); + return m; + } + /** * Sets this translation to the given value. * @param trans diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/math/Matrix.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/math/Matrix.java new file mode 100644 index 000000000..29550f23b --- /dev/null +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/math/Matrix.java @@ -0,0 +1,214 @@ +package com.jme3.scene.plugins.blender.math; + +import java.text.DecimalFormat; + +import org.ejml.ops.CommonOps; +import org.ejml.simple.SimpleMatrix; +import org.ejml.simple.SimpleSVD; + +import com.jme3.math.FastMath; + +/** + * Encapsulates a 4x4 matrix + * + * + */ +public class Matrix extends SimpleMatrix { + private static final long serialVersionUID = 2396600537315902559L; + + public Matrix(int rows, int cols) { + super(rows, cols); + } + + /** + * Copy constructor + */ + public Matrix(SimpleMatrix m) { + super(m); + } + + public Matrix(double[][] data) { + super(data); + } + + public static Matrix identity(int size) { + Matrix result = new Matrix(size, size); + CommonOps.setIdentity(result.mat); + return result; + } + + public Matrix pseudoinverse() { + return this.pseudoinverse(1); + } + + @SuppressWarnings("unchecked") + public Matrix pseudoinverse(double lambda) { + SimpleSVD simpleSVD = this.svd(); + + SimpleMatrix U = simpleSVD.getU(); + SimpleMatrix S = simpleSVD.getW(); + SimpleMatrix V = simpleSVD.getV(); + + int N = Math.min(this.numRows(),this.numCols()); + double maxSingular = 0; + for( int i = 0; i < N; ++i ) { + if( S.get(i, i) > maxSingular ) { + maxSingular = S.get(i, i); + } + } + + double tolerance = FastMath.DBL_EPSILON * Math.max(this.numRows(),this.numCols()) * maxSingular; + for(int i=0;isetRotationQuaternion builds a rotation from a + * Quaternion. + * + * @param quat + * the quaternion to build the rotation from. + * @throws NullPointerException + * if quat is null. + */ + public void setRotationQuaternion(DQuaternion quat) { + quat.toRotationMatrix(this); + } + + public DTransform toTransform() { + DTransform result = new DTransform(); + result.setTranslation(this.toTranslationVector()); + result.setRotation(this.toRotationQuat()); + result.setScale(this.toScaleVector()); + return result; + } + + public Vector3d toTranslationVector() { + return new Vector3d(this.get(0, 3), this.get(1, 3), this.get(2, 3)); + } + + public DQuaternion toRotationQuat() { + DQuaternion quat = new DQuaternion(); + quat.fromRotationMatrix(this.get(0, 0), this.get(0, 1), this.get(0, 2), this.get(1, 0), this.get(1, 1), this.get(1, 2), this.get(2, 0), this.get(2, 1), this.get(2, 2)); + return quat; + } + + /** + * Retreives the scale vector from the matrix and stores it into a given + * vector. + * + * @param the + * vector where the scale will be stored + */ + public Vector3d toScaleVector() { + Vector3d result = new Vector3d(); + this.toScaleVector(result); + return result; + } + + /** + * Retreives the scale vector from the matrix and stores it into a given + * vector. + * + * @param the + * vector where the scale will be stored + */ + public void toScaleVector(Vector3d vector) { + double scaleX = Math.sqrt(this.get(0, 0) * this.get(0, 0) + this.get(1, 0) * this.get(1, 0) + this.get(2, 0) * this.get(2, 0)); + double scaleY = Math.sqrt(this.get(0, 1) * this.get(0, 1) + this.get(1, 1) * this.get(1, 1) + this.get(2, 1) * this.get(2, 1)); + double scaleZ = Math.sqrt(this.get(0, 2) * this.get(0, 2) + this.get(1, 2) * this.get(1, 2) + this.get(2, 2) * this.get(2, 2)); + vector.set(scaleX, scaleY, scaleZ); + } +} diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/meshes/MeshHelper.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/meshes/MeshHelper.java index 92b236f4c..5284b964a 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/meshes/MeshHelper.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/meshes/MeshHelper.java @@ -40,7 +40,6 @@ import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; -import com.jme3.asset.BlenderKey.FeaturesToLoad; import com.jme3.material.Material; import com.jme3.math.ColorRGBA; import com.jme3.math.Vector2f; @@ -52,7 +51,6 @@ import com.jme3.scene.plugins.blender.file.BlenderFileException; import com.jme3.scene.plugins.blender.file.DynamicArray; import com.jme3.scene.plugins.blender.file.Pointer; import com.jme3.scene.plugins.blender.file.Structure; -import com.jme3.scene.plugins.blender.materials.MaterialContext; import com.jme3.scene.plugins.blender.materials.MaterialHelper; import com.jme3.scene.plugins.blender.objects.Properties; @@ -106,17 +104,18 @@ public class MeshHelper extends AbstractBlenderHelper { return temporalMesh.clone(); } + if ("ID".equals(meshStructure.getType())) { + LOGGER.fine("Loading mesh from external blend file."); + return (TemporalMesh) this.loadLibrary(meshStructure); + } + String name = meshStructure.getName(); LOGGER.log(Level.FINE, "Reading mesh: {0}.", name); temporalMesh = new TemporalMesh(meshStructure, blenderContext); LOGGER.fine("Loading materials."); MaterialHelper materialHelper = blenderContext.getHelper(MaterialHelper.class); - MaterialContext[] materials = null; - if ((blenderContext.getBlenderKey().getFeaturesToLoad() & FeaturesToLoad.MATERIALS) != 0) { - materials = materialHelper.getMaterials(meshStructure, blenderContext); - } - temporalMesh.setMaterials(materials); + temporalMesh.setMaterials(materialHelper.getMaterials(meshStructure, blenderContext)); LOGGER.fine("Reading custom properties."); Properties properties = this.loadProperties(meshStructure, blenderContext); diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/objects/ObjectHelper.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/objects/ObjectHelper.java index 8e2dc2652..17c0d421e 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/objects/ObjectHelper.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/objects/ObjectHelper.java @@ -40,12 +40,15 @@ import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; -import com.jme3.asset.BlenderKey.FeaturesToLoad; +import com.jme3.light.Light; import com.jme3.math.FastMath; import com.jme3.math.Matrix4f; import com.jme3.math.Transform; import com.jme3.math.Vector3f; +import com.jme3.renderer.Camera; +import com.jme3.scene.CameraNode; import com.jme3.scene.Geometry; +import com.jme3.scene.LightNode; import com.jme3.scene.Mesh.Mode; import com.jme3.scene.Node; import com.jme3.scene.Spatial; @@ -106,39 +109,34 @@ public class ObjectHelper extends AbstractBlenderHelper { * an exception is thrown when the given data is inapropriate */ public Object toObject(Structure objectStructure, BlenderContext blenderContext) throws BlenderFileException { - LOGGER.fine("Loading blender object."); + Object loadedResult = blenderContext.getLoadedFeature(objectStructure.getOldMemoryAddress(), LoadedDataType.FEATURE); + if (loadedResult != null) { + return loadedResult; + } + LOGGER.fine("Loading blender object."); + if ("ID".equals(objectStructure.getType())) { + Node object = (Node) this.loadLibrary(objectStructure); + if (object.getParent() != null) { + LOGGER.log(Level.FINEST, "Detaching object {0}, loaded from external file, from its parent.", object); + object.getParent().detachChild(object); + } + return object; + } int type = ((Number) objectStructure.getFieldValue("type")).intValue(); ObjectType objectType = ObjectType.valueOf(type); LOGGER.log(Level.FINE, "Type of the object: {0}.", objectType); - if (objectType == ObjectType.LAMP && !blenderContext.getBlenderKey().shouldLoad(FeaturesToLoad.LIGHTS)) { - LOGGER.fine("Lamps are not included in loading."); - return null; - } - if (objectType == ObjectType.CAMERA && !blenderContext.getBlenderKey().shouldLoad(FeaturesToLoad.CAMERAS)) { - LOGGER.fine("Cameras are not included in loading."); - return null; - } - if (!blenderContext.getBlenderKey().shouldLoad(FeaturesToLoad.OBJECTS)) { - LOGGER.fine("Objects are not included in loading."); - return null; - } + int lay = ((Number) objectStructure.getFieldValue("lay")).intValue(); if ((lay & blenderContext.getBlenderKey().getLayersToLoad()) == 0) { LOGGER.fine("The layer this object is located in is not included in loading."); return null; } - LOGGER.fine("Checking if the object has not been already loaded."); - Object loadedResult = blenderContext.getLoadedFeature(objectStructure.getOldMemoryAddress(), LoadedDataType.FEATURE); - if (loadedResult != null) { - return loadedResult; - } - blenderContext.pushParent(objectStructure); String name = objectStructure.getName(); LOGGER.log(Level.FINE, "Loading obejct: {0}", name); - + int restrictflag = ((Number) objectStructure.getFieldValue("restrictflag")).intValue(); boolean visible = (restrictflag & 0x01) != 0; @@ -171,7 +169,7 @@ public class ObjectHelper extends AbstractBlenderHelper { Pointer pMesh = (Pointer) objectStructure.getFieldValue("data"); List meshesArray = pMesh.fetchData(); TemporalMesh temporalMesh = meshHelper.toTemporalMesh(meshesArray.get(0), blenderContext); - if(temporalMesh != null) { + if (temporalMesh != null) { result.attachChild(temporalMesh); } break; @@ -183,7 +181,7 @@ public class ObjectHelper extends AbstractBlenderHelper { CurvesHelper curvesHelper = blenderContext.getHelper(CurvesHelper.class); Structure curveData = pCurve.fetchData().get(0); TemporalMesh curvesTemporalMesh = curvesHelper.toCurve(curveData, blenderContext); - if(curvesTemporalMesh != null) { + if (curvesTemporalMesh != null) { result.attachChild(curvesTemporalMesh); } } @@ -193,10 +191,12 @@ public class ObjectHelper extends AbstractBlenderHelper { if (pLamp.isNotNull()) { LightHelper lightHelper = blenderContext.getHelper(LightHelper.class); List lampsArray = pLamp.fetchData(); - result = lightHelper.toLight(lampsArray.get(0), blenderContext); - if (result == null) { + Light light = lightHelper.toLight(lampsArray.get(0), blenderContext); + if (light == null) { // probably some light type is not supported, just create a node so that we can maintain child-parent relationship for nodes result = new Node(name); + } else { + result = new LightNode(name, light); } } break; @@ -205,19 +205,25 @@ public class ObjectHelper extends AbstractBlenderHelper { if (pCamera.isNotNull()) { CameraHelper cameraHelper = blenderContext.getHelper(CameraHelper.class); List camerasArray = pCamera.fetchData(); - result = cameraHelper.toCamera(camerasArray.get(0), blenderContext); + Camera camera = cameraHelper.toCamera(camerasArray.get(0), blenderContext); + if (camera == null) { + // just create a node so that we can maintain child-parent relationship for nodes + result = new Node(name); + } else { + result = new CameraNode(name, camera); + } } break; default: LOGGER.log(Level.WARNING, "Unsupported object type: {0}", type); } - + if (result != null) { LOGGER.fine("Storing loaded feature in blender context and applying markers (those will be removed before the final result is released)."); Long oma = objectStructure.getOldMemoryAddress(); blenderContext.addLoadedFeatures(oma, LoadedDataType.STRUCTURE, objectStructure); blenderContext.addLoadedFeatures(oma, LoadedDataType.FEATURE, result); - + blenderContext.addMarker(OMA_MARKER, result, objectStructure.getOldMemoryAddress()); if (objectType == ObjectType.ARMATURE) { blenderContext.addMarker(ARMATURE_NODE_MARKER, result, Boolean.TRUE); @@ -235,13 +241,13 @@ public class ObjectHelper extends AbstractBlenderHelper { for (Modifier modifier : modifiers) { modifier.apply(result, blenderContext); } - + if (result.getChildren() != null && result.getChildren().size() > 0) { - if(result.getChildren().size() == 1 && result.getChild(0) instanceof TemporalMesh) { + if (result.getChildren().size() == 1 && result.getChild(0) instanceof TemporalMesh) { LOGGER.fine("Converting temporal mesh into jme geometries."); - ((TemporalMesh)result.getChild(0)).toGeometries(); + ((TemporalMesh) result.getChild(0)).toGeometries(); } - + LOGGER.fine("Applying proper scale to the geometries."); for (Spatial child : result.getChildren()) { if (child instanceof Geometry) { diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/CombinedTexture.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/CombinedTexture.java index 5bfc9eb78..b7d6958ca 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/CombinedTexture.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/CombinedTexture.java @@ -444,13 +444,17 @@ public class CombinedTexture { case RGB8: return true;// these types have no alpha by definition case ABGR8: + case DXT1A: case DXT3: case DXT5: case Luminance16FAlpha16F: case Luminance8Alpha8: case RGBA16F: case RGBA32F: - case RGBA8:// with these types it is better to make sure if the texture is or is not transparent + case RGBA8: + case ARGB8: + case BGRA8: + case RGB5A1:// with these types it is better to make sure if the texture is or is not transparent PixelInputOutput pixelInputOutput = PixelIOFactory.getPixelIO(image.getFormat()); TexturePixel pixel = new TexturePixel(); int depth = image.getDepth() == 0 ? 1 : image.getDepth(); @@ -465,6 +469,8 @@ public class CombinedTexture { } } return true; + default: + throw new IllegalStateException("Unknown image format: " + image.getFormat()); } } } diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/ImageUtils.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/ImageUtils.java index 66740769d..99ea9b5d2 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/ImageUtils.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/ImageUtils.java @@ -41,13 +41,13 @@ public final class ImageUtils { public static Image createEmptyImage(Format format, int width, int height, int depth) { int bufferSize = width * height * (format.getBitsPerPixel() >> 3); if (depth < 2) { - return new Image(format, width, height, BufferUtils.createByteBuffer(bufferSize)); + return new Image(format, width, height, BufferUtils.createByteBuffer(bufferSize), com.jme3.texture.image.ColorSpace.Linear); } ArrayList data = new ArrayList(depth); for (int i = 0; i < depth; ++i) { data.add(BufferUtils.createByteBuffer(bufferSize)); } - return new Image(Format.RGB8, width, height, depth, data); + return new Image(Format.RGB8, width, height, depth, data, com.jme3.texture.image.ColorSpace.Linear); } /** @@ -337,7 +337,7 @@ public final class ImageUtils { alphas[0] = data.get() * 255.0f; alphas[1] = data.get() * 255.0f; //the casts to long must be done here because otherwise 32-bit integers would be shifetd by 32 and 40 bits which would result in improper values - long alphaIndices = (long)data.get() | (long)data.get() << 8 | (long)data.get() << 16 | (long)data.get() << 24 | (long)data.get() << 32 | (long)data.get() << 40; + long alphaIndices = data.get() | (long)data.get() << 8 | (long)data.get() << 16 | (long)data.get() << 24 | (long)data.get() << 32 | (long)data.get() << 40; if (alphas[0] > alphas[1]) {// 6 interpolated alpha values. alphas[2] = (6 * alphas[0] + alphas[1]) / 7; alphas[3] = (5 * alphas[0] + 2 * alphas[1]) / 7; @@ -404,7 +404,8 @@ public final class ImageUtils { dataArray.add(BufferUtils.createByteBuffer(bytes)); } - Image result = depth > 1 ? new Image(Format.RGBA8, image.getWidth(), image.getHeight(), depth, dataArray) : new Image(Format.RGBA8, image.getWidth(), image.getHeight(), dataArray.get(0)); + Image result = depth > 1 ? new Image(Format.RGBA8, image.getWidth(), image.getHeight(), depth, dataArray, com.jme3.texture.image.ColorSpace.Linear) : + new Image(Format.RGBA8, image.getWidth(), image.getHeight(), dataArray.get(0), com.jme3.texture.image.ColorSpace.Linear); if (newMipmapSizes != null) { result.setMipMapSizes(newMipmapSizes); } @@ -467,6 +468,6 @@ public final class ImageUtils { private static Image toJmeImage(BufferedImage bufferedImage, Format format) { ByteBuffer byteBuffer = BufferUtils.createByteBuffer(bufferedImage.getWidth() * bufferedImage.getHeight() * 3); ImageToAwt.convert(bufferedImage, format, byteBuffer); - return new Image(format, bufferedImage.getWidth(), bufferedImage.getHeight(), byteBuffer); + return new Image(format, bufferedImage.getWidth(), bufferedImage.getHeight(), byteBuffer, com.jme3.texture.image.ColorSpace.Linear); } } diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/TextureHelper.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/TextureHelper.java index ad35a2ebc..f1c1c64fc 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/TextureHelper.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/TextureHelper.java @@ -121,7 +121,7 @@ public class TextureHelper extends AbstractBlenderHelper { * data. The returned texture has the name set to the value of its blender * type. * - * @param tex + * @param textureStructure * texture structure filled with data * @param blenderContext * the blender context @@ -130,23 +130,29 @@ public class TextureHelper extends AbstractBlenderHelper { * this exception is thrown when the blend file structure is * somehow invalid or corrupted */ - public Texture getTexture(Structure tex, Structure mTex, BlenderContext blenderContext) throws BlenderFileException { - Texture result = (Texture) blenderContext.getLoadedFeature(tex.getOldMemoryAddress(), LoadedDataType.FEATURE); + public Texture getTexture(Structure textureStructure, Structure mTex, BlenderContext blenderContext) throws BlenderFileException { + Texture result = (Texture) blenderContext.getLoadedFeature(textureStructure.getOldMemoryAddress(), LoadedDataType.FEATURE); if (result != null) { return result; } - int type = ((Number) tex.getFieldValue("type")).intValue(); - int imaflag = ((Number) tex.getFieldValue("imaflag")).intValue(); + + if ("ID".equals(textureStructure.getType())) { + LOGGER.fine("Loading texture from external blend file."); + return (Texture) this.loadLibrary(textureStructure); + } + + int type = ((Number) textureStructure.getFieldValue("type")).intValue(); + int imaflag = ((Number) textureStructure.getFieldValue("imaflag")).intValue(); switch (type) { case TEX_IMAGE:// (it is first because probably this will be most commonly used) - Pointer pImage = (Pointer) tex.getFieldValue("ima"); + Pointer pImage = (Pointer) textureStructure.getFieldValue("ima"); if (pImage.isNotNull()) { Structure image = pImage.fetchData().get(0); - Texture loadedTexture = this.loadTexture(image, imaflag, blenderContext); + Texture loadedTexture = this.loadImageAsTexture(image, imaflag, blenderContext); if (loadedTexture != null) { result = loadedTexture; - this.applyColorbandAndColorFactors(tex, result.getImage(), blenderContext); + this.applyColorbandAndColorFactors(textureStructure, result.getImage(), blenderContext); } } break; @@ -160,7 +166,7 @@ public class TextureHelper extends AbstractBlenderHelper { case TEX_MUSGRAVE: case TEX_VORONOI: case TEX_DISTNOISE: - result = new GeneratedTexture(tex, mTex, textureGeneratorFactory.createTextureGenerator(type), blenderContext); + result = new GeneratedTexture(textureStructure, mTex, textureGeneratorFactory.createTextureGenerator(type), blenderContext); break; case TEX_NONE:// No texture, do nothing break; @@ -169,13 +175,13 @@ public class TextureHelper extends AbstractBlenderHelper { case TEX_PLUGIN: case TEX_ENVMAP: case TEX_OCEAN: - LOGGER.log(Level.WARNING, "Unsupported texture type: {0} for texture: {1}", new Object[] { type, tex.getName() }); + LOGGER.log(Level.WARNING, "Unsupported texture type: {0} for texture: {1}", new Object[] { type, textureStructure.getName() }); break; default: - throw new BlenderFileException("Unknown texture type: " + type + " for texture: " + tex.getName()); + throw new BlenderFileException("Unknown texture type: " + type + " for texture: " + textureStructure.getName()); } if (result != null) { - result.setName(tex.getName()); + result.setName(textureStructure.getName()); result.setWrap(WrapMode.Repeat); // decide if the mipmaps will be generated @@ -195,14 +201,14 @@ public class TextureHelper extends AbstractBlenderHelper { } if (type != TEX_IMAGE) {// only generated textures should have this key - result.setKey(new GeneratedTextureKey(tex.getName())); + result.setKey(new GeneratedTextureKey(textureStructure.getName())); } if (LOGGER.isLoggable(Level.FINE)) { - LOGGER.log(Level.FINE, "Adding texture {0} to the loaded features with OMA = {1}", new Object[] { result.getName(), tex.getOldMemoryAddress() }); + LOGGER.log(Level.FINE, "Adding texture {0} to the loaded features with OMA = {1}", new Object[] { result.getName(), textureStructure.getOldMemoryAddress() }); } - blenderContext.addLoadedFeatures(tex.getOldMemoryAddress(), LoadedDataType.STRUCTURE, tex); - blenderContext.addLoadedFeatures(tex.getOldMemoryAddress(), LoadedDataType.FEATURE, result); + blenderContext.addLoadedFeatures(textureStructure.getOldMemoryAddress(), LoadedDataType.STRUCTURE, textureStructure); + blenderContext.addLoadedFeatures(textureStructure.getOldMemoryAddress(), LoadedDataType.FEATURE, result); } return result; } @@ -222,29 +228,39 @@ public class TextureHelper extends AbstractBlenderHelper { * this exception is thrown when the blend file structure is * somehow invalid or corrupted */ - protected Texture loadTexture(Structure imageStructure, int imaflag, BlenderContext blenderContext) throws BlenderFileException { + public Texture loadImageAsTexture(Structure imageStructure, int imaflag, BlenderContext blenderContext) throws BlenderFileException { LOGGER.log(Level.FINE, "Fetching texture with OMA = {0}", imageStructure.getOldMemoryAddress()); Texture result = null; Image im = (Image) blenderContext.getLoadedFeature(imageStructure.getOldMemoryAddress(), LoadedDataType.FEATURE); - if (im == null) { - String texturePath = imageStructure.getFieldValue("name").toString(); - Pointer pPackedFile = (Pointer) imageStructure.getFieldValue("packedfile"); - if (pPackedFile.isNull()) { - LOGGER.log(Level.FINE, "Reading texture from file: {0}", texturePath); - result = this.loadImageFromFile(texturePath, imaflag, blenderContext); + // if (im == null) { HACK force reaload always, as constructor in else case is destroying the TextureKeys! + if ("ID".equals(imageStructure.getType())) { + LOGGER.fine("Loading texture from external blend file."); + result = (Texture) this.loadLibrary(imageStructure); } else { - LOGGER.fine("Packed texture. Reading directly from the blend file!"); - Structure packedFile = pPackedFile.fetchData().get(0); - Pointer pData = (Pointer) packedFile.getFieldValue("data"); - FileBlockHeader dataFileBlock = blenderContext.getFileBlock(pData.getOldMemoryAddress()); - blenderContext.getInputStream().setPosition(dataFileBlock.getBlockPosition()); - ImageLoader imageLoader = new ImageLoader(); - - // Should the texture be flipped? It works for sinbad .. - result = new Texture2D(imageLoader.loadImage(blenderContext.getInputStream(), dataFileBlock.getBlockPosition(), true)); + String texturePath = imageStructure.getFieldValue("name").toString(); + Pointer pPackedFile = (Pointer) imageStructure.getFieldValue("packedfile"); + if (pPackedFile.isNull()) { + LOGGER.log(Level.FINE, "Reading texture from file: {0}", texturePath); + result = this.loadImageFromFile(texturePath, imaflag, blenderContext); + } else { + LOGGER.fine("Packed texture. Reading directly from the blend file!"); + Structure packedFile = pPackedFile.fetchData().get(0); + Pointer pData = (Pointer) packedFile.getFieldValue("data"); + FileBlockHeader dataFileBlock = blenderContext.getFileBlock(pData.getOldMemoryAddress()); + blenderContext.getInputStream().setPosition(dataFileBlock.getBlockPosition()); + + // Should the texture be flipped? It works for sinbad .. + result = new Texture2D(new ImageLoader().loadImage(blenderContext.getInputStream(), dataFileBlock.getBlockPosition(), true)); + } } - } else { - result = new Texture2D(im); + //} else { + // result = new Texture2D(im); + // } + + if (result != null) {// render result is not being loaded + blenderContext.addLoadedFeatures(imageStructure.getOldMemoryAddress(), LoadedDataType.STRUCTURE, imageStructure); + blenderContext.addLoadedFeatures(imageStructure.getOldMemoryAddress(), LoadedDataType.FEATURE, result.getImage()); + result.setName(imageStructure.getName()); } return result; } @@ -524,6 +540,18 @@ public class TextureHelper extends AbstractBlenderHelper { return result; } + /** + * Reads the texture data from the given material or sky structure. + * @param structure + * the structure of material or sky + * @param diffuseColorArray + * array of diffuse colors + * @param skyTexture + * indicates it we're going to read sky texture or not + * @return a list of combined textures + * @throws BlenderFileException + * an exception is thrown when problems with reading the blend file occur + */ @SuppressWarnings("unchecked") public List readTextureData(Structure structure, float[] diffuseColorArray, boolean skyTexture) throws BlenderFileException { DynamicArray mtexsArray = (DynamicArray) structure.getFieldValue("mtex"); diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/TriangulatedTexture.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/TriangulatedTexture.java index fd4044244..9a4889109 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/TriangulatedTexture.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/TriangulatedTexture.java @@ -31,6 +31,7 @@ import com.jme3.texture.Image; import com.jme3.texture.Image.Format; import com.jme3.texture.Texture; import com.jme3.texture.Texture2D; +import com.jme3.texture.image.ColorSpace; import com.jme3.util.BufferUtils; /** @@ -77,7 +78,7 @@ import com.jme3.util.BufferUtils; for (int i = 0; i < facesCount; ++i) { faceTextures.add(new TriangleTextureElement(i, texture2d.getImage(), uvs, true, blenderContext)); } - this.format = texture2d.getImage().getFormat(); + format = texture2d.getImage().getFormat(); } /** @@ -113,7 +114,7 @@ import com.jme3.util.BufferUtils; */ public void blend(TextureBlender textureBlender, TriangulatedTexture baseTexture, BlenderContext blenderContext) { Format newFormat = null; - for (TriangleTextureElement triangleTextureElement : this.faceTextures) { + for (TriangleTextureElement triangleTextureElement : faceTextures) { Image baseImage = baseTexture == null ? null : baseTexture.getFaceTextureElement(triangleTextureElement.faceIndex).image; triangleTextureElement.image = textureBlender.blend(triangleTextureElement.image, baseImage, blenderContext); if (newFormat == null) { @@ -122,7 +123,7 @@ import com.jme3.util.BufferUtils; throw new IllegalArgumentException("Face texture element images MUST have the same image format!"); } } - this.format = newFormat; + format = newFormat; } /** @@ -242,7 +243,7 @@ import com.jme3.util.BufferUtils; resultUVS.set(entry.getKey().faceIndex * 3 + 2, uvs[2]); } - Image resultImage = new Image(format, resultImageWidth, resultImageHeight, BufferUtils.createByteBuffer(resultImageWidth * resultImageHeight * (format.getBitsPerPixel() >> 3))); + Image resultImage = new Image(format, resultImageWidth, resultImageHeight, BufferUtils.createByteBuffer(resultImageWidth * resultImageHeight * (format.getBitsPerPixel() >> 3)), ColorSpace.Linear); resultTexture = new Texture2D(resultImage); for (Entry entry : imageLayoutData.entrySet()) { if (!duplicatedFaceIndexes.contains(entry.getKey().faceIndex)) { @@ -420,7 +421,7 @@ import com.jme3.util.BufferUtils; data.put(pixel.getA8()); } } - image = new Image(Format.RGBA8, width, height, data); + image = new Image(Format.RGBA8, width, height, data, ColorSpace.Linear); // modify the UV values so that they fit the new image float heightUV = maxUVY - minUVY; @@ -481,7 +482,7 @@ import com.jme3.util.BufferUtils; imageHeight = 1; } ByteBuffer data = BufferUtils.createByteBuffer(imageWidth * imageHeight * (imageFormat.getBitsPerPixel() >> 3)); - image = new Image(texture.getImage().getFormat(), imageWidth, imageHeight, data); + image = new Image(texture.getImage().getFormat(), imageWidth, imageHeight, data, ColorSpace.Linear); // computing the pixels PixelInputOutput pixelWriter = PixelIOFactory.getPixelIO(imageFormat); @@ -529,8 +530,8 @@ import com.jme3.util.BufferUtils; public void computeFinalUVCoordinates(int totalImageWidth, int totalImageHeight, int xPos, int yPos, Vector2f[] result) { for (int i = 0; i < 3; ++i) { result[i] = new Vector2f(); - result[i].x = xPos / (float) totalImageWidth + this.uv[i].x * (this.image.getWidth() / (float) totalImageWidth); - result[i].y = yPos / (float) totalImageHeight + this.uv[i].y * (this.image.getHeight() / (float) totalImageHeight); + result[i].x = xPos / (float) totalImageWidth + uv[i].x * (image.getWidth() / (float) totalImageWidth); + result[i].y = yPos / (float) totalImageHeight + uv[i].y * (image.getHeight() / (float) totalImageHeight); } } @@ -623,9 +624,9 @@ import com.jme3.util.BufferUtils; * a position in 3D space */ public RectangleEnvelope(Vector3f pointPosition) { - this.min = pointPosition; - this.h = this.w = Vector3f.ZERO; - this.width = this.height = 1; + min = pointPosition; + h = w = Vector3f.ZERO; + width = height = 1; } /** @@ -642,8 +643,8 @@ import com.jme3.util.BufferUtils; this.min = min; this.h = h; this.w = w; - this.width = w.length(); - this.height = h.length(); + width = w.length(); + height = h.length(); } @Override diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/blending/AbstractTextureBlender.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/blending/AbstractTextureBlender.java index 5c3504771..8ff55baac 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/blending/AbstractTextureBlender.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/blending/AbstractTextureBlender.java @@ -1,10 +1,12 @@ package com.jme3.scene.plugins.blender.textures.blending; +import java.util.logging.Logger; + +import jme3tools.converters.MipMapGenerator; + import com.jme3.scene.plugins.blender.BlenderContext; import com.jme3.scene.plugins.blender.materials.MaterialHelper; import com.jme3.texture.Image; -import java.util.logging.Logger; -import jme3tools.converters.MipMapGenerator; /** * An abstract class that contains the basic methods used by the classes that @@ -103,12 +105,12 @@ import jme3tools.converters.MipMapGenerator; public void copyBlendingData(TextureBlender textureBlender) { if (textureBlender instanceof AbstractTextureBlender) { - this.flag = ((AbstractTextureBlender) textureBlender).flag; - this.negateTexture = ((AbstractTextureBlender) textureBlender).negateTexture; - this.blendType = ((AbstractTextureBlender) textureBlender).blendType; - this.materialColor = ((AbstractTextureBlender) textureBlender).materialColor.clone(); - this.color = ((AbstractTextureBlender) textureBlender).color.clone(); - this.blendFactor = ((AbstractTextureBlender) textureBlender).blendFactor; + flag = ((AbstractTextureBlender) textureBlender).flag; + negateTexture = ((AbstractTextureBlender) textureBlender).negateTexture; + blendType = ((AbstractTextureBlender) textureBlender).blendType; + materialColor = ((AbstractTextureBlender) textureBlender).materialColor.clone(); + color = ((AbstractTextureBlender) textureBlender).color.clone(); + blendFactor = ((AbstractTextureBlender) textureBlender).blendFactor; } else { LOGGER.warning("Cannot copy blending data from other types than " + this.getClass()); } diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/blending/TextureBlenderAWT.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/blending/TextureBlenderAWT.java index d7f26b1be..1d7bf2146 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/blending/TextureBlenderAWT.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/blending/TextureBlenderAWT.java @@ -38,7 +38,9 @@ import com.jme3.scene.plugins.blender.textures.io.PixelIOFactory; import com.jme3.scene.plugins.blender.textures.io.PixelInputOutput; import com.jme3.texture.Image; import com.jme3.texture.Image.Format; +import com.jme3.texture.image.ColorSpace; import com.jme3.util.BufferUtils; + import java.nio.ByteBuffer; import java.util.ArrayList; @@ -141,7 +143,7 @@ public class TextureBlenderAWT extends AbstractTextureBlender { dataArray.add(newData); } - Image result = depth > 1 ? new Image(Format.RGBA8, width, height, depth, dataArray) : new Image(Format.RGBA8, width, height, dataArray.get(0)); + Image result = depth > 1 ? new Image(Format.RGBA8, width, height, depth, dataArray, ColorSpace.Linear) : new Image(Format.RGBA8, width, height, dataArray.get(0), ColorSpace.Linear); if (image.getMipMapSizes() != null) { result.setMipMapSizes(image.getMipMapSizes().clone()); } diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/blending/TextureBlenderDDS.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/blending/TextureBlenderDDS.java index 264ebc1da..b40e2cc8f 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/blending/TextureBlenderDDS.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/blending/TextureBlenderDDS.java @@ -6,9 +6,12 @@ import com.jme3.scene.plugins.blender.textures.io.PixelIOFactory; import com.jme3.scene.plugins.blender.textures.io.PixelInputOutput; import com.jme3.texture.Image; import com.jme3.texture.Image.Format; +import com.jme3.texture.image.ColorSpace; import com.jme3.util.BufferUtils; + import java.nio.ByteBuffer; import java.util.ArrayList; + import jme3tools.converters.RGB565; /** @@ -119,7 +122,7 @@ public class TextureBlenderDDS extends TextureBlenderAWT { dataArray.add(newData); } - Image result = dataArray.size() > 1 ? new Image(format, width, height, depth, dataArray) : new Image(format, width, height, dataArray.get(0)); + Image result = dataArray.size() > 1 ? new Image(format, width, height, depth, dataArray, ColorSpace.Linear) : new Image(format, width, height, dataArray.get(0), ColorSpace.Linear); if (image.getMipMapSizes() != null) { result.setMipMapSizes(image.getMipMapSizes().clone()); } diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/blending/TextureBlenderFactory.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/blending/TextureBlenderFactory.java index c682ed1e5..f487e240d 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/blending/TextureBlenderFactory.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/blending/TextureBlenderFactory.java @@ -31,13 +31,13 @@ */ package com.jme3.scene.plugins.blender.textures.blending; +import java.util.logging.Level; +import java.util.logging.Logger; + import com.jme3.scene.plugins.blender.BlenderContext; import com.jme3.texture.Image; import com.jme3.texture.Image.Format; -import java.util.logging.Level; -import java.util.logging.Logger; - /** * This class creates the texture blending class depending on the texture type. * @@ -66,7 +66,6 @@ public class TextureBlenderFactory { * the texture format * @return texture blending class */ - @SuppressWarnings("deprecation") public static TextureBlender createTextureBlender(Format format, int flag, boolean negate, int blendType, float[] materialColor, float[] color, float colfac) { switch (format) { case Luminance8: diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/blending/TextureBlenderLuminance.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/blending/TextureBlenderLuminance.java index cbfc28631..1f2ae01e1 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/blending/TextureBlenderLuminance.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/blending/TextureBlenderLuminance.java @@ -7,7 +7,9 @@ import com.jme3.scene.plugins.blender.textures.io.PixelIOFactory; import com.jme3.scene.plugins.blender.textures.io.PixelInputOutput; import com.jme3.texture.Image; import com.jme3.texture.Image.Format; +import com.jme3.texture.image.ColorSpace; import com.jme3.util.BufferUtils; + import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.logging.Level; @@ -93,7 +95,7 @@ public class TextureBlenderLuminance extends AbstractTextureBlender { dataArray.add(newData); } - Image result = depth > 1 ? new Image(Format.RGBA8, width, height, depth, dataArray) : new Image(Format.RGBA8, width, height, dataArray.get(0)); + Image result = depth > 1 ? new Image(Format.RGBA8, width, height, depth, dataArray, ColorSpace.Linear) : new Image(Format.RGBA8, width, height, dataArray.get(0), ColorSpace.Linear); if (image.getMipMapSizes() != null) { result.setMipMapSizes(image.getMipMapSizes().clone()); } diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/io/AWTPixelInputOutput.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/io/AWTPixelInputOutput.java index efacee639..569c328be 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/io/AWTPixelInputOutput.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/io/AWTPixelInputOutput.java @@ -17,12 +17,18 @@ import jme3tools.converters.RGB565; case RGBA8: pixel.fromARGB8(data.get(index + 3), data.get(index), data.get(index + 1), data.get(index + 2)); break; + case ARGB8: + pixel.fromARGB8(data.get(index), data.get(index + 1), data.get(index + 2), data.get(index + 3)); + break; case ABGR8: pixel.fromARGB8(data.get(index), data.get(index + 3), data.get(index + 2), data.get(index + 1)); break; case BGR8: pixel.fromARGB8((byte) 0xFF, data.get(index + 2), data.get(index + 1), data.get(index)); break; + case BGRA8: + pixel.fromARGB8(data.get(index + 3), data.get(index + 2), data.get(index + 1), data.get(index)); + break; case RGB8: pixel.fromARGB8((byte) 0xFF, data.get(index), data.get(index + 1), data.get(index + 2)); break; @@ -72,6 +78,12 @@ import jme3tools.converters.RGB565; data.put(index + 2, pixel.getB8()); data.put(index + 3, pixel.getA8()); break; + case ARGB8: + data.put(index, pixel.getA8()); + data.put(index + 1, pixel.getR8()); + data.put(index + 2, pixel.getG8()); + data.put(index + 3, pixel.getB8()); + break; case ABGR8: data.put(index, pixel.getA8()); data.put(index + 1, pixel.getB8()); @@ -83,6 +95,12 @@ import jme3tools.converters.RGB565; data.put(index + 1, pixel.getG8()); data.put(index + 2, pixel.getR8()); break; + case BGRA8: + data.put(index, pixel.getB8()); + data.put(index + 1, pixel.getG8()); + data.put(index + 2, pixel.getR8()); + data.put(index + 3, pixel.getA8()); + break; case RGB8: data.put(index, pixel.getR8()); data.put(index + 1, pixel.getG8()); diff --git a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/io/PixelIOFactory.java b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/io/PixelIOFactory.java index 916090228..47cf7090b 100644 --- a/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/io/PixelIOFactory.java +++ b/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/io/PixelIOFactory.java @@ -26,7 +26,9 @@ public class PixelIOFactory { case ABGR8: case RGBA8: case BGR8: + case BGRA8: case RGB8: + case ARGB8: case RGB111110F: case RGB16F: case RGB16F_to_RGB111110F: diff --git a/jme3-bullet-native/build.gradle b/jme3-bullet-native/build.gradle index 163485f0e..dbb74981a 100644 --- a/jme3-bullet-native/build.gradle +++ b/jme3-bullet-native/build.gradle @@ -175,7 +175,7 @@ binaries.withType(SharedLibraryBinary) { binary -> // Add depend on build jar.dependsOn builderTask // Add output to libs folder - task "copyBinaryToLibs${targetPlatform}"(type: Copy) { + task "copyBinaryToLibs${targetPlatform}"(type: Copy, dependsOn: builderTask) { from builderTask.outputFile into "libs/native/${targetPlatform.operatingSystem.name}/${targetPlatform.architecture.name}" } diff --git a/jme3-bullet-native/libs/native/windows/x86/bulletjme.dll b/jme3-bullet-native/libs/native/windows/x86/bulletjme.dll index 6839705bf..6874ad53d 100644 Binary files a/jme3-bullet-native/libs/native/windows/x86/bulletjme.dll and b/jme3-bullet-native/libs/native/windows/x86/bulletjme.dll differ diff --git a/jme3-bullet-native/libs/native/windows/x86_64/bulletjme.dll b/jme3-bullet-native/libs/native/windows/x86_64/bulletjme.dll index 3a2aa3449..24ae0eb52 100644 Binary files a/jme3-bullet-native/libs/native/windows/x86_64/bulletjme.dll and b/jme3-bullet-native/libs/native/windows/x86_64/bulletjme.dll differ diff --git a/jme3-bullet-native/src/native/cpp/com_jme3_bullet_PhysicsSpace.cpp b/jme3-bullet-native/src/native/cpp/com_jme3_bullet_PhysicsSpace.cpp index b51630c55..3ecf7fd6b 100644 --- a/jme3-bullet-native/src/native/cpp/com_jme3_bullet_PhysicsSpace.cpp +++ b/jme3-bullet-native/src/native/cpp/com_jme3_bullet_PhysicsSpace.cpp @@ -468,6 +468,79 @@ extern "C" { return; } + + + JNIEXPORT void JNICALL Java_com_jme3_bullet_PhysicsSpace_sweepTest_1native + (JNIEnv * env, jobject object, jlong shapeId, jobject from, jobject to, jlong spaceId, jobject resultlist, jfloat allowedCcdPenetration) { + + jmePhysicsSpace* space = reinterpret_cast (spaceId); + if (space == NULL) { + jclass newExc = env->FindClass("java/lang/NullPointerException"); + env->ThrowNew(newExc, "The physics space does not exist."); + return; + } + + btCollisionShape* shape = reinterpret_cast (shapeId); + if (shape == NULL) { + jclass newExc = env->FindClass("java/lang/NullPointerException"); + env->ThrowNew(newExc, "The shape does not exist."); + return; + } + + struct AllConvexResultCallback : public btCollisionWorld::ConvexResultCallback { + + AllConvexResultCallback(const btTransform& convexFromWorld, const btTransform & convexToWorld) : m_convexFromWorld(convexFromWorld), m_convexToWorld(convexToWorld) { + } + jobject resultlist; + JNIEnv* env; + btTransform m_convexFromWorld; //used to calculate hitPointWorld from hitFraction + btTransform m_convexToWorld; + + btVector3 m_hitNormalWorld; + btVector3 m_hitPointWorld; + + virtual btScalar addSingleResult(btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace) { + if (normalInWorldSpace) { + m_hitNormalWorld = convexResult.m_hitNormalLocal; + } + else { + m_hitNormalWorld = convexResult.m_hitCollisionObject->getWorldTransform().getBasis() * convexResult.m_hitNormalLocal; + } + m_hitPointWorld.setInterpolate3(m_convexFromWorld.getBasis() * m_convexFromWorld.getOrigin(), m_convexToWorld.getBasis() * m_convexToWorld.getOrigin(), convexResult.m_hitFraction); + + jmeBulletUtil::addSweepResult(env, resultlist, &m_hitNormalWorld, &m_hitPointWorld, convexResult.m_hitFraction, convexResult.m_hitCollisionObject); + + return 1.f; + } + }; + + btTransform native_to = btTransform(); + jmeBulletUtil::convert(env, to, &native_to); + + btTransform native_from = btTransform(); + jmeBulletUtil::convert(env, from, &native_from); + + btScalar native_allowed_ccd_penetration = btScalar(allowedCcdPenetration); + + AllConvexResultCallback resultCallback(native_from, native_to); + resultCallback.env = env; + resultCallback.resultlist = resultlist; + space->getDynamicsWorld()->convexSweepTest((btConvexShape *) shape, native_from, native_to, resultCallback, native_allowed_ccd_penetration); + return; + } + + JNIEXPORT void JNICALL Java_com_jme3_bullet_PhysicsSpace_setSolverNumIterations + (JNIEnv *env, jobject object, jlong spaceId, jint value) { + jmePhysicsSpace* space = reinterpret_cast(spaceId); + if (space == NULL) { + jclass newExc = env->FindClass("java/lang/NullPointerException"); + env->ThrowNew(newExc, "The physics space does not exist."); + return; + } + + space->getDynamicsWorld()->getSolverInfo().m_numIterations = value; + } + #ifdef __cplusplus } #endif diff --git a/jme3-bullet-native/src/native/cpp/com_jme3_bullet_PhysicsSpace.h b/jme3-bullet-native/src/native/cpp/com_jme3_bullet_PhysicsSpace.h index e040f8da8..0380c17b0 100644 --- a/jme3-bullet-native/src/native/cpp/com_jme3_bullet_PhysicsSpace.h +++ b/jme3-bullet-native/src/native/cpp/com_jme3_bullet_PhysicsSpace.h @@ -165,6 +165,23 @@ JNIEXPORT void JNICALL Java_com_jme3_bullet_PhysicsSpace_initNativePhysics JNIEXPORT void JNICALL Java_com_jme3_bullet_PhysicsSpace_finalizeNative (JNIEnv *, jobject, jlong); + +/* +* Class: com_jme3_bullet_PhysicsSpace +* Method : sweepTest_native +* Signature: (J;L;Lcom/jme3/math/Transform;Lcom/jme3/math/Transform;L;JLjava/util/List;F)V +*/ +JNIEXPORT void JNICALL Java_com_jme3_bullet_PhysicsSpace_sweepTest_1native +(JNIEnv *, jobject, jlong, jobject, jobject, jlong, jobject, jfloat); + +/* + * Class: com_jme3_bullet_PhysicsSpace + * Method: setSolverNumIterations + * Signature: (JI)V + */ +JNIEXPORT void JNICALL Java_com_jme3_bullet_PhysicsSpace_setSolverNumIterations +(JNIEnv *, jobject, jlong, jint); + #ifdef __cplusplus } #endif diff --git a/jme3-bullet-native/src/native/cpp/jmeBulletUtil.cpp b/jme3-bullet-native/src/native/cpp/jmeBulletUtil.cpp index fa88ad473..04b56a545 100644 --- a/jme3-bullet-native/src/native/cpp/jmeBulletUtil.cpp +++ b/jme3-bullet-native/src/native/cpp/jmeBulletUtil.cpp @@ -59,6 +59,38 @@ void jmeBulletUtil::convert(JNIEnv* env, jobject in, btVector3* out) { out->setZ(z); } +void jmeBulletUtil::convert(JNIEnv* env, jobject in, btQuaternion* out) { + if (in == NULL || out == NULL) { + jmeClasses::throwNPE(env); + } + float x = env->GetFloatField(in, jmeClasses::Quaternion_x); + if (env->ExceptionCheck()) { + env->Throw(env->ExceptionOccurred()); + return; + } + float y = env->GetFloatField(in, jmeClasses::Quaternion_y); //env->CallFloatMethod(in, jmeClasses::Vector3f_getY); + if (env->ExceptionCheck()) { + env->Throw(env->ExceptionOccurred()); + return; + } + float z = env->GetFloatField(in, jmeClasses::Quaternion_z); //env->CallFloatMethod(in, jmeClasses::Vector3f_getZ); + if (env->ExceptionCheck()) { + env->Throw(env->ExceptionOccurred()); + return; + } + + float w = env->GetFloatField(in, jmeClasses::Quaternion_w); //env->CallFloatMethod(in, jmeClasses::Vector3f_getZ); + if (env->ExceptionCheck()) { + env->Throw(env->ExceptionOccurred()); + return; + } + out->setX(x); + out->setY(y); + out->setZ(z); + out->setW(w); +} + + void jmeBulletUtil::convert(JNIEnv* env, const btVector3* in, jobject out) { if (in == NULL || out == NULL) { jmeClasses::throwNPE(env); @@ -325,3 +357,61 @@ void jmeBulletUtil::addResult(JNIEnv* env, jobject resultlist, btVector3* hitnor return; } } + + +void jmeBulletUtil::addSweepResult(JNIEnv* env, jobject resultlist, btVector3* hitnormal, btVector3* m_hitPointWorld, btScalar m_hitFraction, const btCollisionObject* hitobject) { + + jobject singleresult = env->AllocObject(jmeClasses::PhysicsSweep_Class); + jobject hitnormalvec = env->AllocObject(jmeClasses::Vector3f); + + convert(env, hitnormal, hitnormalvec); + jmeUserPointer *up1 = (jmeUserPointer*)hitobject->getUserPointer(); + + env->SetObjectField(singleresult, jmeClasses::PhysicsSweep_normalInWorldSpace, hitnormalvec); + env->SetFloatField(singleresult, jmeClasses::PhysicsSweep_hitfraction, m_hitFraction); + + env->SetObjectField(singleresult, jmeClasses::PhysicsSweep_collisionObject, up1->javaCollisionObject); + env->CallVoidMethod(resultlist, jmeClasses::PhysicsSweep_addmethod, singleresult); + if (env->ExceptionCheck()) { + env->Throw(env->ExceptionOccurred()); + return; + } +} + +void jmeBulletUtil::convert(JNIEnv* env, jobject in, btTransform* out) { + if (in == NULL || out == NULL) { + jmeClasses::throwNPE(env); + } + + jobject translation_vec = env->CallObjectMethod(in, jmeClasses::Transform_translation); + if (env->ExceptionCheck()) { + env->Throw(env->ExceptionOccurred()); + return; + } + + jobject rot_quat = env->CallObjectMethod(in, jmeClasses::Transform_rotation); + if (env->ExceptionCheck()) { + env->Throw(env->ExceptionOccurred()); + return; + } + + /* + //Scale currently not supported by bullet + //@TBD: Create an assertion somewhere to avoid scale values + jobject scale_vec = env->GetObjectField(in, jmeClasses::Transform_scale); + if (env->ExceptionCheck()) { + env->Throw(env->ExceptionOccurred()); + return; + } + */ + btVector3 native_translation_vec = btVector3(); + //btVector3 native_scale_vec = btVector3(); + btQuaternion native_rot_quat = btQuaternion(); + + convert(env, translation_vec, &native_translation_vec); + //convert(env, scale_vec, native_scale_vec); + convert(env, rot_quat, &native_rot_quat); + + out->setRotation(native_rot_quat); + out->setOrigin(native_translation_vec); +} diff --git a/jme3-bullet-native/src/native/cpp/jmeBulletUtil.h b/jme3-bullet-native/src/native/cpp/jmeBulletUtil.h index 96509ab9e..7d982c80e 100644 --- a/jme3-bullet-native/src/native/cpp/jmeBulletUtil.h +++ b/jme3-bullet-native/src/native/cpp/jmeBulletUtil.h @@ -42,10 +42,13 @@ public: static void convert(JNIEnv* env, jobject in, btVector3* out); static void convert(JNIEnv* env, const btVector3* in, jobject out); static void convert(JNIEnv* env, jobject in, btMatrix3x3* out); + static void convert(JNIEnv* env, jobject in, btQuaternion* out); static void convert(JNIEnv* env, const btMatrix3x3* in, jobject out); static void convertQuat(JNIEnv* env, jobject in, btMatrix3x3* out); static void convertQuat(JNIEnv* env, const btMatrix3x3* in, jobject out); + static void convert(JNIEnv* env, jobject in, btTransform* out); static void addResult(JNIEnv* env, jobject resultlist, btVector3* hitnormal, btVector3* m_hitPointWorld,const btScalar m_hitFraction,const btCollisionObject* hitobject); + static void addSweepResult(JNIEnv* env, jobject resultlist, btVector3* hitnormal, btVector3* m_hitPointWorld, const btScalar m_hitFraction, const btCollisionObject* hitobject); private: jmeBulletUtil(){}; ~jmeBulletUtil(){}; diff --git a/jme3-bullet-native/src/native/cpp/jmeClasses.cpp b/jme3-bullet-native/src/native/cpp/jmeClasses.cpp index e0b5515b4..6b7caa0e9 100644 --- a/jme3-bullet-native/src/native/cpp/jmeClasses.cpp +++ b/jme3-bullet-native/src/native/cpp/jmeClasses.cpp @@ -91,6 +91,21 @@ jfieldID jmeClasses::PhysicsRay_collisionObject; jclass jmeClasses::PhysicsRay_listresult; jmethodID jmeClasses::PhysicsRay_addmethod; +jclass jmeClasses::PhysicsSweep_Class; +jmethodID jmeClasses::PhysicsSweep_newSingleResult; + +jfieldID jmeClasses::PhysicsSweep_normalInWorldSpace; +jfieldID jmeClasses::PhysicsSweep_hitfraction; +jfieldID jmeClasses::PhysicsSweep_collisionObject; + +jclass jmeClasses::PhysicsSweep_listresult; +jmethodID jmeClasses::PhysicsSweep_addmethod; + + +jclass jmeClasses::Transform; +jmethodID jmeClasses::Transform_rotation; +jmethodID jmeClasses::Transform_translation; + //private fields //JNIEnv* jmeClasses::env; JavaVM* jmeClasses::vm; @@ -240,6 +255,70 @@ void jmeClasses::initJavaClasses(JNIEnv* env) { env->Throw(env->ExceptionOccurred()); return; } + + PhysicsSweep_Class = (jclass)env->NewGlobalRef(env->FindClass("com/jme3/bullet/collision/PhysicsSweepTestResult")); + if (env->ExceptionCheck()) { + env->Throw(env->ExceptionOccurred()); + return; +} + + PhysicsSweep_newSingleResult = env->GetMethodID(PhysicsSweep_Class, "", "()V"); + if (env->ExceptionCheck()) { + env->Throw(env->ExceptionOccurred()); + return; + } + + PhysicsSweep_normalInWorldSpace = env->GetFieldID(PhysicsSweep_Class, "hitNormalLocal", "Lcom/jme3/math/Vector3f;"); + if (env->ExceptionCheck()) { + env->Throw(env->ExceptionOccurred()); + return; + } + + + PhysicsSweep_hitfraction = env->GetFieldID(PhysicsSweep_Class, "hitFraction", "F"); + if (env->ExceptionCheck()) { + env->Throw(env->ExceptionOccurred()); + return; + } + + + PhysicsSweep_collisionObject = env->GetFieldID(PhysicsSweep_Class, "collisionObject", "Lcom/jme3/bullet/collision/PhysicsCollisionObject;"); + if (env->ExceptionCheck()) { + env->Throw(env->ExceptionOccurred()); + return; + } + + PhysicsSweep_listresult = env->FindClass("java/util/List"); + PhysicsSweep_listresult = (jclass)env->NewGlobalRef(PhysicsSweep_listresult); + if (env->ExceptionCheck()) { + env->Throw(env->ExceptionOccurred()); + return; + } + + PhysicsSweep_addmethod = env->GetMethodID(PhysicsSweep_listresult, "add", "(Ljava/lang/Object;)Z"); + if (env->ExceptionCheck()) { + env->Throw(env->ExceptionOccurred()); + return; + } + + Transform = (jclass)env->NewGlobalRef(env->FindClass("com/jme3/math/Transform")); + if (env->ExceptionCheck()) { + env->Throw(env->ExceptionOccurred()); + return; + } + + Transform_rotation = env->GetMethodID(Transform, "getRotation", "()Lcom/jme3/math/Quaternion;"); + if (env->ExceptionCheck()) { + env->Throw(env->ExceptionOccurred()); + return; + } + + Transform_translation = env->GetMethodID(Transform, "getTranslation", "()Lcom/jme3/math/Vector3f;"); + if (env->ExceptionCheck()) { + env->Throw(env->ExceptionOccurred()); + return; + } + } void jmeClasses::throwNPE(JNIEnv* env) { diff --git a/jme3-bullet-native/src/native/cpp/jmeClasses.h b/jme3-bullet-native/src/native/cpp/jmeClasses.h index 24684dae9..bb1b0e99a 100644 --- a/jme3-bullet-native/src/native/cpp/jmeClasses.h +++ b/jme3-bullet-native/src/native/cpp/jmeClasses.h @@ -89,6 +89,18 @@ public: static jclass PhysicsRay_listresult; static jmethodID PhysicsRay_addmethod; + static jclass PhysicsSweep_Class; + static jmethodID PhysicsSweep_newSingleResult; + static jfieldID PhysicsSweep_normalInWorldSpace; + static jfieldID PhysicsSweep_hitfraction; + static jfieldID PhysicsSweep_collisionObject; + static jclass PhysicsSweep_listresult; + static jmethodID PhysicsSweep_addmethod; + + static jclass Transform; + static jmethodID Transform_rotation; + static jmethodID Transform_translation; + static jclass DebugMeshCallback; static jmethodID DebugMeshCallback_addVector; diff --git a/jme3-bullet/src/common/java/com/jme3/bullet/BulletAppState.java b/jme3-bullet/src/common/java/com/jme3/bullet/BulletAppState.java index 05aa9a926..ae278c871 100644 --- a/jme3-bullet/src/common/java/com/jme3/bullet/BulletAppState.java +++ b/jme3-bullet/src/common/java/com/jme3/bullet/BulletAppState.java @@ -166,7 +166,7 @@ public class BulletAppState implements AppState, PhysicsTickListener { pSpace.addTickListener(this); initialized = true; } - + public void stopPhysics() { if(!initialized){ return; @@ -226,19 +226,9 @@ public class BulletAppState implements AppState, PhysicsTickListener { if (debugEnabled && debugAppState == null && pSpace != null) { debugAppState = new BulletDebugAppState(pSpace); stateManager.attach(debugAppState); - pSpace.enableDebug(app.getAssetManager()); } else if (!debugEnabled && debugAppState != null) { stateManager.detach(debugAppState); debugAppState = null; - if (pSpace != null) { - pSpace.enableDebug(null); - } - } - //TODO: remove when deprecation of PhysicsSpace.enableDebug is through - if (pSpace.getDebugManager() != null && !debugEnabled) { - debugEnabled = true; - } else if (pSpace.getDebugManager() == null && debugEnabled) { - debugEnabled = false; } if (!active) { return; diff --git a/jme3-bullet/src/common/java/com/jme3/bullet/control/RigidBodyControl.java b/jme3-bullet/src/common/java/com/jme3/bullet/control/RigidBodyControl.java index c4c0f3995..baad952a0 100644 --- a/jme3-bullet/src/common/java/com/jme3/bullet/control/RigidBodyControl.java +++ b/jme3-bullet/src/common/java/com/jme3/bullet/control/RigidBodyControl.java @@ -195,7 +195,7 @@ public class RigidBodyControl extends PhysicsRigidBody implements PhysicsControl /** * When set to true, the physics coordinates will be applied to the local - * translation of the Spatial instead of the world traslation. + * translation of the Spatial instead of the world translation. * @param applyPhysicsLocal */ public void setApplyPhysicsLocal(boolean applyPhysicsLocal) { diff --git a/jme3-bullet/src/main/java/com/jme3/bullet/PhysicsSpace.java b/jme3-bullet/src/main/java/com/jme3/bullet/PhysicsSpace.java index 0f011f8d7..edea485ef 100644 --- a/jme3-bullet/src/main/java/com/jme3/bullet/PhysicsSpace.java +++ b/jme3-bullet/src/main/java/com/jme3/bullet/PhysicsSpace.java @@ -102,7 +102,7 @@ public class PhysicsSpace { private Vector3f worldMax = new Vector3f(10000f, 10000f, 10000f); private float accuracy = 1f / 60f; private int maxSubSteps = 4, rayTestFlags = 1 << 2; - private AssetManager debugManager; + private int solverNumIterations = 10; static { // System.loadLibrary("bulletjme"); @@ -702,7 +702,7 @@ public class PhysicsSpace { public Vector3f getGravity(Vector3f gravity) { return gravity.set(this.gravity); } - + // /** // * applies gravity value to all objects // */ @@ -783,7 +783,7 @@ public class PhysicsSpace { public void SetRayTestFlags(int flags) { rayTestFlags = flags; } - + /** * Gets m_flags for raytest, see https://code.google.com/p/bullet/source/browse/trunk/src/BulletCollision/NarrowPhaseCollision/btRaycastCallback.h * for possible options. @@ -792,7 +792,7 @@ public class PhysicsSpace { public int GetRayTestFlags() { return rayTestFlags; } - + /** * Performs a ray collision test and returns the results as a list of * PhysicsRayTestResults @@ -820,6 +820,10 @@ public class PhysicsSpace { // return lrr.hitFraction; // } // } +// +// + + /** * Performs a sweep collision test and returns the results as a list of * PhysicsSweepTestResults
You have to use different Transforms for @@ -828,48 +832,47 @@ public class PhysicsSpace { * center. */ public List sweepTest(CollisionShape shape, Transform start, Transform end) { - List results = new LinkedList(); -// if (!(shape.getCShape() instanceof ConvexShape)) { -// logger.log(Level.WARNING, "Trying to sweep test with incompatible mesh shape!"); -// return results; -// } -// dynamicsWorld.convexSweepTest((ConvexShape) shape.getCShape(), Converter.convert(start, sweepTrans1), Converter.convert(end, sweepTrans2), new InternalSweepListener(results)); - return results; + List results = new LinkedList(); + sweepTest(shape, start, end , results); + return (List) results; + } + public List sweepTest(CollisionShape shape, Transform start, Transform end, List results) { + return sweepTest(shape, start, end, results, 0.0f); } + public native void sweepTest_native(long shape, Transform from, Transform to, long physicsSpaceId, List results, float allowedCcdPenetration); /** * Performs a sweep collision test and returns the results as a list of * PhysicsSweepTestResults
You have to use different Transforms for - * start and end (at least distance > 0.4f). SweepTest will not see a + * start and end (at least distance > allowedCcdPenetration). SweepTest will not see a * collision if it starts INSIDE an object and is moving AWAY from its * center. */ - public List sweepTest(CollisionShape shape, Transform start, Transform end, List results) { + public List sweepTest(CollisionShape shape, Transform start, Transform end, List results, float allowedCcdPenetration ) { results.clear(); -// if (!(shape.getCShape() instanceof ConvexShape)) { -// logger.log(Level.WARNING, "Trying to sweep test with incompatible mesh shape!"); -// return results; -// } -// dynamicsWorld.convexSweepTest((ConvexShape) shape.getCShape(), Converter.convert(start, sweepTrans1), Converter.convert(end, sweepTrans2), new InternalSweepListener(results)); + sweepTest_native(shape.getObjectId(), start, end, physicsSpaceId, results, allowedCcdPenetration); return results; } -// private class InternalSweepListener extends CollisionWorld.ConvexResultCallback { -// -// private List results; -// -// public InternalSweepListener(List results) { -// this.results = results; -// } -// -// @Override -// public float addSingleResult(LocalConvexResult lcr, boolean bln) { -// PhysicsCollisionObject obj = (PhysicsCollisionObject) lcr.hitCollisionObject.getUserPointer(); -// results.add(new PhysicsSweepTestResult(obj, Converter.convert(lcr.hitNormalLocal), lcr.hitFraction, bln)); -// return lcr.hitFraction; -// } -// } +/* private class InternalSweepListener extends CollisionWorld.ConvexResultCallback { + + private List results; + + public InternalSweepListener(List results) { + this.results = results; + } + + @Override + public float addSingleResult(LocalConvexResult lcr, boolean bln) { + PhysicsCollisionObject obj = (PhysicsCollisionObject) lcr.hitCollisionObject.getUserPointer(); + results.add(new PhysicsSweepTestResult(obj, Converter.convert(lcr.hitNormalLocal), lcr.hitFraction, bln)); + return lcr.hitFraction; + } + } + + */ + /** * destroys the current PhysicsSpace so that a new one can be created */ @@ -957,28 +960,28 @@ public class PhysicsSpace { } /** - * Enable debug display for physics. - * - * @deprecated in favor of BulletDebugAppState, use - * BulletAppState.setDebugEnabled(boolean) to add automatically - * @param manager AssetManager to use to create debug materials + * Set the number of iterations used by the contact solver. + * + * The default is 10. Use 4 for low quality, 20 for high quality. + * + * @param numIterations The number of iterations used by the contact & constraint solver. */ - @Deprecated - public void enableDebug(AssetManager manager) { - debugManager = manager; + public void setSolverNumIterations(int numIterations) { + this.solverNumIterations = numIterations; + setSolverNumIterations(physicsSpaceId, numIterations); } - + /** - * Disable debug display + * Get the number of iterations used by the contact solver. + * + * @return The number of iterations used by the contact & constraint solver. */ - public void disableDebug() { - debugManager = null; + public int getSolverNumIterations() { + return solverNumIterations; } - - public AssetManager getDebugManager() { - return debugManager; - } - + + private static native void setSolverNumIterations(long physicsSpaceId, int numIterations); + public static native void initNativePhysics(); /** diff --git a/jme3-core/build.gradle b/jme3-core/build.gradle index 78bc24dd1..bd699f52a 100644 --- a/jme3-core/build.gradle +++ b/jme3-core/build.gradle @@ -26,14 +26,29 @@ import org.ajoberstar.grgit.* task updateVersion << { - def grgit = Grgit.open(project.file('.').parent) + def verfile = file('src/main/java/com/jme3/system/JmeVersion.java') + def jmeGitHash + def jmeShortGitHash + def jmeBuildDate + def jmeBranchName - def jmeGitHash = grgit.head().id - def jmeShortGitHash = grgit.head().abbreviatedId - def jmeBuildDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) - def jmeBranchName = grgit.branch.current.name + try { + def grgit = Grgit.open(project.file('.').parent) + jmeGitHash = grgit.head().id + jmeShortGitHash = grgit.head().abbreviatedId + jmeBuildDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + jmeBranchName = grgit.branch.current.name + } catch (ex) { + // Failed to get repo info + logger.warn("Failed to get repository info: " + ex.message + ". " + \ + "Only partial build info will be generated.") + + jmeGitHash = "" + jmeShortGitHash = "" + jmeBuildDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + jmeBranchName = "unknown" + } - def verfile = file('src/main/java/com/jme3/system/JmeVersion.java') verfile.text = "\npackage com.jme3.system;\n\n" + "/**\n * THIS IS AN AUTO-GENERATED FILE..\n * DO NOT MODIFY!\n */\n" + "public class JmeVersion {\n" + diff --git a/jme3-core/src/main/java/com/jme3/animation/AnimChannel.java b/jme3-core/src/main/java/com/jme3/animation/AnimChannel.java index 4c362ff00..44b836115 100644 --- a/jme3-core/src/main/java/com/jme3/animation/AnimChannel.java +++ b/jme3-core/src/main/java/com/jme3/animation/AnimChannel.java @@ -312,7 +312,6 @@ public final class AnimChannel { } } animation = null; - // System.out.println("Setting notified false"); notified = false; } diff --git a/jme3-core/src/main/java/com/jme3/animation/Bone.java b/jme3-core/src/main/java/com/jme3/animation/Bone.java index 819a77383..a78b4b931 100644 --- a/jme3-core/src/main/java/com/jme3/animation/Bone.java +++ b/jme3-core/src/main/java/com/jme3/animation/Bone.java @@ -313,6 +313,26 @@ public final class Bone implements Savable { return modelBindInverseScale; } + public Transform getModelBindInverseTransform() { + Transform t = new Transform(); + t.setTranslation(modelBindInversePos); + t.setRotation(modelBindInverseRot); + if (modelBindInverseScale != null) { + t.setScale(modelBindInverseScale); + } + return t; + } + + public Transform getBindInverseTransform() { + Transform t = new Transform(); + t.setTranslation(bindPos); + t.setRotation(bindRot); + if (bindScale != null) { + t.setScale(bindScale); + } + return t.invert(); + } + /** * @deprecated use {@link #getBindPosition()} */ diff --git a/jme3-core/src/main/java/com/jme3/animation/SkeletonControl.java b/jme3-core/src/main/java/com/jme3/animation/SkeletonControl.java index d5ef31939..b1f3d02df 100644 --- a/jme3-core/src/main/java/com/jme3/animation/SkeletonControl.java +++ b/jme3-core/src/main/java/com/jme3/animation/SkeletonControl.java @@ -82,7 +82,7 @@ public class SkeletonControl extends AbstractControl implements Cloneable { /** * User wishes to use hardware skinning if available. */ - private transient boolean hwSkinningDesired = false; + private transient boolean hwSkinningDesired = true; /** * Hardware skinning is currently being used. @@ -347,11 +347,22 @@ public class SkeletonControl extends AbstractControl implements Cloneable { public Control cloneForSpatial(Spatial spatial) { Node clonedNode = (Node) spatial; - AnimControl ctrl = spatial.getControl(AnimControl.class); SkeletonControl clone = new SkeletonControl(); - clone.skeleton = ctrl.getSkeleton(); - + AnimControl ctrl = spatial.getControl(AnimControl.class); + if (ctrl != null) { + // AnimControl is responsible for cloning the skeleton, not + // SkeletonControl. + clone.skeleton = ctrl.getSkeleton(); + } else { + // If there's no AnimControl, create the clone ourselves. + clone.skeleton = new Skeleton(skeleton); + } + clone.hwSkinningDesired = this.hwSkinningDesired; + clone.hwSkinningEnabled = this.hwSkinningEnabled; + clone.hwSkinningSupported = this.hwSkinningSupported; + clone.hwSkinningTested = this.hwSkinningTested; + clone.setSpatial(clonedNode); // Fix attachments for the cloned node diff --git a/jme3-core/src/main/java/com/jme3/app/StatsView.java b/jme3-core/src/main/java/com/jme3/app/StatsView.java index 9f748fdf4..a0446e85e 100644 --- a/jme3-core/src/main/java/com/jme3/app/StatsView.java +++ b/jme3-core/src/main/java/com/jme3/app/StatsView.java @@ -60,7 +60,7 @@ import com.jme3.scene.control.Control; */ public class StatsView extends Node implements Control { - private BitmapText[] labels; + private BitmapText statText; private Statistics statistics; private String[] statLabels; @@ -81,20 +81,17 @@ public class StatsView extends Node implements Control { statLabels = statistics.getLabels(); statData = new int[statLabels.length]; - labels = new BitmapText[statLabels.length]; BitmapFont font = manager.loadFont("Interface/Fonts/Console.fnt"); - for (int i = 0; i < labels.length; i++){ - labels[i] = new BitmapText(font); - labels[i].setLocalTranslation(0, labels[i].getLineHeight() * (i+1), 0); - attachChild(labels[i]); - } + statText = new BitmapText(font); + statText.setLocalTranslation(0, statText.getLineHeight() * statLabels.length, 0); + attachChild(statText); addControl(this); } public float getHeight() { - return labels[0].getLineHeight() * statLabels.length; + return statText.getLineHeight() * statLabels.length; } public void update(float tpf) { @@ -103,11 +100,14 @@ public class StatsView extends Node implements Control { return; statistics.getData(statData); - for (int i = 0; i < labels.length; i++) { - stringBuilder.setLength(0); - stringBuilder.append(statLabels[i]).append(" = ").append(statData[i]); - labels[i].setText(stringBuilder); + stringBuilder.setLength(0); + + // Need to walk through it backwards, as the first label + // should appear at the bottom, not the top. + for (int i = statLabels.length - 1; i >= 0; i--) { + stringBuilder.append(statLabels[i]).append(" = ").append(statData[i]).append('\n'); } + statText.setText(stringBuilder); // Moved to ResetStatsState to make sure it is // done even if there is no StatsView or the StatsView diff --git a/jme3-core/src/main/java/com/jme3/asset/AssetConfig.java b/jme3-core/src/main/java/com/jme3/asset/AssetConfig.java index 50b6e38af..71c4d8bb1 100644 --- a/jme3-core/src/main/java/com/jme3/asset/AssetConfig.java +++ b/jme3-core/src/main/java/com/jme3/asset/AssetConfig.java @@ -69,7 +69,7 @@ public final class AssetConfig { public static void loadText(AssetManager assetManager, URL configUrl) throws IOException{ InputStream in = configUrl.openStream(); try { - Scanner scan = new Scanner(in); + Scanner scan = new Scanner(in, "UTF-8"); scan.useLocale(Locale.US); // Fix commas / periods ?? while (scan.hasNext()){ String cmd = scan.next(); diff --git a/jme3-core/src/main/java/com/jme3/asset/DesktopAssetManager.java b/jme3-core/src/main/java/com/jme3/asset/DesktopAssetManager.java index 4364f3b60..66a6fbbdf 100644 --- a/jme3-core/src/main/java/com/jme3/asset/DesktopAssetManager.java +++ b/jme3-core/src/main/java/com/jme3/asset/DesktopAssetManager.java @@ -312,13 +312,12 @@ public class DesktopAssetManager implements AssetManager { protected T registerAndCloneSmartAsset(AssetKey key, T obj, AssetProcessor proc, AssetCache cache) { // object obj is the original asset // create an instance for user - T clone = (T) obj; if (proc == null) { throw new IllegalStateException("Asset implements " + "CloneableSmartAsset but doesn't " + "have processor to handle cloning"); } else { - clone = (T) proc.createClone(obj); + T clone = (T) proc.createClone(obj); if (cache != null && clone != obj) { cache.registerAssetClone(key, clone); } else { @@ -326,8 +325,8 @@ public class DesktopAssetManager implements AssetManager { + "CloneableSmartAsset but doesn't have cache or " + "was not cloned"); } + return clone; } - return clone; } @Override diff --git a/jme3-core/src/main/java/com/jme3/asset/ImplHandler.java b/jme3-core/src/main/java/com/jme3/asset/ImplHandler.java index 571be53c3..73e6d8df3 100644 --- a/jme3-core/src/main/java/com/jme3/asset/ImplHandler.java +++ b/jme3-core/src/main/java/com/jme3/asset/ImplHandler.java @@ -47,7 +47,7 @@ import java.util.logging.Logger; * This is done by keeping an instance of each asset loader and asset * locator object in a thread local. */ -public class ImplHandler { +final class ImplHandler { private static final Logger logger = Logger.getLogger(ImplHandler.class.getName()); @@ -75,7 +75,7 @@ public class ImplHandler { this.assetManager = assetManager; } - protected class ImplThreadLocal extends ThreadLocal { + protected static class ImplThreadLocal extends ThreadLocal { private final Class type; private final String path; @@ -83,7 +83,7 @@ public class ImplHandler { public ImplThreadLocal(Class type, String[] extensions){ this.type = type; - this.extensions = extensions; + this.extensions = extensions.clone(); this.path = null; } @@ -195,8 +195,8 @@ public class ImplHandler { // No need to synchronize() against map, its concurrent ImplThreadLocal local = extensionToLoaderMap.get(key.getExtension()); if (local == null){ - throw new IllegalStateException("No loader registered for type \"" + - key.getExtension() + "\""); + throw new AssetLoadException("No loader registered for type \"" + + key.getExtension() + "\""); } return (AssetLoader) local.get(); diff --git a/jme3-core/src/main/java/com/jme3/asset/ShaderNodeDefinitionKey.java b/jme3-core/src/main/java/com/jme3/asset/ShaderNodeDefinitionKey.java index db25a1217..9713d6ab8 100644 --- a/jme3-core/src/main/java/com/jme3/asset/ShaderNodeDefinitionKey.java +++ b/jme3-core/src/main/java/com/jme3/asset/ShaderNodeDefinitionKey.java @@ -39,8 +39,6 @@ import java.util.List; * Used for loading {@link ShaderNodeDefinition shader nodes definition} * * Tells if the defintion has to be loaded with or without its documentation - * - * @author Kirill Vainer */ public class ShaderNodeDefinitionKey extends AssetKey> { diff --git a/jme3-core/src/main/java/com/jme3/asset/cache/WeakRefCloneAssetCache.java b/jme3-core/src/main/java/com/jme3/asset/cache/WeakRefCloneAssetCache.java index e3566d22c..ab3581013 100644 --- a/jme3-core/src/main/java/com/jme3/asset/cache/WeakRefCloneAssetCache.java +++ b/jme3-core/src/main/java/com/jme3/asset/cache/WeakRefCloneAssetCache.java @@ -155,11 +155,7 @@ public class WeakRefCloneAssetCache implements AssetCache { } public T getFromCache(AssetKey key) { - AssetRef smartInfo; - synchronized (smartCache){ - smartInfo = smartCache.get(key); - } - + AssetRef smartInfo = smartCache.get(key); if (smartInfo == null) { return null; } else { diff --git a/jme3-core/src/main/java/com/jme3/audio/AudioNode.java b/jme3-core/src/main/java/com/jme3/audio/AudioNode.java index 0e75db9fe..8664af6c7 100644 --- a/jme3-core/src/main/java/com/jme3/audio/AudioNode.java +++ b/jme3-core/src/main/java/com/jme3/audio/AudioNode.java @@ -77,7 +77,7 @@ public class AudioNode extends Node implements AudioSource { protected transient volatile AudioSource.Status status = AudioSource.Status.Stopped; protected transient volatile int channel = -1; protected Vector3f velocity = new Vector3f(); - protected boolean reverbEnabled = true; + protected boolean reverbEnabled = false; protected float maxDistance = 200; // 200 meters protected float refDistance = 10; // 10 meters protected Filter reverbFilter; @@ -409,6 +409,14 @@ public class AudioNode extends Node implements AudioSource { play(); } } + + @Override + public float getPlaybackTime() { + if (channel >= 0) + return getRenderer().getSourcePlaybackTime(this); + else + return 0; + } public Vector3f getPosition() { return getWorldTranslation(); diff --git a/jme3-core/src/main/java/com/jme3/audio/AudioRenderer.java b/jme3-core/src/main/java/com/jme3/audio/AudioRenderer.java index 78ea88e91..695999e48 100644 --- a/jme3-core/src/main/java/com/jme3/audio/AudioRenderer.java +++ b/jme3-core/src/main/java/com/jme3/audio/AudioRenderer.java @@ -59,6 +59,7 @@ public interface AudioRenderer { public void updateSourceParam(AudioSource src, AudioParam param); public void updateListenerParam(Listener listener, ListenerParam param); + public float getSourcePlaybackTime(AudioSource src); public void deleteFilter(Filter filter); public void deleteAudioData(AudioData ad); diff --git a/jme3-core/src/main/java/com/jme3/audio/AudioSource.java b/jme3-core/src/main/java/com/jme3/audio/AudioSource.java index 3aa23b78d..75a4e70f9 100644 --- a/jme3-core/src/main/java/com/jme3/audio/AudioSource.java +++ b/jme3-core/src/main/java/com/jme3/audio/AudioSource.java @@ -95,6 +95,11 @@ public interface AudioSource { * @return the time offset in the sound sample when to start playing. */ public float getTimeOffset(); + + /** + * @return the current playback position of the source in seconds. + */ + public float getPlaybackTime(); /** * @return The velocity of the audio source. diff --git a/jme3-core/src/main/java/com/jme3/audio/AudioStream.java b/jme3-core/src/main/java/com/jme3/audio/AudioStream.java index f7ff4c04b..598ae189c 100644 --- a/jme3-core/src/main/java/com/jme3/audio/AudioStream.java +++ b/jme3-core/src/main/java/com/jme3/audio/AudioStream.java @@ -54,6 +54,8 @@ public class AudioStream extends AudioData implements Closeable { protected boolean eof = false; protected int[] ids; + protected int unqueuedBuffersBytes = 0; + public AudioStream() { super(); } @@ -196,10 +198,21 @@ public class AudioStream extends AudioData implements Closeable { return in instanceof SeekableStream; } + public int getUnqueuedBufferBytes() { + return unqueuedBuffersBytes; + } + + public void setUnqueuedBufferBytes(int unqueuedBuffers) { + this.unqueuedBuffersBytes = unqueuedBuffers; + } + public void setTime(float time) { if (in instanceof SeekableStream) { ((SeekableStream) in).setTime(time); eof = false; + + // TODO: when we actually support seeking, this will need to be properly set. + unqueuedBuffersBytes = 0; } else { throw new IllegalStateException( "Cannot use setTime on a stream that " diff --git a/jme3-core/src/main/java/com/jme3/audio/openal/ALAudioRenderer.java b/jme3-core/src/main/java/com/jme3/audio/openal/ALAudioRenderer.java index 346998e2e..62f04018a 100644 --- a/jme3-core/src/main/java/com/jme3/audio/openal/ALAudioRenderer.java +++ b/jme3-core/src/main/java/com/jme3/audio/openal/ALAudioRenderer.java @@ -51,6 +51,9 @@ import static com.jme3.audio.openal.EFX.*; public class ALAudioRenderer implements AudioRenderer, Runnable { private static final Logger logger = Logger.getLogger(ALAudioRenderer.class.getName()); + + private static final String THREAD_NAME = "jME3 Audio Decoder"; + private final NativeObjectManager objManager = new NativeObjectManager(); // When multiplied by STREAMING_BUFFER_COUNT, will equal 44100 * 2 * 2 // which is exactly 1 second of audio. @@ -75,7 +78,7 @@ public class ALAudioRenderer implements AudioRenderer, Runnable { // Fill streaming sources every 50 ms private static final float UPDATE_RATE = 0.05f; - private final Thread decoderThread = new Thread(this, "jME3 Audio Decoding Thread"); + private final Thread decoderThread = new Thread(this, THREAD_NAME); private final Object threadLock = new Object(); private final AL al; @@ -298,6 +301,58 @@ public class ALAudioRenderer implements AudioRenderer, Runnable { f.clearUpdateNeeded(); } + @Override + public float getSourcePlaybackTime(AudioSource src) { + checkDead(); + synchronized (threadLock) { + if (audioDisabled) { + return 0; + } + + // See comment in updateSourceParam(). + if (src.getChannel() < 0) { + return 0; + } + + int id = channels[src.getChannel()]; + AudioData data = src.getAudioData(); + int playbackOffsetBytes = 0; + + if (data instanceof AudioStream) { + // Because audio streams are processed in buffer chunks, + // we have to compute the amount of time the stream was already + // been playing based on the number of buffers that were processed. + AudioStream stream = (AudioStream) data; + + // NOTE: the assumption is that all enqueued buffers are the same size. + // this is currently enforced by fillBuffer(). + + // The number of unenqueued bytes that the decoder thread + // keeps track of. + int unqueuedBytes = stream.getUnqueuedBufferBytes(); + + // Additional processed buffers that the decoder thread + // did not unenqueue yet (it only updates 20 times per second). + int unqueuedBytesExtra = al.alGetSourcei(id, AL_BUFFERS_PROCESSED) * BUFFER_SIZE; + + // Total additional bytes that need to be considered. + playbackOffsetBytes = unqueuedBytes; // + unqueuedBytesExtra; + } + + // Add byte offset from source (for both streams and buffers) + playbackOffsetBytes += al.alGetSourcei(id, AL_BYTE_OFFSET); + + // Compute time value from bytes + // E.g. for 44100 source with 2 channels and 16 bits per sample: + // (44100 * 2 * 16 / 8) = 176400 + int bytesPerSecond = (data.getSampleRate() * + data.getChannels() * + data.getBitsPerSample() / 8); + + return (float)playbackOffsetBytes / bytesPerSecond; + } + } + public void updateSourceParam(AudioSource src, AudioParam param) { checkDead(); synchronized (threadLock) { @@ -645,6 +700,7 @@ public class ALAudioRenderer implements AudioRenderer, Runnable { private boolean fillStreamingSource(int sourceId, AudioStream stream, boolean looping) { boolean success = false; int processed = al.alGetSourcei(sourceId, AL_BUFFERS_PROCESSED); + int unqueuedBufferBytes = 0; for (int i = 0; i < processed; i++) { int buffer; @@ -653,6 +709,11 @@ public class ALAudioRenderer implements AudioRenderer, Runnable { al.alSourceUnqueueBuffers(sourceId, 1, ib); buffer = ib.get(0); + // XXX: assume that reading from AudioStream always + // gives BUFFER_SIZE amount of bytes! This might not always + // be the case... + unqueuedBufferBytes += BUFFER_SIZE; + boolean active = fillBuffer(stream, buffer); if (!active && !stream.isEOF()) { @@ -679,6 +740,8 @@ public class ALAudioRenderer implements AudioRenderer, Runnable { break; } } + + stream.setUnqueuedBufferBytes(stream.getUnqueuedBufferBytes() + unqueuedBufferBytes); return success; } diff --git a/jme3-core/src/main/java/com/jme3/bounding/BoundingSphere.java b/jme3-core/src/main/java/com/jme3/bounding/BoundingSphere.java index 30751e078..d5dd56203 100644 --- a/jme3-core/src/main/java/com/jme3/bounding/BoundingSphere.java +++ b/jme3-core/src/main/java/com/jme3/bounding/BoundingSphere.java @@ -640,8 +640,7 @@ public class BoundingSphere extends BoundingVolume { return rVal; } - return new BoundingSphere(radius, - (center != null ? (Vector3f) center.clone() : null)); + return new BoundingSphere(radius, center.clone()); } /** diff --git a/jme3-core/src/main/java/com/jme3/collision/CollisionResult.java b/jme3-core/src/main/java/com/jme3/collision/CollisionResult.java index a777bc9b6..ae271c880 100644 --- a/jme3-core/src/main/java/com/jme3/collision/CollisionResult.java +++ b/jme3-core/src/main/java/com/jme3/collision/CollisionResult.java @@ -109,6 +109,11 @@ public class CollisionResult implements Comparable { return super.equals(obj); } + @Override + public int hashCode() { + return Float.floatToIntBits(distance); + } + public Vector3f getContactPoint() { return contactPoint; } diff --git a/jme3-core/src/main/java/com/jme3/export/JmeExporter.java b/jme3-core/src/main/java/com/jme3/export/JmeExporter.java index 0afd170ea..b8c3abc60 100644 --- a/jme3-core/src/main/java/com/jme3/export/JmeExporter.java +++ b/jme3-core/src/main/java/com/jme3/export/JmeExporter.java @@ -46,22 +46,18 @@ public interface JmeExporter { * * @param object The savable to export * @param f The output stream - * @return Always returns true. If an error occurs during export, - * an exception is thrown * @throws IOException If an io exception occurs during export */ - public boolean save(Savable object, OutputStream f) throws IOException; + public void save(Savable object, OutputStream f) throws IOException; /** * Export the {@link Savable} to a file. * * @param object The savable to export * @param f The file to export to - * @return Always returns true. If an error occurs during export, - * an exception is thrown * @throws IOException If an io exception occurs during export */ - public boolean save(Savable object, File f) throws IOException; + public void save(Savable object, File f) throws IOException; /** * Returns the {@link OutputCapsule} for the given savable object. diff --git a/jme3-core/src/main/java/com/jme3/input/DefaultJoystickAxis.java b/jme3-core/src/main/java/com/jme3/input/DefaultJoystickAxis.java index 954451145..8f32c2d6b 100644 --- a/jme3-core/src/main/java/com/jme3/input/DefaultJoystickAxis.java +++ b/jme3-core/src/main/java/com/jme3/input/DefaultJoystickAxis.java @@ -72,8 +72,10 @@ public class DefaultJoystickAxis implements JoystickAxis { * @param negativeMapping The mapping to receive events when the axis is positive */ public void assignAxis(String positiveMapping, String negativeMapping){ - inputManager.addMapping(positiveMapping, new JoyAxisTrigger(parent.getJoyId(), axisIndex, false)); - inputManager.addMapping(negativeMapping, new JoyAxisTrigger(parent.getJoyId(), axisIndex, true)); + if (axisIndex != -1) { + inputManager.addMapping(positiveMapping, new JoyAxisTrigger(parent.getJoyId(), axisIndex, false)); + inputManager.addMapping(negativeMapping, new JoyAxisTrigger(parent.getJoyId(), axisIndex, true)); + } } /** diff --git a/jme3-core/src/main/java/com/jme3/light/SpotLight.java b/jme3-core/src/main/java/com/jme3/light/SpotLight.java index 0499ce254..e6443df7c 100644 --- a/jme3-core/src/main/java/com/jme3/light/SpotLight.java +++ b/jme3-core/src/main/java/com/jme3/light/SpotLight.java @@ -56,14 +56,14 @@ import java.io.IOException; * the light intensity slowly decrease between the inner cone and the outer cone. * @author Nehon */ -public class SpotLight extends Light implements Savable { +public class SpotLight extends Light { protected Vector3f position = new Vector3f(); protected Vector3f direction = new Vector3f(0,-1,0); protected float spotInnerAngle = FastMath.QUARTER_PI / 8; protected float spotOuterAngle = FastMath.QUARTER_PI / 6; protected float spotRange = 100; - protected float invSpotRange = 1 / 100; + protected float invSpotRange = 1f / 100; protected float packedAngleCos=0; protected float outerAngleCosSqr, outerAngleSinSqr; diff --git a/jme3-core/src/main/java/com/jme3/material/MatParamTexture.java b/jme3-core/src/main/java/com/jme3/material/MatParamTexture.java index b24d27a95..a3db63a1c 100644 --- a/jme3-core/src/main/java/com/jme3/material/MatParamTexture.java +++ b/jme3-core/src/main/java/com/jme3/material/MatParamTexture.java @@ -47,12 +47,6 @@ public class MatParamTexture extends MatParam { private int unit; private ColorSpace colorSpace; - public MatParamTexture(VarType type, String name, Texture texture, int unit) { - super(type, name, texture); - this.texture = texture; - this.unit = unit; - } - public MatParamTexture(VarType type, String name, Texture texture, int unit, ColorSpace colorSpace) { super(type, name, texture); this.texture = texture; diff --git a/jme3-core/src/main/java/com/jme3/material/Material.java b/jme3-core/src/main/java/com/jme3/material/Material.java index 74fdbb006..44bfb73f5 100644 --- a/jme3-core/src/main/java/com/jme3/material/Material.java +++ b/jme3-core/src/main/java/com/jme3/material/Material.java @@ -69,7 +69,7 @@ import java.util.logging.Logger; * Setting the parameters can modify the behavior of a * shader. *

- * + * * @author Kirill Vainer */ public class Material implements CloneableSmartAsset, Cloneable, Savable { @@ -146,7 +146,7 @@ public class Material implements CloneableSmartAsset, Cloneable, Savable { public String getName() { return name; } - + /** * This method sets the name of the material. * The name is not the same as the asset name. @@ -222,11 +222,11 @@ public class Material implements CloneableSmartAsset, Cloneable, Savable { } /** - * Compares two materials and returns true if they are equal. + * Compares two materials and returns true if they are equal. * This methods compare definition, parameters, additional render states. - * Since materials are mutable objects, implementing equals() properly is not possible, + * Since materials are mutable objects, implementing equals() properly is not possible, * hence the name contentEquals(). - * + * * @param otherObj the material to compare to this material * @return true if the materials are equal. */ @@ -234,15 +234,15 @@ public class Material implements CloneableSmartAsset, Cloneable, Savable { if (!(otherObj instanceof Material)) { return false; } - + Material other = (Material) otherObj; - + // Early exit if the material are the same object if (this == other) { return true; } - // Check material definition + // Check material definition if (this.getMaterialDef() != other.getMaterialDef()) { return false; } @@ -251,12 +251,12 @@ public class Material implements CloneableSmartAsset, Cloneable, Savable { if (this.paramValues.size() != other.paramValues.size()) { return false; } - + // Checking technique if (this.technique != null || other.technique != null) { // Techniques are considered equal if their names are the same - // E.g. if user chose custom technique for one material but - // uses default technique for other material, the materials + // E.g. if user chose custom technique for one material but + // uses default technique for other material, the materials // are not equal. String thisDefName = this.technique != null ? this.technique.getDef().getName() : "Default"; String otherDefName = other.technique != null ? other.technique.getDef().getName() : "Default"; @@ -290,7 +290,7 @@ public class Material implements CloneableSmartAsset, Cloneable, Savable { return false; } } - + return true; } @@ -305,7 +305,7 @@ public class Material implements CloneableSmartAsset, Cloneable, Savable { hash = 29 * hash + (this.additionalState != null ? this.additionalState.contentHashCode() : 0); return hash; } - + /** * Returns the currently active technique. *

@@ -436,7 +436,7 @@ public class Material implements CloneableSmartAsset, Cloneable, Savable { public Collection getParams() { return paramValues.values(); } - + /** * Returns the ListMap of all parameters set on this material. * @@ -473,7 +473,7 @@ public class Material implements CloneableSmartAsset, Cloneable, Savable { */ public void setParam(String name, VarType type, Object value) { checkSetParam(type, name); - + if (type.isTextureType()) { setTextureParam(name, type, (Texture)value); } else { @@ -501,7 +501,7 @@ public class Material implements CloneableSmartAsset, Cloneable, Savable { if (matParam == null) { return; } - + paramValues.remove(name); if (matParam instanceof MatParamTexture) { int texUnit = ((MatParamTexture) matParam).getUnit(); @@ -556,7 +556,7 @@ public class Material implements CloneableSmartAsset, Cloneable, Savable { + "Linear using texture.getImage.setColorSpace().", new Object[]{value.getName(), value.getImage().getColorSpace().name(), name}); } - paramValues.put(name, new MatParamTexture(type, name, value, nextTexUnit++)); + paramValues.put(name, new MatParamTexture(type, name, value, nextTexUnit++, null)); } else { val.setTextureValue(value); } @@ -728,7 +728,7 @@ public class Material implements CloneableSmartAsset, Cloneable, Savable { renderer.renderMesh(mesh, lodLevel, 1, null); } } - + /** * Uploads the lights in the light list as two uniform arrays.

* *

@@ -747,30 +747,30 @@ public class Material implements CloneableSmartAsset, Cloneable, Savable { return 0; } - Uniform lightData = shader.getUniform("g_LightData"); - lightData.setVector4Length(numLights * 3);//8 lights * max 3 + Uniform lightData = shader.getUniform("g_LightData"); + lightData.setVector4Length(numLights * 3);//8 lights * max 3 Uniform ambientColor = shader.getUniform("g_AmbientLightColor"); - - if (startIndex != 0) { + + if (startIndex != 0) { // apply additive blending for 2nd and future passes rm.getRenderer().applyRenderState(additiveLight); - ambientColor.setValue(VarType.Vector4, ColorRGBA.Black); + ambientColor.setValue(VarType.Vector4, ColorRGBA.Black); }else{ ambientColor.setValue(VarType.Vector4, getAmbientColor(lightList,true)); } - + int lightDataIndex = 0; TempVars vars = TempVars.get(); Vector4f tmpVec = vars.vect4f1; int curIndex; int endIndex = numLights + startIndex; for (curIndex = startIndex; curIndex < endIndex && curIndex < lightList.size(); curIndex++) { - - - Light l = lightList.get(curIndex); + + + Light l = lightList.get(curIndex); if(l.getType() == Light.Type.Ambient){ - endIndex++; + endIndex++; continue; } ColorRGBA color = l.getColor(); @@ -781,14 +781,14 @@ public class Material implements CloneableSmartAsset, Cloneable, Savable { l.getType().getId(), lightDataIndex); lightDataIndex++; - + switch (l.getType()) { case Directional: DirectionalLight dl = (DirectionalLight) l; - Vector3f dir = dl.getDirection(); + Vector3f dir = dl.getDirection(); //Data directly sent in view space to avoid a matrix mult for each pixel tmpVec.set(dir.getX(), dir.getY(), dir.getZ(), 0.0f); - rm.getCurrentCamera().getViewMatrix().mult(tmpVec, tmpVec); + rm.getCurrentCamera().getViewMatrix().mult(tmpVec, tmpVec); // tmpVec.divideLocal(tmpVec.w); // tmpVec.normalizeLocal(); lightData.setVector4InArray(tmpVec.getX(), tmpVec.getY(), tmpVec.getZ(), -1, lightDataIndex); @@ -802,7 +802,7 @@ public class Material implements CloneableSmartAsset, Cloneable, Savable { Vector3f pos = pl.getPosition(); float invRadius = pl.getInvRadius(); tmpVec.set(pos.getX(), pos.getY(), pos.getZ(), 1.0f); - rm.getCurrentCamera().getViewMatrix().mult(tmpVec, tmpVec); + rm.getCurrentCamera().getViewMatrix().mult(tmpVec, tmpVec); //tmpVec.divideLocal(tmpVec.w); lightData.setVector4InArray(tmpVec.getX(), tmpVec.getY(), tmpVec.getZ(), invRadius, lightDataIndex); lightDataIndex++; @@ -810,37 +810,37 @@ public class Material implements CloneableSmartAsset, Cloneable, Savable { lightData.setVector4InArray(0,0,0,0, lightDataIndex); lightDataIndex++; break; - case Spot: + case Spot: SpotLight sl = (SpotLight) l; Vector3f pos2 = sl.getPosition(); Vector3f dir2 = sl.getDirection(); float invRange = sl.getInvSpotRange(); float spotAngleCos = sl.getPackedAngleCos(); tmpVec.set(pos2.getX(), pos2.getY(), pos2.getZ(), 1.0f); - rm.getCurrentCamera().getViewMatrix().mult(tmpVec, tmpVec); + rm.getCurrentCamera().getViewMatrix().mult(tmpVec, tmpVec); // tmpVec.divideLocal(tmpVec.w); lightData.setVector4InArray(tmpVec.getX(), tmpVec.getY(), tmpVec.getZ(), invRange, lightDataIndex); lightDataIndex++; - + //We transform the spot direction in view space here to save 5 varying later in the lighting shader //one vec4 less and a vec4 that becomes a vec3 //the downside is that spotAngleCos decoding happens now in the frag shader. tmpVec.set(dir2.getX(), dir2.getY(), dir2.getZ(), 0.0f); - rm.getCurrentCamera().getViewMatrix().mult(tmpVec, tmpVec); + rm.getCurrentCamera().getViewMatrix().mult(tmpVec, tmpVec); tmpVec.normalizeLocal(); lightData.setVector4InArray(tmpVec.getX(), tmpVec.getY(), tmpVec.getZ(), spotAngleCos, lightDataIndex); lightDataIndex++; - break; + break; default: throw new UnsupportedOperationException("Unknown type of light: " + l.getType()); } } - vars.release(); + vars.release(); //Padding of unsued buffer space while(lightDataIndex < numLights * 3) { lightData.setVector4InArray(0f, 0f, 0f, 0f, lightDataIndex); - lightDataIndex++; - } + lightDataIndex++; + } return curIndex; } @@ -887,10 +887,10 @@ public class Material implements CloneableSmartAsset, Cloneable, Savable { case Directional: DirectionalLight dl = (DirectionalLight) l; Vector3f dir = dl.getDirection(); - //FIXME : there is an inconstency here due to backward + //FIXME : there is an inconstency here due to backward //compatibility of the lighting shader. - //The directional light direction is passed in the - //LightPosition uniform. The lighting shader needs to be + //The directional light direction is passed in the + //LightPosition uniform. The lighting shader needs to be //reworked though in order to fix this. tmpLightPosition.set(dir.getX(), dir.getY(), dir.getZ(), -1); lightPos.setValue(VarType.Vector4, tmpLightPosition); @@ -987,11 +987,11 @@ public class Material implements CloneableSmartAsset, Cloneable, Savable { for (TechniqueDef techDef : techDefs) { if (rendererCaps.containsAll(techDef.getRequiredCaps())) { // use the first one that supports all the caps - tech = new Technique(this, techDef); + tech = new Technique(this, techDef); techniques.put(name, tech); if(tech.getDef().getLightMode() == renderManager.getPreferredLightMode() || tech.getDef().getLightMode() == LightMode.Disable){ - break; + break; } } lastTech = techDef; @@ -1078,7 +1078,7 @@ public class Material implements CloneableSmartAsset, Cloneable, Savable { Uniform u = uniforms.getValue(i); if (!u.isSetByCurrentMaterial()) { if (u.getName().charAt(0) != 'g') { - // Don't reset world globals! + // Don't reset world globals! // The benefits gained from this are very minimal // and cause lots of matrix -> FloatBuffer conversions. u.clearValue(); @@ -1093,21 +1093,21 @@ public class Material implements CloneableSmartAsset, Cloneable, Savable { *

* The material is rendered as follows: *

    - *
  • Determine which technique to use to render the material - - * either what the user selected via - * {@link #selectTechnique(java.lang.String, com.jme3.renderer.RenderManager) - * Material.selectTechnique()}, - * or the first default technique that the renderer supports + *
  • Determine which technique to use to render the material - + * either what the user selected via + * {@link #selectTechnique(java.lang.String, com.jme3.renderer.RenderManager) + * Material.selectTechnique()}, + * or the first default technique that the renderer supports * (based on the technique's {@link TechniqueDef#getRequiredCaps() requested rendering capabilities})
      - *
    • If the technique has been changed since the last frame, then it is notified via - * {@link Technique#makeCurrent(com.jme3.asset.AssetManager, boolean, java.util.EnumSet) - * Technique.makeCurrent()}. - * If the technique wants to use a shader to render the model, it should load it at this part - - * the shader should have all the proper defines as declared in the technique definition, - * including those that are bound to material parameters. - * The technique can re-use the shader from the last frame if + *
    • If the technique has been changed since the last frame, then it is notified via + * {@link Technique#makeCurrent(com.jme3.asset.AssetManager, boolean, java.util.EnumSet) + * Technique.makeCurrent()}. + * If the technique wants to use a shader to render the model, it should load it at this part - + * the shader should have all the proper defines as declared in the technique definition, + * including those that are bound to material parameters. + * The technique can re-use the shader from the last frame if * no changes to the defines occurred.
    - *
  • Set the {@link RenderState} to use for rendering. The render states are + *
  • Set the {@link RenderState} to use for rendering. The render states are * applied in this order (later RenderStates override earlier RenderStates):
      *
    1. {@link TechniqueDef#getRenderState() Technique Definition's RenderState} * - i.e. specific renderstate that is required for the shader.
    2. @@ -1120,22 +1120,22 @@ public class Material implements CloneableSmartAsset, Cloneable, Savable { *
    3. Uniforms bound to material parameters are updated based on the current material parameter values.
    4. *
    5. Uniforms bound to world parameters are updated from the RenderManager. * Internally {@link UniformBindingManager} is used for this task.
    6. - *
    7. Uniforms bound to textures will cause the texture to be uploaded as necessary. + *
    8. Uniforms bound to textures will cause the texture to be uploaded as necessary. * The uniform is set to the texture unit where the texture is bound.
- *
  • If the technique uses a shader, the model is then rendered according + *
  • If the technique uses a shader, the model is then rendered according * to the lighting mode specified on the technique definition.
      - *
    • {@link LightMode#SinglePass single pass light mode} fills the shader's light uniform arrays + *
    • {@link LightMode#SinglePass single pass light mode} fills the shader's light uniform arrays * with the first 4 lights and renders the model once.
    • - *
    • {@link LightMode#MultiPass multi pass light mode} light mode renders the model multiple times, - * for the first light it is rendered opaque, on subsequent lights it is + *
    • {@link LightMode#MultiPass multi pass light mode} light mode renders the model multiple times, + * for the first light it is rendered opaque, on subsequent lights it is * rendered with {@link BlendMode#AlphaAdditive alpha-additive} blending and depth writing disabled.
    • *
    - *
  • For techniques that do not use shaders, + *
  • For techniques that do not use shaders, * fixed function OpenGL is used to render the model (see {@link GL1Renderer} interface):
      *
    • OpenGL state ({@link FixedFuncBinding}) that is bound to material parameters is updated.
    • - *
    • The texture set on the material is uploaded and bound. + *
    • The texture set on the material is uploaded and bound. * Currently only 1 texture is supported for fixed function techniques.
    • - *
    • If the technique uses lighting, then OpenGL lighting state is updated + *
    • If the technique uses lighting, then OpenGL lighting state is updated * based on the light list on the geometry, otherwise OpenGL lighting is disabled.
    • *
    • The mesh is uploaded and rendered.
    • *
    @@ -1147,10 +1147,11 @@ public class Material implements CloneableSmartAsset, Cloneable, Savable { */ public void render(Geometry geom, LightList lights, RenderManager rm) { autoSelectTechnique(rm); + TechniqueDef techDef = technique.getDef(); - Renderer r = rm.getRenderer(); + if (techDef.isNoRender()) return; - TechniqueDef techDef = technique.getDef(); + Renderer r = rm.getRenderer(); if (rm.getForcedRenderState() != null) { r.applyRenderState(rm.getForcedRenderState()); @@ -1169,7 +1170,7 @@ public class Material implements CloneableSmartAsset, Cloneable, Savable { // reset unchanged uniform flag clearUniformsSetByCurrent(technique.getShader()); rm.updateUniformBindings(technique.getWorldBindUniforms()); - + // setup textures and uniforms for (int i = 0; i < paramValues.size(); i++) { @@ -1212,24 +1213,24 @@ public class Material implements CloneableSmartAsset, Cloneable, Savable { // any unset uniforms will be set to 0 resetUniformsNotSetByCurrent(shader); r.setShader(shader); - + renderMeshFromGeometry(r, geom); } /** * Called by {@link RenderManager} to render the geometry by * using this material. - * + * * Note that this version of the render method * does not perform light filtering. - * + * * @param geom The geometry to render * @param rm The render manager requesting the rendering */ public void render(Geometry geom, RenderManager rm) { render(geom, geom.getWorldLightList(), rm); } - + public void write(JmeExporter ex) throws IOException { OutputCapsule oc = ex.getCapsule(this); oc.write(def.getAssetName(), "material_def", null); @@ -1304,14 +1305,14 @@ public class Material implements CloneableSmartAsset, Cloneable, Savable { continue; } } - + if (im.getFormatVersion() == 0 && param.getName().startsWith("m_")) { // Ancient version of jME3 ... param.setName(param.getName().substring(2)); } - + if (def.getMaterialParam(param.getName()) == null) { - logger.log(Level.WARNING, "The material parameter is not defined: {0}. Ignoring..", + logger.log(Level.WARNING, "The material parameter is not defined: {0}. Ignoring..", param.getName()); } else { checkSetParam(param.getVarType(), param.getName()); diff --git a/jme3-core/src/main/java/com/jme3/material/TechniqueDef.java b/jme3-core/src/main/java/com/jme3/material/TechniqueDef.java index e618a046c..d7523956c 100644 --- a/jme3-core/src/main/java/com/jme3/material/TechniqueDef.java +++ b/jme3-core/src/main/java/com/jme3/material/TechniqueDef.java @@ -40,7 +40,7 @@ import java.util.*; /** * Describes a technique definition. - * + * * @author Kirill Vainer */ public class TechniqueDef implements Savable { @@ -49,7 +49,7 @@ public class TechniqueDef implements Savable { * Version #1: Separate shader language for each shader source. */ public static final int SAVABLE_VERSION = 1; - + /** * Describes light rendering mode. */ @@ -58,15 +58,15 @@ public class TechniqueDef implements Savable { * Disable light-based rendering */ Disable, - + /** - * Enable light rendering by using a single pass. + * Enable light rendering by using a single pass. *

    * An array of light positions and light colors is passed to the shader * containing the world light list for the geometry being rendered. */ SinglePass, - + /** * Enable light rendering by using multi-pass rendering. *

    @@ -77,7 +77,7 @@ public class TechniqueDef implements Savable { * passes have it set to black. */ MultiPass, - + /** * @deprecated OpenGL1 is not supported anymore */ @@ -94,18 +94,18 @@ public class TechniqueDef implements Savable { private EnumSet requiredCaps = EnumSet.noneOf(Caps.class); private String name; - private EnumMap shaderLanguage; - private EnumMap shaderName; - + private EnumMap shaderLanguages; + private EnumMap shaderNames; + private DefineList presetDefines; - private boolean usesShaders; private boolean usesNodes = false; private List shaderNodes; private ShaderGenerationInfo shaderGenerationInfo; + private boolean noRender = false; private RenderState renderState; private RenderState forcedRenderState; - + private LightMode lightMode = LightMode.Disable; private ShadowMode shadowMode = ShadowMode.Disable; @@ -116,7 +116,7 @@ public class TechniqueDef implements Savable { * Creates a new technique definition. *

    * Used internally by the J3M/J3MD loader. - * + * * @param name The name of the technique, should be set to null * for default techniques. */ @@ -129,14 +129,14 @@ public class TechniqueDef implements Savable { * Serialization only. Do not use. */ public TechniqueDef(){ - shaderLanguage=new EnumMap(Shader.ShaderType.class); - shaderName=new EnumMap(Shader.ShaderType.class); + shaderLanguages=new EnumMap(Shader.ShaderType.class); + shaderNames=new EnumMap(Shader.ShaderType.class); } /** * Returns the name of this technique as specified in the J3MD file. * Default techniques have the name "Default". - * + * * @return the name of this technique */ public String getName(){ @@ -154,9 +154,9 @@ public class TechniqueDef implements Savable { /** * Set the light mode - * + * * @param lightMode the light mode - * + * * @see LightMode */ public void setLightMode(LightMode lightMode) { @@ -173,9 +173,9 @@ public class TechniqueDef implements Savable { /** * Set the shadow mode. - * + * * @param shadowMode the shadow mode. - * + * * @see ShadowMode */ public void setShadowMode(ShadowMode shadowMode) { @@ -185,7 +185,7 @@ public class TechniqueDef implements Savable { /** * Returns the render state that this technique is using * @return the render state that this technique is using - * @see #setRenderState(com.jme3.material.RenderState) + * @see #setRenderState(com.jme3.material.RenderState) */ public RenderState getRenderState() { return renderState; @@ -193,28 +193,50 @@ public class TechniqueDef implements Savable { /** * Sets the render state that this technique is using. - * + * * @param renderState the render state that this technique is using. - * + * * @see RenderState */ public void setRenderState(RenderState renderState) { this.renderState = renderState; } + /** + * Sets if this technique should not be used to render. + * + * @param noRender not render or render ? + * + * @see NoRender + */ + public void setNoRender(boolean noRender) { + this.noRender = noRender; + } + + /** + * Returns true if this technique should not be used to render. + * (eg. to not render a material with default technique) + * + * @return true if this technique should not be rendered, false otherwise. + * + */ + public boolean isNoRender(){ + return noRender; + } + /** * @deprecated jME3 always requires shaders now */ @Deprecated public boolean isUsingShaders(){ - return usesShaders; + return true; } - + /** * Returns true if this technique uses Shader Nodes, false otherwise. - * + * * @return true if this technique uses Shader Nodes, false otherwise. - * + * */ public boolean isUsingShaderNodes(){ return usesNodes; @@ -223,7 +245,7 @@ public class TechniqueDef implements Savable { /** * Gets the {@link Caps renderer capabilities} that are required * by this technique. - * + * * @return the required renderer capabilities */ public EnumSet getRequiredCaps() { @@ -232,52 +254,60 @@ public class TechniqueDef implements Savable { /** * Sets the shaders that this technique definition will use. - * + * * @param vertexShader The name of the vertex shader * @param fragmentShader The name of the fragment shader * @param vertLanguage The vertex shader language * @param fragLanguage The fragment shader language */ public void setShaderFile(String vertexShader, String fragmentShader, String vertLanguage, String fragLanguage) { - this.shaderLanguage.put(Shader.ShaderType.Vertex, vertLanguage); - this.shaderName.put(Shader.ShaderType.Vertex, vertexShader); - this.shaderLanguage.put(Shader.ShaderType.Fragment, fragLanguage); - this.shaderName.put(Shader.ShaderType.Fragment, fragmentShader); + this.shaderLanguages.put(Shader.ShaderType.Vertex, vertLanguage); + this.shaderNames.put(Shader.ShaderType.Vertex, vertexShader); + this.shaderLanguages.put(Shader.ShaderType.Fragment, fragLanguage); + this.shaderNames.put(Shader.ShaderType.Fragment, fragmentShader); + + requiredCaps.clear(); Caps vertCap = Caps.valueOf(vertLanguage); requiredCaps.add(vertCap); Caps fragCap = Caps.valueOf(fragLanguage); requiredCaps.add(fragCap); - - usesShaders = true; } /** * Sets the shaders that this technique definition will use. * - * @param shaderName EnumMap containing all shader names for this stage - * @param shaderLanguage EnumMap containing all shader languages for this stage - */ - public void setShaderFile(EnumMap shaderName, EnumMap shaderLanguage) { - for (Shader.ShaderType shaderType : shaderName.keySet()) { - this.shaderLanguage.put(shaderType,shaderLanguage.get(shaderType)); - this.shaderName.put(shaderType,shaderName.get(shaderType)); - if(shaderType.equals(Shader.ShaderType.Geometry)){ + * @param shaderNames EnumMap containing all shader names for this stage + * @param shaderLanguages EnumMap containing all shader languages for this stage + */ + public void setShaderFile(EnumMap shaderNames, EnumMap shaderLanguages) { + requiredCaps.clear(); + + for (Shader.ShaderType shaderType : shaderNames.keySet()) { + String language = shaderLanguages.get(shaderType); + String shaderFile = shaderNames.get(shaderType); + + this.shaderLanguages.put(shaderType, language); + this.shaderNames.put(shaderType, shaderFile); + + Caps vertCap = Caps.valueOf(language); + requiredCaps.add(vertCap); + + if (shaderType.equals(Shader.ShaderType.Geometry)) { requiredCaps.add(Caps.GeometryShader); - }else if(shaderType.equals(Shader.ShaderType.TessellationControl)){ + } else if (shaderType.equals(Shader.ShaderType.TessellationControl)) { requiredCaps.add(Caps.TesselationShader); } } - usesShaders=true; } /** * Returns the define name which the given material parameter influences. - * + * * @param paramName The parameter name to look up * @return The define name - * - * @see #addShaderParamDefine(java.lang.String, java.lang.String) + * + * @see #addShaderParamDefine(java.lang.String, java.lang.String) */ public String getShaderParamDefine(String paramName){ if (defineParams == null) { @@ -290,11 +320,11 @@ public class TechniqueDef implements Savable { * Adds a define linked to a material parameter. *

    * Any time the material parameter on the parent material is altered, - * the appropriate define on the technique will be modified as well. - * See the method + * the appropriate define on the technique will be modified as well. + * See the method * {@link DefineList#set(java.lang.String, com.jme3.shader.VarType, java.lang.Object) } * on the exact details of how the material parameter changes the define. - * + * * @param paramName The name of the material parameter to link to. * @param defineName The name of the define parameter, e.g. USE_LIGHTING */ @@ -307,26 +337,26 @@ public class TechniqueDef implements Savable { /** * Returns the {@link DefineList} for the preset defines. - * + * * @return the {@link DefineList} for the preset defines. - * - * @see #addShaderPresetDefine(java.lang.String, com.jme3.shader.VarType, java.lang.Object) + * + * @see #addShaderPresetDefine(java.lang.String, com.jme3.shader.VarType, java.lang.Object) */ public DefineList getShaderPresetDefines() { return presetDefines; } - + /** - * Adds a preset define. + * Adds a preset define. *

    * Preset defines do not depend upon any parameters to be activated, * they are always passed to the shader as long as this technique is used. - * + * * @param defineName The name of the define parameter, e.g. USE_LIGHTING - * @param type The type of the define. See + * @param type The type of the define. See * {@link DefineList#set(java.lang.String, com.jme3.shader.VarType, java.lang.Object) } * to see why it matters. - * + * * @param value The value of the define */ public void addShaderPresetDefine(String defineName, VarType type, Object value){ @@ -339,62 +369,54 @@ public class TechniqueDef implements Savable { /** * Returns the name of the fragment shader used by the technique, or null * if no fragment shader is specified. - * + * * @return the name of the fragment shader to be used. */ public String getFragmentShaderName() { - return shaderName.get(Shader.ShaderType.Fragment); + return shaderNames.get(Shader.ShaderType.Fragment); } - + /** * Returns the name of the vertex shader used by the technique, or null * if no vertex shader is specified. - * + * * @return the name of the vertex shader to be used. */ public String getVertexShaderName() { - return shaderName.get(Shader.ShaderType.Vertex); - } - - /** - * @deprecated Use {@link #getVertexShaderLanguage() } instead. - */ - @Deprecated - public String getShaderLanguage() { - return shaderLanguage.get(Shader.ShaderType.Vertex); + return shaderNames.get(Shader.ShaderType.Vertex); } /** * Returns the language of the fragment shader used in this technique. */ public String getFragmentShaderLanguage() { - return shaderLanguage.get(Shader.ShaderType.Fragment); + return shaderLanguages.get(Shader.ShaderType.Fragment); } - + /** * Returns the language of the vertex shader used in this technique. */ public String getVertexShaderLanguage() { - return shaderLanguage.get(Shader.ShaderType.Vertex); + return shaderLanguages.get(Shader.ShaderType.Vertex); } /**Returns the language for each shader program * @param shaderType */ public String getShaderProgramLanguage(Shader.ShaderType shaderType){ - return shaderLanguage.get(shaderType); + return shaderLanguages.get(shaderType); } /**Returns the name for each shader program * @param shaderType */ public String getShaderProgramName(Shader.ShaderType shaderType){ - return shaderName.get(shaderType); + return shaderNames.get(shaderType); } - + /** * Adds a new world parameter by the given name. - * + * * @param name The world parameter to add. * @return True if the world parameter name was found and added * to the list of world parameters, false otherwise. @@ -403,7 +425,7 @@ public class TechniqueDef implements Savable { if (worldBinds == null){ worldBinds = new ArrayList(); } - + try { worldBinds.add( UniformBinding.valueOf(name) ); return true; @@ -419,11 +441,11 @@ public class TechniqueDef implements Savable { public void setForcedRenderState(RenderState forcedRenderState) { this.forcedRenderState = forcedRenderState; } - + /** * Returns a list of world parameters that are used by this * technique definition. - * + * * @return The list of world parameters */ public List getWorldBindings() { @@ -434,26 +456,26 @@ public class TechniqueDef implements Savable { OutputCapsule oc = ex.getCapsule(this); oc.write(name, "name", null); - oc.write(shaderName.get(Shader.ShaderType.Vertex), "vertName", null); - oc.write(shaderName.get(Shader.ShaderType.Fragment), "fragName", null); - oc.write(shaderName.get(Shader.ShaderType.Geometry), "geomName", null); - oc.write(shaderName.get(Shader.ShaderType.TessellationControl), "tsctrlName", null); - oc.write(shaderName.get(Shader.ShaderType.TessellationEvaluation), "tsevalName", null); - oc.write(shaderLanguage.get(Shader.ShaderType.Vertex), "vertLanguage", null); - oc.write(shaderLanguage.get(Shader.ShaderType.Fragment), "fragLanguage", null); - oc.write(shaderLanguage.get(Shader.ShaderType.Geometry), "geomLanguage", null); - oc.write(shaderLanguage.get(Shader.ShaderType.TessellationControl), "tsctrlLanguage", null); - oc.write(shaderLanguage.get(Shader.ShaderType.TessellationEvaluation), "tsevalLanguage", null); + oc.write(shaderNames.get(Shader.ShaderType.Vertex), "vertName", null); + oc.write(shaderNames.get(Shader.ShaderType.Fragment), "fragName", null); + oc.write(shaderNames.get(Shader.ShaderType.Geometry), "geomName", null); + oc.write(shaderNames.get(Shader.ShaderType.TessellationControl), "tsctrlName", null); + oc.write(shaderNames.get(Shader.ShaderType.TessellationEvaluation), "tsevalName", null); + oc.write(shaderLanguages.get(Shader.ShaderType.Vertex), "vertLanguage", null); + oc.write(shaderLanguages.get(Shader.ShaderType.Fragment), "fragLanguage", null); + oc.write(shaderLanguages.get(Shader.ShaderType.Geometry), "geomLanguage", null); + oc.write(shaderLanguages.get(Shader.ShaderType.TessellationControl), "tsctrlLanguage", null); + oc.write(shaderLanguages.get(Shader.ShaderType.TessellationEvaluation), "tsevalLanguage", null); oc.write(presetDefines, "presetDefines", null); oc.write(lightMode, "lightMode", LightMode.Disable); oc.write(shadowMode, "shadowMode", ShadowMode.Disable); oc.write(renderState, "renderState", null); - oc.write(usesShaders, "usesShaders", false); + oc.write(noRender, "noRender", false); oc.write(usesNodes, "usesNodes", false); oc.writeSavableArrayList((ArrayList)shaderNodes,"shaderNodes", null); oc.write(shaderGenerationInfo, "shaderGenerationInfo", null); - + // TODO: Finish this when Map export is available // oc.write(defineParams, "defineParams", null); // TODO: Finish this when List export is available @@ -463,30 +485,30 @@ public class TechniqueDef implements Savable { public void read(JmeImporter im) throws IOException{ InputCapsule ic = im.getCapsule(this); name = ic.readString("name", null); - shaderName.put(Shader.ShaderType.Vertex,ic.readString("vertName", null)); - shaderName.put(Shader.ShaderType.Fragment,ic.readString("fragName", null)); - shaderName.put(Shader.ShaderType.Geometry,ic.readString("geomName", null)); - shaderName.put(Shader.ShaderType.TessellationControl,ic.readString("tsctrlName", null)); - shaderName.put(Shader.ShaderType.TessellationEvaluation,ic.readString("tsevalName", null)); + shaderNames.put(Shader.ShaderType.Vertex,ic.readString("vertName", null)); + shaderNames.put(Shader.ShaderType.Fragment,ic.readString("fragName", null)); + shaderNames.put(Shader.ShaderType.Geometry,ic.readString("geomName", null)); + shaderNames.put(Shader.ShaderType.TessellationControl,ic.readString("tsctrlName", null)); + shaderNames.put(Shader.ShaderType.TessellationEvaluation,ic.readString("tsevalName", null)); presetDefines = (DefineList) ic.readSavable("presetDefines", null); lightMode = ic.readEnum("lightMode", LightMode.class, LightMode.Disable); shadowMode = ic.readEnum("shadowMode", ShadowMode.class, ShadowMode.Disable); renderState = (RenderState) ic.readSavable("renderState", null); - usesShaders = ic.readBoolean("usesShaders", false); - + noRender = ic.readBoolean("noRender", false); + if (ic.getSavableVersion(TechniqueDef.class) == 0) { // Old version - shaderLanguage.put(Shader.ShaderType.Vertex,ic.readString("shaderLang", null)); - shaderLanguage.put(Shader.ShaderType.Fragment,shaderLanguage.get(Shader.ShaderType.Vertex)); + shaderLanguages.put(Shader.ShaderType.Vertex,ic.readString("shaderLang", null)); + shaderLanguages.put(Shader.ShaderType.Fragment,shaderLanguages.get(Shader.ShaderType.Vertex)); } else { // New version - shaderLanguage.put(Shader.ShaderType.Vertex,ic.readString("vertLanguage", null)); - shaderLanguage.put(Shader.ShaderType.Fragment,ic.readString("fragLanguage", null)); - shaderLanguage.put(Shader.ShaderType.Geometry,ic.readString("geomLanguage", null)); - shaderLanguage.put(Shader.ShaderType.TessellationControl,ic.readString("tsctrlLanguage", null)); - shaderLanguage.put(Shader.ShaderType.TessellationEvaluation,ic.readString("tsevalLanguage", null)); + shaderLanguages.put(Shader.ShaderType.Vertex,ic.readString("vertLanguage", null)); + shaderLanguages.put(Shader.ShaderType.Fragment,ic.readString("fragLanguage", null)); + shaderLanguages.put(Shader.ShaderType.Geometry,ic.readString("geomLanguage", null)); + shaderLanguages.put(Shader.ShaderType.TessellationControl,ic.readString("tsctrlLanguage", null)); + shaderLanguages.put(Shader.ShaderType.TessellationEvaluation,ic.readString("tsevalLanguage", null)); } - + usesNodes = ic.readBoolean("usesNodes", false); shaderNodes = ic.readSavableArrayList("shaderNodes", null); shaderGenerationInfo = (ShaderGenerationInfo) ic.readSavable("shaderGenerationInfo", null); @@ -499,7 +521,6 @@ public class TechniqueDef implements Savable { public void setShaderNodes(List shaderNodes) { this.shaderNodes = shaderNodes; usesNodes = true; - usesShaders = true; } /** @@ -507,7 +528,7 @@ public class TechniqueDef implements Savable { * @return */ public EnumMap getShaderProgramNames() { - return shaderName; + return shaderNames; } /** @@ -515,7 +536,7 @@ public class TechniqueDef implements Savable { * @return */ public EnumMap getShaderProgramLanguages() { - return shaderLanguage; + return shaderLanguages; } public ShaderGenerationInfo getShaderGenerationInfo() { @@ -529,6 +550,6 @@ public class TechniqueDef implements Savable { //todo: make toString return something usefull @Override public String toString() { - return "TechniqueDef{" + "requiredCaps=" + requiredCaps + ", name=" + name /*+ ", vertName=" + vertName + ", fragName=" + fragName + ", vertLanguage=" + vertLanguage + ", fragLanguage=" + fragLanguage */+ ", presetDefines=" + presetDefines + ", usesShaders=" + usesShaders + ", usesNodes=" + usesNodes + ", shaderNodes=" + shaderNodes + ", shaderGenerationInfo=" + shaderGenerationInfo + ", renderState=" + renderState + ", forcedRenderState=" + forcedRenderState + ", lightMode=" + lightMode + ", shadowMode=" + shadowMode + ", defineParams=" + defineParams + ", worldBinds=" + worldBinds + '}'; - } + return "TechniqueDef{" + "requiredCaps=" + requiredCaps + ", name=" + name /*+ ", vertName=" + vertName + ", fragName=" + fragName + ", vertLanguage=" + vertLanguage + ", fragLanguage=" + fragLanguage */+ ", presetDefines=" + presetDefines + ", usesNodes=" + usesNodes + ", shaderNodes=" + shaderNodes + ", shaderGenerationInfo=" + shaderGenerationInfo + ", renderState=" + renderState + ", forcedRenderState=" + forcedRenderState + ", lightMode=" + lightMode + ", shadowMode=" + shadowMode + ", defineParams=" + defineParams + ", worldBinds=" + worldBinds + ", noRender=" + noRender + '}'; + } } diff --git a/jme3-core/src/main/java/com/jme3/math/ColorRGBA.java b/jme3-core/src/main/java/com/jme3/math/ColorRGBA.java index 89f82ebbd..89df1bb2b 100644 --- a/jme3-core/src/main/java/com/jme3/math/ColorRGBA.java +++ b/jme3-core/src/main/java/com/jme3/math/ColorRGBA.java @@ -607,28 +607,28 @@ public final class ColorRGBA implements Savable, Cloneable, java.io.Serializable } /** - * Get the color in sRGB color space as a Vector4f + * Get the color in sRGB color space as a ColorRGBA. * * Note that linear values stored in the ColorRGBA will be gamma corrected - * and returned as a Vector4f - * the x atribute will be fed with the r channel in sRGB space - * the y atribute will be fed with the g channel in sRGB space - * the z atribute will be fed with the b channel in sRGB space - * the w atribute will be fed with the a channel + * and returned as a ColorRGBA. * - * Note that no correction will be performed on the alpha channel as it's - * conventionnally doesn't represent a color itself + * The x attribute will be fed with the r channel in sRGB space. + * The y attribute will be fed with the g channel in sRGB space. + * The z attribute will be fed with the b channel in sRGB space. + * The w attribute will be fed with the a channel. * - * @return the color in sRGB color space as a Vector4f - */ - public Vector4f getAsSrgb(){ - Vector4f srgb = new Vector4f(); - float invGama = 1f/GAMMA; - srgb.x = (float)Math.pow(r, invGama); - srgb.y = (float)Math.pow(g, invGama); - srgb.z = (float)Math.pow(b, invGama); - srgb.w = a; - + * Note that no correction will be performed on the alpha channel as it + * conventionally doesn't represent a color itself. + * + * @return the color in sRGB color space as a ColorRGBA. + */ + public ColorRGBA getAsSrgb() { + ColorRGBA srgb = new ColorRGBA(); + float invGama = 1f / GAMMA; + srgb.r = (float) Math.pow(r, invGama); + srgb.g = (float) Math.pow(g, invGama); + srgb.b = (float) Math.pow(b, invGama); + srgb.a = a; return srgb; } diff --git a/jme3-core/src/main/java/com/jme3/math/FastMath.java b/jme3-core/src/main/java/com/jme3/math/FastMath.java index 5e230dabb..d9d944057 100644 --- a/jme3-core/src/main/java/com/jme3/math/FastMath.java +++ b/jme3-core/src/main/java/com/jme3/math/FastMath.java @@ -902,6 +902,25 @@ final public class FastMath { return clamp(input, 0f, 1f); } + /** + * Determine if two floats are approximately equal. + * This takes into account the magnitude of the floats, since + * large numbers will have larger differences be close to each other. + * + * Should return true for a=100000, b=100001, but false for a=10000, b=10001. + * + * @param a The first float to compare + * @param b The second float to compare + * @return True if a and b are approximately equal, false otherwise. + */ + public static boolean approximateEquals(float a, float b) { + if (a == b) { + return true; + } else { + return (abs(a - b) / Math.max(abs(a), abs(b))) <= 0.00001f; + } + } + /** * Converts a single precision (32 bit) floating point value * into half precision (16 bit). diff --git a/jme3-core/src/main/java/com/jme3/math/Transform.java b/jme3-core/src/main/java/com/jme3/math/Transform.java index 79992ed2b..ac7a324d0 100644 --- a/jme3-core/src/main/java/com/jme3/math/Transform.java +++ b/jme3-core/src/main/java/com/jme3/math/Transform.java @@ -259,6 +259,26 @@ public final class Transform implements Savable, Cloneable, java.io.Serializable return store; } + public Matrix4f toTransformMatrix() { + Matrix4f trans = new Matrix4f(); + trans.setTranslation(translation); + trans.setRotationQuaternion(rot); + trans.setScale(scale); + return trans; + } + + public void fromTransformMatrix(Matrix4f mat) { + translation.set(mat.toTranslationVector()); + rot.set(mat.toRotationQuat()); + scale.set(mat.toScaleVector()); + } + + public Transform invert() { + Transform t = new Transform(); + t.fromTransformMatrix(toTransformMatrix().invertLocal()); + return t; + } + /** * Loads the identity. Equal to translation=0,0,0 scale=1,1,1 rot=0,0,0,1. */ diff --git a/jme3-core/src/main/java/com/jme3/post/Filter.java b/jme3-core/src/main/java/com/jme3/post/Filter.java index 320ff734d..a6e2e3c01 100644 --- a/jme3-core/src/main/java/com/jme3/post/Filter.java +++ b/jme3-core/src/main/java/com/jme3/post/Filter.java @@ -201,7 +201,7 @@ public abstract class Filter implements Savable { /** * returns the default pass texture format - * default is {@link Format#RGB10_A2} + * default is {@link Format#RGB111110F} * * @return */ diff --git a/jme3-core/src/main/java/com/jme3/renderer/Caps.java b/jme3-core/src/main/java/com/jme3/renderer/Caps.java index f0d42c8f2..9387b687e 100644 --- a/jme3-core/src/main/java/com/jme3/renderer/Caps.java +++ b/jme3-core/src/main/java/com/jme3/renderer/Caps.java @@ -337,7 +337,19 @@ public enum Caps { *

    * Improves the quality of environment mapping. */ - SeamlessCubemap; + SeamlessCubemap, + + /** + * Running with OpenGL 3.2+ core profile. + * + * Compatibility features will not be available. + */ + CoreProfile, + + /** + * GPU can provide and accept binary shaders. + */ + BinaryShader; /** * Returns true if given the renderer capabilities, the texture diff --git a/jme3-core/src/main/java/com/jme3/renderer/Limits.java b/jme3-core/src/main/java/com/jme3/renderer/Limits.java index b10c539b8..86cddb178 100644 --- a/jme3-core/src/main/java/com/jme3/renderer/Limits.java +++ b/jme3-core/src/main/java/com/jme3/renderer/Limits.java @@ -75,4 +75,6 @@ public enum Limits { ColorTextureSamples, DepthTextureSamples, + + VertexUniformVectors, } diff --git a/jme3-core/src/main/java/com/jme3/renderer/opengl/GL.java b/jme3-core/src/main/java/com/jme3/renderer/opengl/GL.java index 9c73838e2..4a9380cf4 100644 --- a/jme3-core/src/main/java/com/jme3/renderer/opengl/GL.java +++ b/jme3-core/src/main/java/com/jme3/renderer/opengl/GL.java @@ -32,7 +32,6 @@ package com.jme3.renderer.opengl; import java.nio.ByteBuffer; -import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; @@ -75,6 +74,7 @@ public interface GL { public static final int GL_FRONT_AND_BACK = 0x408; public static final int GL_GEQUAL = 0x206; public static final int GL_GREATER = 0x204; + public static final int GL_GREEN = 0x1904; public static final int GL_INCR = 0x1E02; public static final int GL_INCR_WRAP = 0x8507; public static final int GL_INFO_LOG_LENGTH = 0x8B84; @@ -100,6 +100,8 @@ public interface GL { public static final int GL_MAX_TEXTURE_SIZE = 0xD33; public static final int GL_MAX_VERTEX_ATTRIBS = 0x8869; public static final int GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8B4C; + public static final int GL_MAX_VERTEX_UNIFORM_COMPONENTS = 0x8B4A; + public static final int GL_MAX_VERTEX_UNIFORM_VECTORS = 0x8DFB; public static final int GL_MIRRORED_REPEAT = 0x8370; public static final int GL_NEAREST = 0x2600; public static final int GL_NEAREST_MIPMAP_LINEAR = 0x2702; @@ -115,6 +117,7 @@ public interface GL { public static final int GL_OUT_OF_MEMORY = 0x505; public static final int GL_POINTS = 0x0; public static final int GL_POLYGON_OFFSET_FILL = 0x8037; + public static final int GL_RED = 0x1903; public static final int GL_RENDERER = 0x1F01; public static final int GL_REPEAT = 0x2901; public static final int GL_REPLACE = 0x1E01; @@ -178,6 +181,8 @@ public interface GL { public static final int GL_VERTEX_SHADER = 0x8B31; public static final int GL_ZERO = 0x0; + public void resetStats(); + public void glActiveTexture(int texture); public void glAttachShader(int program, int shader); public void glBindBuffer(int target, int buffer); diff --git a/jme3-core/src/main/java/com/jme3/renderer/opengl/GL3.java b/jme3-core/src/main/java/com/jme3/renderer/opengl/GL3.java index 50eb065ab..2a7c38bb9 100644 --- a/jme3-core/src/main/java/com/jme3/renderer/opengl/GL3.java +++ b/jme3-core/src/main/java/com/jme3/renderer/opengl/GL3.java @@ -34,15 +34,30 @@ package com.jme3.renderer.opengl; import java.nio.IntBuffer; /** - * GL functions only available on vanilla desktop OpenGL 3.0. - * + * GL functions only available on vanilla desktop OpenGL 3.0+. + * * @author Kirill Vainer */ public interface GL3 extends GL2 { - + public static final int GL_DEPTH_STENCIL_ATTACHMENT = 0x821A; - public static final int GL_GEOMETRY_SHADER=0x8DD9; + public static final int GL_GEOMETRY_SHADER = 0x8DD9; + public static final int GL_NUM_EXTENSIONS = 0x821D; + public static final int GL_R8 = 0x8229; + public static final int GL_R16F = 0x822D; + public static final int GL_R32F = 0x822E; + public static final int GL_RG16F = 0x822F; + public static final int GL_RG32F = 0x8230; + public static final int GL_RG = 0x8227; + public static final int GL_RG8 = 0x822B; + public static final int GL_TEXTURE_SWIZZLE_A = 0x8E45; + public static final int GL_TEXTURE_SWIZZLE_B = 0x8E44; + public static final int GL_TEXTURE_SWIZZLE_G = 0x8E43; + public static final int GL_TEXTURE_SWIZZLE_R = 0x8E42; + public void glBindFragDataLocation(int param1, int param2, String param3); /// GL3+ public void glBindVertexArray(int param1); /// GL3+ + public void glDeleteVertexArrays(IntBuffer arrays); /// GL3+ public void glGenVertexArrays(IntBuffer param1); /// GL3+ + public String glGetString(int param1, int param2); /// GL3+ } diff --git a/jme3-core/src/main/java/com/jme3/renderer/opengl/GL4.java b/jme3-core/src/main/java/com/jme3/renderer/opengl/GL4.java index ce982eebf..058bc00ec 100644 --- a/jme3-core/src/main/java/com/jme3/renderer/opengl/GL4.java +++ b/jme3-core/src/main/java/com/jme3/renderer/opengl/GL4.java @@ -34,7 +34,7 @@ package com.jme3.renderer.opengl; import java.nio.IntBuffer; /** - * GL functions only available on vanilla desktop OpenGL 3.0. + * GL functions only available on vanilla desktop OpenGL 4.0. * * @author Kirill Vainer */ diff --git a/jme3-core/src/main/java/com/jme3/renderer/opengl/GLDebugDesktop.java b/jme3-core/src/main/java/com/jme3/renderer/opengl/GLDebugDesktop.java index e13402bd5..a0511f6ad 100644 --- a/jme3-core/src/main/java/com/jme3/renderer/opengl/GLDebugDesktop.java +++ b/jme3-core/src/main/java/com/jme3/renderer/opengl/GLDebugDesktop.java @@ -3,15 +3,17 @@ package com.jme3.renderer.opengl; import java.nio.ByteBuffer; import java.nio.IntBuffer; -public class GLDebugDesktop extends GLDebugES implements GL2, GL3 { +public class GLDebugDesktop extends GLDebugES implements GL2, GL3, GL4 { private final GL2 gl2; private final GL3 gl3; + private final GL4 gl4; - public GLDebugDesktop(GL gl, GLFbo glfbo) { - super(gl, glfbo); + public GLDebugDesktop(GL gl, GLExt glext, GLFbo glfbo) { + super(gl, glext, glfbo); this.gl2 = gl instanceof GL2 ? (GL2) gl : null; this.gl3 = gl instanceof GL3 ? (GL3) gl : null; + this.gl4 = gl instanceof GL4 ? (GL4) gl : null; } public void glAlphaFunc(int func, float ref) { @@ -73,5 +75,23 @@ public class GLDebugDesktop extends GLDebugES implements GL2, GL3 { gl3.glGenVertexArrays(param1); checkError(); } + + @Override + public String glGetString(int param1, int param2) { + String result = gl3.glGetString(param1, param2); + checkError(); + return result; + } + + @Override + public void glDeleteVertexArrays(IntBuffer arrays) { + gl3.glDeleteVertexArrays(arrays); + checkError(); + } + @Override + public void glPatchParameter(int count) { + gl4.glPatchParameter(count); + checkError(); + } } diff --git a/jme3-core/src/main/java/com/jme3/renderer/opengl/GLDebugES.java b/jme3-core/src/main/java/com/jme3/renderer/opengl/GLDebugES.java index 259c56406..2348bd3cd 100644 --- a/jme3-core/src/main/java/com/jme3/renderer/opengl/GLDebugES.java +++ b/jme3-core/src/main/java/com/jme3/renderer/opengl/GLDebugES.java @@ -10,14 +10,16 @@ public class GLDebugES extends GLDebug implements GL, GLFbo, GLExt { private final GLFbo glfbo; private final GLExt glext; - public GLDebugES(GL gl, GLFbo glfbo) { + public GLDebugES(GL gl, GLExt glext, GLFbo glfbo) { this.gl = gl; -// this.gl2 = gl instanceof GL2 ? (GL2) gl : null; -// this.gl3 = gl instanceof GL3 ? (GL3) gl : null; + this.glext = glext; this.glfbo = glfbo; - this.glext = glfbo instanceof GLExt ? (GLExt) glfbo : null; } + public void resetStats() { + gl.resetStats(); + } + public void glActiveTexture(int texture) { gl.glActiveTexture(texture); checkError(); @@ -478,7 +480,7 @@ public class GLDebugES extends GLDebug implements GL, GLFbo, GLExt { } public void glBlitFramebufferEXT(int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, int mask, int filter) { - glext.glBlitFramebufferEXT(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); + glfbo.glBlitFramebufferEXT(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); checkError(); } @@ -525,7 +527,7 @@ public class GLDebugES extends GLDebug implements GL, GLFbo, GLExt { } public void glRenderbufferStorageMultisampleEXT(int target, int samples, int internalformat, int width, int height) { - glext.glRenderbufferStorageMultisampleEXT(target, samples, internalformat, width, height); + glfbo.glRenderbufferStorageMultisampleEXT(target, samples, internalformat, width, height); checkError(); } diff --git a/jme3-core/src/main/java/com/jme3/renderer/opengl/GLExt.java b/jme3-core/src/main/java/com/jme3/renderer/opengl/GLExt.java index b0e0b5f78..27f0eb8bd 100644 --- a/jme3-core/src/main/java/com/jme3/renderer/opengl/GLExt.java +++ b/jme3-core/src/main/java/com/jme3/renderer/opengl/GLExt.java @@ -41,7 +41,7 @@ import java.nio.IntBuffer; * * @author Kirill Vainer */ -public interface GLExt extends GLFbo { +public interface GLExt { public static final int GL_ALREADY_SIGNALED = 0x911A; public static final int GL_COMPRESSED_RGB8_ETC2 = 0x9274; @@ -100,7 +100,6 @@ public interface GLExt extends GLFbo { public static final int GL_UNSIGNED_INT_5_9_9_9_REV_EXT = 0x8C3E; public static final int GL_WAIT_FAILED = 0x911D; - public void glBlitFramebufferEXT(int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, int mask, int filter); public void glBufferData(int target, IntBuffer data, int usage); public void glBufferSubData(int target, long offset, IntBuffer data); public int glClientWaitSync(Object sync, int flags, long timeout); @@ -110,7 +109,6 @@ public interface GLExt extends GLFbo { public void glDrawElementsInstancedARB(int mode, int indices_count, int type, long indices_buffer_offset, int primcount); public Object glFenceSync(int condition, int flags); public void glGetMultisample(int pname, int index, FloatBuffer val); - public void glRenderbufferStorageMultisampleEXT(int target, int samples, int internalformat, int width, int height); public void glTexImage2DMultisample(int target, int samples, int internalformat, int width, int height, boolean fixedsamplelocations); public void glVertexAttribDivisorARB(int index, int divisor); } diff --git a/jme3-core/src/main/java/com/jme3/renderer/opengl/GLFbo.java b/jme3-core/src/main/java/com/jme3/renderer/opengl/GLFbo.java index 252619db8..737019ce2 100644 --- a/jme3-core/src/main/java/com/jme3/renderer/opengl/GLFbo.java +++ b/jme3-core/src/main/java/com/jme3/renderer/opengl/GLFbo.java @@ -83,6 +83,7 @@ public interface GLFbo { public void glBindFramebufferEXT(int param1, int param2); public void glBindRenderbufferEXT(int param1, int param2); + public void glBlitFramebufferEXT(int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, int mask, int filter); public int glCheckFramebufferStatusEXT(int param1); public void glDeleteFramebuffersEXT(IntBuffer param1); public void glDeleteRenderbuffersEXT(IntBuffer param1); @@ -92,5 +93,5 @@ public interface GLFbo { public void glGenRenderbuffersEXT(IntBuffer param1); public void glGenerateMipmapEXT(int param1); public void glRenderbufferStorageEXT(int param1, int param2, int param3, int param4); - + public void glRenderbufferStorageMultisampleEXT(int target, int samples, int internalformat, int width, int height); } diff --git a/jme3-core/src/main/java/com/jme3/renderer/opengl/GLImageFormat.java b/jme3-core/src/main/java/com/jme3/renderer/opengl/GLImageFormat.java index 71d95f59b..8e65fbdef 100644 --- a/jme3-core/src/main/java/com/jme3/renderer/opengl/GLImageFormat.java +++ b/jme3-core/src/main/java/com/jme3/renderer/opengl/GLImageFormat.java @@ -42,6 +42,7 @@ public final class GLImageFormat { public final int format; public final int dataType; public final boolean compressed; + public final boolean swizzleRequired; /** * Constructor for formats. @@ -55,6 +56,7 @@ public final class GLImageFormat { this.format = format; this.dataType = dataType; this.compressed = false; + this.swizzleRequired = false; } /** @@ -63,11 +65,30 @@ public final class GLImageFormat { * @param internalFormat OpenGL internal format * @param format OpenGL format * @param dataType OpenGL datatype + * @param compressed Format is compressed */ public GLImageFormat(int internalFormat, int format, int dataType, boolean compressed) { this.internalFormat = internalFormat; this.format = format; this.dataType = dataType; this.compressed = compressed; + this.swizzleRequired = false; + } + + /** + * Constructor for formats. + * + * @param internalFormat OpenGL internal format + * @param format OpenGL format + * @param dataType OpenGL datatype + * @param compressed Format is compressed + * @param swizzleRequired Need to use texture swizzle to upload texture + */ + public GLImageFormat(int internalFormat, int format, int dataType, boolean compressed, boolean swizzleRequired) { + this.internalFormat = internalFormat; + this.format = format; + this.dataType = dataType; + this.compressed = compressed; + this.swizzleRequired = swizzleRequired; } } diff --git a/jme3-core/src/main/java/com/jme3/renderer/opengl/GLImageFormats.java b/jme3-core/src/main/java/com/jme3/renderer/opengl/GLImageFormats.java index 423ae909e..ab80b9e2a 100644 --- a/jme3-core/src/main/java/com/jme3/renderer/opengl/GLImageFormats.java +++ b/jme3-core/src/main/java/com/jme3/renderer/opengl/GLImageFormats.java @@ -52,6 +52,13 @@ public final class GLImageFormats { formatToGL[0][format.ordinal()] = new GLImageFormat(glInternalFormat, glFormat, glDataType); } + private static void formatSwiz(GLImageFormat[][] formatToGL, Image.Format format, + int glInternalFormat, + int glFormat, + int glDataType){ + formatToGL[0][format.ordinal()] = new GLImageFormat(glInternalFormat, glFormat, glDataType, false, true); + } + private static void formatSrgb(GLImageFormat[][] formatToGL, Image.Format format, int glInternalFormat, int glFormat, @@ -60,6 +67,14 @@ public final class GLImageFormats { formatToGL[1][format.ordinal()] = new GLImageFormat(glInternalFormat, glFormat, glDataType); } + private static void formatSrgbSwiz(GLImageFormat[][] formatToGL, Image.Format format, + int glInternalFormat, + int glFormat, + int glDataType) + { + formatToGL[1][format.ordinal()] = new GLImageFormat(glInternalFormat, glFormat, glDataType, false, true); + } + private static void formatComp(GLImageFormat[][] formatToGL, Image.Format format, int glCompressedFormat, int glFormat, @@ -88,10 +103,25 @@ public final class GLImageFormats { public static GLImageFormat[][] getFormatsForCaps(EnumSet caps) { GLImageFormat[][] formatToGL = new GLImageFormat[2][Image.Format.values().length]; + // Core Profile Formats (supported by both OpenGL Core 3.3 and OpenGL ES 3.0+) + if (caps.contains(Caps.CoreProfile)) { + formatSwiz(formatToGL, Format.Alpha8, GL3.GL_R8, GL.GL_RED, GL.GL_UNSIGNED_BYTE); + formatSwiz(formatToGL, Format.Luminance8, GL3.GL_R8, GL.GL_RED, GL.GL_UNSIGNED_BYTE); + formatSwiz(formatToGL, Format.Luminance8Alpha8, GL3.GL_RG8, GL3.GL_RG, GL.GL_UNSIGNED_BYTE); + formatSwiz(formatToGL, Format.Luminance16F, GL3.GL_R16F, GL.GL_RED, GLExt.GL_HALF_FLOAT_ARB); + formatSwiz(formatToGL, Format.Luminance32F, GL3.GL_R32F, GL.GL_RED, GL.GL_FLOAT); + formatSwiz(formatToGL, Format.Luminance16FAlpha16F, GL3.GL_RG16F, GL3.GL_RG, GLExt.GL_HALF_FLOAT_ARB); + + formatSrgbSwiz(formatToGL, Format.Luminance8, GLExt.GL_SRGB8_EXT, GL.GL_RED, GL.GL_UNSIGNED_BYTE); + formatSrgbSwiz(formatToGL, Format.Luminance8Alpha8, GLExt.GL_SRGB8_ALPHA8_EXT, GL3.GL_RG, GL.GL_UNSIGNED_BYTE); + } + if (caps.contains(Caps.OpenGL20)) { - format(formatToGL, Format.Alpha8, GL2.GL_ALPHA8, GL.GL_ALPHA, GL.GL_UNSIGNED_BYTE); - format(formatToGL, Format.Luminance8, GL2.GL_LUMINANCE8, GL.GL_LUMINANCE, GL.GL_UNSIGNED_BYTE); - format(formatToGL, Format.Luminance8Alpha8, GL2.GL_LUMINANCE8_ALPHA8, GL.GL_LUMINANCE_ALPHA, GL.GL_UNSIGNED_BYTE); + if (!caps.contains(Caps.CoreProfile)) { + format(formatToGL, Format.Alpha8, GL2.GL_ALPHA8, GL.GL_ALPHA, GL.GL_UNSIGNED_BYTE); + format(formatToGL, Format.Luminance8, GL2.GL_LUMINANCE8, GL.GL_LUMINANCE, GL.GL_UNSIGNED_BYTE); + format(formatToGL, Format.Luminance8Alpha8, GL2.GL_LUMINANCE8_ALPHA8, GL.GL_LUMINANCE_ALPHA, GL.GL_UNSIGNED_BYTE); + } format(formatToGL, Format.RGB8, GL2.GL_RGB8, GL.GL_RGB, GL.GL_UNSIGNED_BYTE); format(formatToGL, Format.RGBA8, GLExt.GL_RGBA8, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE); format(formatToGL, Format.RGB565, GL2.GL_RGB8, GL.GL_RGB, GL.GL_UNSIGNED_SHORT_5_6_5); @@ -108,8 +138,10 @@ public final class GLImageFormats { formatSrgb(formatToGL, Format.RGB565, GLExt.GL_SRGB8_EXT, GL.GL_RGB, GL.GL_UNSIGNED_SHORT_5_6_5); formatSrgb(formatToGL, Format.RGB5A1, GLExt.GL_SRGB8_ALPHA8_EXT, GL.GL_RGBA, GL.GL_UNSIGNED_SHORT_5_5_5_1); formatSrgb(formatToGL, Format.RGBA8, GLExt.GL_SRGB8_ALPHA8_EXT, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE); - formatSrgb(formatToGL, Format.Luminance8, GLExt.GL_SLUMINANCE8_EXT, GL.GL_LUMINANCE, GL.GL_UNSIGNED_BYTE); - formatSrgb(formatToGL, Format.Luminance8Alpha8, GLExt.GL_SLUMINANCE8_ALPHA8_EXT, GL.GL_LUMINANCE_ALPHA, GL.GL_UNSIGNED_BYTE); + if (!caps.contains(Caps.CoreProfile)) { + formatSrgb(formatToGL, Format.Luminance8, GLExt.GL_SLUMINANCE8_EXT, GL.GL_LUMINANCE, GL.GL_UNSIGNED_BYTE); + formatSrgb(formatToGL, Format.Luminance8Alpha8, GLExt.GL_SLUMINANCE8_ALPHA8_EXT, GL.GL_LUMINANCE_ALPHA, GL.GL_UNSIGNED_BYTE); + } formatSrgb(formatToGL, Format.BGR8, GLExt.GL_SRGB8_EXT, GL2.GL_BGR, GL.GL_UNSIGNED_BYTE); formatSrgb(formatToGL, Format.ABGR8, GLExt.GL_SRGB8_ALPHA8_EXT, GL.GL_RGBA, GL2.GL_UNSIGNED_INT_8_8_8_8); formatSrgb(formatToGL, Format.ARGB8, GLExt.GL_SRGB8_ALPHA8_EXT, GL2.GL_BGRA, GL2.GL_UNSIGNED_INT_8_8_8_8); @@ -124,16 +156,20 @@ public final class GLImageFormats { } } else if (caps.contains(Caps.Rgba8)) { // A more limited form of 32-bit RGBA. Only GL_RGBA8 is available. - format(formatToGL, Format.Alpha8, GLExt.GL_RGBA8, GL.GL_ALPHA, GL.GL_UNSIGNED_BYTE); - format(formatToGL, Format.Luminance8, GLExt.GL_RGBA8, GL.GL_LUMINANCE, GL.GL_UNSIGNED_BYTE); - format(formatToGL, Format.Luminance8Alpha8, GLExt.GL_RGBA8, GL.GL_LUMINANCE_ALPHA, GL.GL_UNSIGNED_BYTE); + if (!caps.contains(Caps.CoreProfile)) { + format(formatToGL, Format.Alpha8, GLExt.GL_RGBA8, GL.GL_ALPHA, GL.GL_UNSIGNED_BYTE); + format(formatToGL, Format.Luminance8, GLExt.GL_RGBA8, GL.GL_LUMINANCE, GL.GL_UNSIGNED_BYTE); + format(formatToGL, Format.Luminance8Alpha8, GLExt.GL_RGBA8, GL.GL_LUMINANCE_ALPHA, GL.GL_UNSIGNED_BYTE); + } format(formatToGL, Format.RGB8, GLExt.GL_RGBA8, GL.GL_RGB, GL.GL_UNSIGNED_BYTE); format(formatToGL, Format.RGBA8, GLExt.GL_RGBA8, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE); } else { // Actually, the internal format isn't used for OpenGL ES 2! This is the same as the above.. - format(formatToGL, Format.Alpha8, GL.GL_RGBA4, GL.GL_ALPHA, GL.GL_UNSIGNED_BYTE); - format(formatToGL, Format.Luminance8, GL.GL_RGB565, GL.GL_LUMINANCE, GL.GL_UNSIGNED_BYTE); - format(formatToGL, Format.Luminance8Alpha8, GL.GL_RGBA4, GL.GL_LUMINANCE_ALPHA, GL.GL_UNSIGNED_BYTE); + if (!caps.contains(Caps.CoreProfile)) { + format(formatToGL, Format.Alpha8, GL.GL_RGBA4, GL.GL_ALPHA, GL.GL_UNSIGNED_BYTE); + format(formatToGL, Format.Luminance8, GL.GL_RGB565, GL.GL_LUMINANCE, GL.GL_UNSIGNED_BYTE); + format(formatToGL, Format.Luminance8Alpha8, GL.GL_RGBA4, GL.GL_LUMINANCE_ALPHA, GL.GL_UNSIGNED_BYTE); + } format(formatToGL, Format.RGB8, GL.GL_RGB565, GL.GL_RGB, GL.GL_UNSIGNED_BYTE); format(formatToGL, Format.RGBA8, GL.GL_RGBA4, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE); } @@ -145,9 +181,11 @@ public final class GLImageFormats { format(formatToGL, Format.RGB5A1, GL.GL_RGB5_A1, GL.GL_RGBA, GL.GL_UNSIGNED_SHORT_5_5_5_1); if (caps.contains(Caps.FloatTexture)) { - format(formatToGL, Format.Luminance16F, GLExt.GL_LUMINANCE16F_ARB, GL.GL_LUMINANCE, GLExt.GL_HALF_FLOAT_ARB); - format(formatToGL, Format.Luminance32F, GLExt.GL_LUMINANCE32F_ARB, GL.GL_LUMINANCE, GL.GL_FLOAT); - format(formatToGL, Format.Luminance16FAlpha16F, GLExt.GL_LUMINANCE_ALPHA16F_ARB, GL.GL_LUMINANCE_ALPHA, GLExt.GL_HALF_FLOAT_ARB); + if (!caps.contains(Caps.CoreProfile)) { + format(formatToGL, Format.Luminance16F, GLExt.GL_LUMINANCE16F_ARB, GL.GL_LUMINANCE, GLExt.GL_HALF_FLOAT_ARB); + format(formatToGL, Format.Luminance32F, GLExt.GL_LUMINANCE32F_ARB, GL.GL_LUMINANCE, GL.GL_FLOAT); + format(formatToGL, Format.Luminance16FAlpha16F, GLExt.GL_LUMINANCE_ALPHA16F_ARB, GL.GL_LUMINANCE_ALPHA, GLExt.GL_HALF_FLOAT_ARB); + } format(formatToGL, Format.RGB16F, GLExt.GL_RGB16F_ARB, GL.GL_RGB, GLExt.GL_HALF_FLOAT_ARB); format(formatToGL, Format.RGB32F, GLExt.GL_RGB32F_ARB, GL.GL_RGB, GL.GL_FLOAT); format(formatToGL, Format.RGBA16F, GLExt.GL_RGBA16F_ARB, GL.GL_RGBA, GLExt.GL_HALF_FLOAT_ARB); diff --git a/jme3-core/src/main/java/com/jme3/renderer/opengl/GLRenderer.java b/jme3-core/src/main/java/com/jme3/renderer/opengl/GLRenderer.java index 395b7e485..729f4e203 100644 --- a/jme3-core/src/main/java/com/jme3/renderer/opengl/GLRenderer.java +++ b/jme3-core/src/main/java/com/jme3/renderer/opengl/GLRenderer.java @@ -54,8 +54,10 @@ import com.jme3.texture.Texture; import com.jme3.texture.Texture.WrapAxis; import com.jme3.util.BufferUtils; import com.jme3.util.ListMap; +import com.jme3.util.MipMapGenerator; import com.jme3.util.NativeObjectManager; import java.nio.*; +import java.util.Arrays; import java.util.EnumMap; import java.util.EnumSet; import java.util.HashSet; @@ -71,7 +73,7 @@ public class GLRenderer implements Renderer { private static final Logger logger = Logger.getLogger(GLRenderer.class.getName()); private static final boolean VALIDATE_SHADER = false; private static final Pattern GLVERSION_PATTERN = Pattern.compile(".*?(\\d+)\\.(\\d+).*"); - + private final ByteBuffer nameBuf = BufferUtils.createByteBuffer(250); private final StringBuilder stringBuf = new StringBuilder(250); private final IntBuffer intBuf1 = BufferUtils.createIntBuffer(1); @@ -81,22 +83,7 @@ public class GLRenderer implements Renderer { private final NativeObjectManager objManager = new NativeObjectManager(); private final EnumSet caps = EnumSet.noneOf(Caps.class); private final EnumMap limits = new EnumMap(Limits.class); - -// private int vertexTextureUnits; -// private int fragTextureUnits; -// private int vertexUniforms; -// private int fragUniforms; -// private int vertexAttribs; -// private int maxFBOSamples; -// private int maxFBOAttachs; -// private int maxMRTFBOAttachs; -// private int maxRBSize; -// private int maxTexSize; -// private int maxCubeTexSize; -// private int maxVertCount; -// private int maxTriCount; -// private int maxColorTexSamples; -// private int maxDepthTexSamples; + private FrameBuffer mainFbOverride = null; private final Statistics statistics = new Statistics(); private int vpX, vpY, vpW, vpH; @@ -111,15 +98,15 @@ public class GLRenderer implements Renderer { private final GLExt glext; private final GLFbo glfbo; private final TextureUtil texUtil; - - public GLRenderer(GL gl, GLFbo glfbo) { + + public GLRenderer(GL gl, GLExt glext, GLFbo glfbo) { this.gl = gl; this.gl2 = gl instanceof GL2 ? (GL2)gl : null; this.gl3 = gl instanceof GL3 ? (GL3)gl : null; this.gl4 = gl instanceof GL4 ? (GL4)gl : null; this.glfbo = glfbo; - this.glext = glfbo instanceof GLExt ? (GLExt)glfbo : null; - this.texUtil = new TextureUtil(gl, gl2, glext, context); + this.glext = glext; + this.texUtil = new TextureUtil(gl, gl2, glext); } @Override @@ -131,20 +118,29 @@ public class GLRenderer implements Renderer { public EnumSet getCaps() { return caps; } - + // Not making public yet ... public EnumMap getLimits() { return limits; } - private static HashSet loadExtensions(String extensions) { + private HashSet loadExtensions() { HashSet extensionSet = new HashSet(64); - for (String extension : extensions.split(" ")) { - extensionSet.add(extension); + if (caps.contains(Caps.OpenGL30)) { + // If OpenGL3+ is available, use the non-deprecated way + // of getting supported extensions. + gl3.glGetInteger(GL3.GL_NUM_EXTENSIONS, intBuf16); + int extensionCount = intBuf16.get(0); + for (int i = 0; i < extensionCount; i++) { + String extension = gl3.glGetString(GL.GL_EXTENSIONS, i); + extensionSet.add(extension); + } + } else { + extensionSet.addAll(Arrays.asList(gl.glGetString(GL.GL_EXTENSIONS).split(" "))); } return extensionSet; } - + public static int extractVersion(String version) { Matcher m = GLVERSION_PATTERN.matcher(version); if (m.matches()) { @@ -164,17 +160,17 @@ public class GLRenderer implements Renderer { private boolean hasExtension(String extensionName) { return extensions.contains(extensionName); } - + private void loadCapabilitiesES() { caps.add(Caps.GLSL100); caps.add(Caps.OpenGLES20); - + // Important: Do not add OpenGL20 - that's the desktop capability! } - + private void loadCapabilitiesGL2() { int oglVer = extractVersion(gl.glGetString(GL.GL_VERSION)); - + if (oglVer >= 200) { caps.add(Caps.OpenGL20); if (oglVer >= 210) { @@ -185,10 +181,12 @@ public class GLRenderer implements Renderer { caps.add(Caps.OpenGL31); if (oglVer >= 320) { caps.add(Caps.OpenGL32); - }if(oglVer>=330){ + } + if (oglVer >= 330) { caps.add(Caps.OpenGL33); caps.add(Caps.GeometryShader); - }if(oglVer>=400){ + } + if (oglVer >= 400) { caps.add(Caps.OpenGL40); caps.add(Caps.TesselationShader); } @@ -196,9 +194,9 @@ public class GLRenderer implements Renderer { } } } - + int glslVer = extractVersion(gl.glGetString(GL.GL_SHADING_LANGUAGE_VERSION)); - + switch (glslVer) { default: if (glslVer < 400) { @@ -224,27 +222,27 @@ public class GLRenderer implements Renderer { caps.add(Caps.GLSL100); break; } - + // Workaround, always assume we support GLSL100 & GLSL110 // Supporting OpenGL 2.0 means supporting GLSL 1.10. caps.add(Caps.GLSL110); caps.add(Caps.GLSL100); - + // Fix issue in TestRenderToMemory when GL.GL_FRONT is the main // buffer being used. context.initialDrawBuf = getInteger(GL2.GL_DRAW_BUFFER); context.initialReadBuf = getInteger(GL2.GL_READ_BUFFER); - + // XXX: This has to be GL.GL_BACK for canvas on Mac // Since initialDrawBuf is GL.GL_FRONT for pbuffer, gotta // change this value later on ... // initialDrawBuf = GL.GL_BACK; // initialReadBuf = GL.GL_BACK; } - + private void loadCapabilitiesCommon() { - extensions = loadExtensions(gl.glGetString(GL.GL_EXTENSIONS)); - + extensions = loadExtensions(); + limits.put(Limits.VertexTextureUnits, getInteger(GL.GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS)); if (limits.get(Limits.VertexTextureUnits) > 0) { caps.add(Caps.VertexTextureFetch); @@ -259,62 +257,66 @@ public class GLRenderer implements Renderer { // gl.glGetInteger(GL.GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, intBuf16); // fragUniforms = intBuf16.get(0); // logger.log(Level.FINER, "Fragment Uniforms: {0}", fragUniforms); - + if (caps.contains(Caps.OpenGLES20)) { + limits.put(Limits.VertexUniformVectors, getInteger(GL.GL_MAX_VERTEX_UNIFORM_VECTORS)); + } else { + limits.put(Limits.VertexUniformVectors, getInteger(GL.GL_MAX_VERTEX_UNIFORM_COMPONENTS) / 4); + } limits.put(Limits.VertexAttributes, getInteger(GL.GL_MAX_VERTEX_ATTRIBS)); limits.put(Limits.TextureSize, getInteger(GL.GL_MAX_TEXTURE_SIZE)); limits.put(Limits.CubemapSize, getInteger(GL.GL_MAX_CUBE_MAP_TEXTURE_SIZE)); - if (hasExtension("GL_ARB_draw_instanced") && - hasExtension("GL_ARB_instanced_arrays")) { + if (hasExtension("GL_ARB_draw_instanced") && + hasExtension("GL_ARB_instanced_arrays")) { caps.add(Caps.MeshInstancing); } if (hasExtension("GL_OES_element_index_uint") || gl2 != null) { caps.add(Caps.IntegerIndexBuffer); } - + if (hasExtension("GL_ARB_texture_buffer_object")) { caps.add(Caps.TextureBuffer); } - + // == texture format extensions == - - boolean hasFloatTexture = false; + + boolean hasFloatTexture; hasFloatTexture = hasExtension("GL_OES_texture_half_float") && - hasExtension("GL_OES_texture_float"); - + hasExtension("GL_OES_texture_float"); + if (!hasFloatTexture) { hasFloatTexture = hasExtension("GL_ARB_texture_float") && - hasExtension("GL_ARB_half_float_pixel"); - + hasExtension("GL_ARB_half_float_pixel"); + if (!hasFloatTexture) { hasFloatTexture = caps.contains(Caps.OpenGL30); } } - + if (hasFloatTexture) { caps.add(Caps.FloatTexture); } - + if (hasExtension("GL_OES_depth_texture") || gl2 != null) { caps.add(Caps.DepthTexture); - + // TODO: GL_OES_depth24 } - - if (hasExtension("GL_OES_rgb8_rgba8") || - hasExtension("GL_ARM_rgba8") || - hasExtension("GL_EXT_texture_format_BGRA8888")) { + + if (hasExtension("GL_OES_rgb8_rgba8") || + hasExtension("GL_ARM_rgba8") || + hasExtension("GL_EXT_texture_format_BGRA8888")) { caps.add(Caps.Rgba8); } - + if (caps.contains(Caps.OpenGL30) || hasExtension("GL_OES_packed_depth_stencil")) { caps.add(Caps.PackedDepthStencilBuffer); } if (hasExtension("GL_ARB_color_buffer_float") && - hasExtension("GL_ARB_half_float_pixel")) { + hasExtension("GL_ARB_half_float_pixel")) { // XXX: Require both 16 and 32 bit float support for FloatColorBuffer. caps.add(Caps.FloatColorBuffer); } @@ -323,45 +325,44 @@ public class GLRenderer implements Renderer { caps.add(Caps.FloatDepthBuffer); } - if ((hasExtension("GL_EXT_packed_float") && hasFloatTexture) || - caps.contains(Caps.OpenGL30)) { + if ((hasExtension("GL_EXT_packed_float") && hasFloatTexture) || + caps.contains(Caps.OpenGL30)) { // Either OpenGL3 is available or both packed_float & half_float_pixel. caps.add(Caps.PackedFloatColorBuffer); caps.add(Caps.PackedFloatTexture); } - + if (hasExtension("GL_EXT_texture_shared_exponent") || caps.contains(Caps.OpenGL30)) { caps.add(Caps.SharedExponentTexture); } - + if (hasExtension("GL_EXT_texture_compression_s3tc")) { caps.add(Caps.TextureCompressionS3TC); } - + if (hasExtension("GL_ARB_ES3_compatibility")) { caps.add(Caps.TextureCompressionETC2); caps.add(Caps.TextureCompressionETC1); } else if (hasExtension("GL_OES_compressed_ETC1_RGB8_texture")) { caps.add(Caps.TextureCompressionETC1); } - + // == end texture format extensions == - + if (hasExtension("GL_ARB_vertex_array_object") || caps.contains(Caps.OpenGL30)) { caps.add(Caps.VertexBufferArray); } - if (hasExtension("GL_ARB_texture_non_power_of_two") || - hasExtension("GL_OES_texture_npot") || - hasExtension("GL_APPLE_texture_2D_limited_npot") || - caps.contains(Caps.OpenGL30)) { + if (hasExtension("GL_ARB_texture_non_power_of_two") || + hasExtension("GL_OES_texture_npot") || + caps.contains(Caps.OpenGL30)) { caps.add(Caps.NonPowerOfTwoTextures); } else { logger.log(Level.WARNING, "Your graphics card does not " - + "support non-power-of-2 textures. " - + "Some features might not work."); + + "support non-power-of-2 textures. " + + "Some features might not work."); } - + if (caps.contains(Caps.OpenGLES20)) { // OpenGL ES 2 has some limited support for NPOT textures caps.add(Caps.PartialNonPowerOfTwoTextures); @@ -375,16 +376,16 @@ public class GLRenderer implements Renderer { caps.add(Caps.TextureFilterAnisotropic); } - if (hasExtension("GL_EXT_framebuffer_object")) { + if (hasExtension("GL_EXT_framebuffer_object") || gl3 != null) { caps.add(Caps.FrameBuffer); - - limits.put(Limits.RenderBufferSize, getInteger(GLExt.GL_MAX_RENDERBUFFER_SIZE_EXT)); - limits.put(Limits.FrameBufferAttachments, getInteger(GLExt.GL_MAX_COLOR_ATTACHMENTS_EXT)); - + + limits.put(Limits.RenderBufferSize, getInteger(GLFbo.GL_MAX_RENDERBUFFER_SIZE_EXT)); + limits.put(Limits.FrameBufferAttachments, getInteger(GLFbo.GL_MAX_COLOR_ATTACHMENTS_EXT)); + if (hasExtension("GL_EXT_framebuffer_blit")) { caps.add(Caps.FrameBufferBlit); } - + if (hasExtension("GL_EXT_framebuffer_multisample")) { caps.add(Caps.FrameBufferMultisample); limits.put(Limits.FrameBufferSamples, getInteger(GLExt.GL_MAX_SAMPLES_EXT)); @@ -422,10 +423,10 @@ public class GLRenderer implements Renderer { } caps.add(Caps.Multisample); } - + // Supports sRGB pipeline. - if ( (hasExtension("GL_ARB_framebuffer_sRGB") && hasExtension("GL_EXT_texture_sRGB")) - || caps.contains(Caps.OpenGL30) ) { + if ( (hasExtension("GL_ARB_framebuffer_sRGB") && hasExtension("GL_EXT_texture_sRGB")) + || caps.contains(Caps.OpenGL30) ) { caps.add(Caps.Srgb); } @@ -433,24 +434,33 @@ public class GLRenderer implements Renderer { if (hasExtension("GL_ARB_seamless_cube_map") || caps.contains(Caps.OpenGL32)) { caps.add(Caps.SeamlessCubemap); } - -// if (hasExtension("GL_ARB_get_program_binary")) { -// int binaryFormats = getInteger(GLExt.GL_NUM_PROGRAM_BINARY_FORMATS); -// } - + + if (caps.contains(Caps.OpenGL32) && !hasExtension("GL_ARB_compatibility")) { + caps.add(Caps.CoreProfile); + } + + if (hasExtension("GL_ARB_get_program_binary")) { + int binaryFormats = getInteger(GLExt.GL_NUM_PROGRAM_BINARY_FORMATS); + if (binaryFormats > 0) { + caps.add(Caps.BinaryShader); + } + } + // Print context information logger.log(Level.INFO, "OpenGL Renderer Information\n" + - " * Vendor: {0}\n" + - " * Renderer: {1}\n" + - " * OpenGL Version: {2}\n" + - " * GLSL Version: {3}", - new Object[]{ - gl.glGetString(GL.GL_VENDOR), - gl.glGetString(GL.GL_RENDERER), - gl.glGetString(GL.GL_VERSION), - gl.glGetString(GL.GL_SHADING_LANGUAGE_VERSION) - }); - + " * Vendor: {0}\n" + + " * Renderer: {1}\n" + + " * OpenGL Version: {2}\n" + + " * GLSL Version: {3}\n" + + " * Profile: {4}", + new Object[]{ + gl.glGetString(GL.GL_VENDOR), + gl.glGetString(GL.GL_RENDERER), + gl.glGetString(GL.GL_VERSION), + gl.glGetString(GL.GL_SHADING_LANGUAGE_VERSION), + caps.contains(Caps.CoreProfile) ? "Core" : "Compatibility" + }); + // Print capabilities (if fine logging is enabled) if (logger.isLoggable(Level.FINE)) { StringBuilder sb = new StringBuilder(); @@ -461,10 +471,10 @@ public class GLRenderer implements Renderer { } logger.log(Level.FINE, sb.toString()); } - + texUtil.initialize(caps); } - + private void loadCapabilities() { if (gl2 != null) { loadCapabilitiesGL2(); @@ -473,24 +483,38 @@ public class GLRenderer implements Renderer { } loadCapabilitiesCommon(); } - + private int getInteger(int en) { intBuf16.clear(); gl.glGetInteger(en, intBuf16); return intBuf16.get(0); } - + private boolean getBoolean(int en) { gl.glGetBoolean(en, nameBuf); return nameBuf.get(0) != (byte)0; } - + @SuppressWarnings("fallthrough") public void initialize() { loadCapabilities(); - + // Initialize default state.. gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1); + + if (caps.contains(Caps.CoreProfile)) { + // Core Profile requires VAO to be bound. + gl3.glGenVertexArrays(intBuf16); + int vaoId = intBuf16.get(0); + gl3.glBindVertexArray(vaoId); + } + if (gl2 != null) { + gl2.glEnable(GL2.GL_VERTEX_PROGRAM_POINT_SIZE); + if (!caps.contains(Caps.CoreProfile)) { + gl2.glEnable(GL2.GL_POINT_SPRITE); + context.pointSprite = true; + } + } } public void invalidateState() { @@ -516,8 +540,8 @@ public class GLRenderer implements Renderer { } /*********************************************************************\ - |* Render State *| - \*********************************************************************/ + |* Render State *| + \*********************************************************************/ public void setDepthRange(float start, float end) { gl.glDepthRange(start, end); } @@ -582,7 +606,7 @@ public class GLRenderer implements Renderer { } if (state.isDepthTest() && !context.depthTestEnabled) { - gl.glEnable(GL.GL_DEPTH_TEST); + gl.glEnable(GL.GL_DEPTH_TEST); gl.glDepthFunc(convertTestFunction(context.depthFunc)); context.depthTestEnabled = true; } else if (!state.isDepthTest() && context.depthTestEnabled) { @@ -610,31 +634,6 @@ public class GLRenderer implements Renderer { context.colorWriteEnabled = false; } - if (gl2 != null) { - if (state.isPointSprite() && !context.pointSprite) { - // Only enable/disable sprite - if (context.boundTextures[0] != null) { - if (context.boundTextureUnit != 0) { - gl.glActiveTexture(GL.GL_TEXTURE0); - context.boundTextureUnit = 0; - } - gl2.glEnable(GL2.GL_POINT_SPRITE); - gl2.glEnable(GL2.GL_VERTEX_PROGRAM_POINT_SIZE); - } - context.pointSprite = true; - } else if (!state.isPointSprite() && context.pointSprite) { - if (context.boundTextures[0] != null) { - if (context.boundTextureUnit != 0) { - gl.glActiveTexture(GL.GL_TEXTURE0); - context.boundTextureUnit = 0; - } - gl2.glDisable(GL2.GL_POINT_SPRITE); - gl2.glDisable(GL2.GL_VERTEX_PROGRAM_POINT_SIZE); - context.pointSprite = false; - } - } - } - if (state.isPolyOffset()) { if (!context.polyOffsetEnabled) { gl.glEnable(GL.GL_POLYGON_OFFSET_FILL); @@ -704,9 +703,6 @@ public class GLRenderer implements Renderer { case AlphaAdditive: gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE); break; - case Color: - gl.glBlendFunc(GL.GL_ONE, GL.GL_ONE_MINUS_SRC_COLOR); - break; case Alpha: gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); break; @@ -719,9 +715,10 @@ public class GLRenderer implements Renderer { case ModulateX2: gl.glBlendFunc(GL.GL_DST_COLOR, GL.GL_SRC_COLOR); break; + case Color: case Screen: gl.glBlendFunc(GL.GL_ONE, GL.GL_ONE_MINUS_SRC_COLOR); - break; + break; case Exclusion: gl.glBlendFunc(GL.GL_ONE_MINUS_DST_COLOR, GL.GL_ONE_MINUS_SRC_COLOR); break; @@ -822,8 +819,8 @@ public class GLRenderer implements Renderer { } /*********************************************************************\ - |* Camera and World transforms *| - \*********************************************************************/ + |* Camera and World transforms *| + \*********************************************************************/ public void setViewPort(int x, int y, int w, int h) { if (x != vpX || vpY != y || vpW != w || vpH != h) { gl.glViewport(x, y, w, h); @@ -862,11 +859,12 @@ public class GLRenderer implements Renderer { public void postFrame() { objManager.deleteUnused(this); + gl.resetStats(); } /*********************************************************************\ - |* Shaders *| - \*********************************************************************/ + |* Shaders *| + \*********************************************************************/ protected void updateUniformLocation(Shader shader, Uniform uniform) { int loc = gl.glGetUniformLocation(shader.getId(), uniform.getName()); if (loc < 0) { @@ -1046,12 +1044,12 @@ public class GLRenderer implements Renderer { boolean gles2 = caps.contains(Caps.OpenGLES20); String language = source.getLanguage(); - + if (gles2 && !language.equals("GLSL100")) { throw new RendererException("This shader cannot run in OpenGL ES 2. " - + "Only GLSL 1.00 shaders are supported."); + + "Only GLSL 1.00 shaders are supported."); } - + // Upload shader source. // Merge the defines and source code. stringBuf.setLength(0); @@ -1078,14 +1076,14 @@ public class GLRenderer implements Renderer { } } } - + if (linearizeSrgbImages) { stringBuf.append("#define SRGB 1\n"); } - + stringBuf.append(source.getDefines()); stringBuf.append(source.getSource()); - + intBuf1.clear(); intBuf1.put(0, stringBuf.length()); gl.glShaderSource(id, new String[]{ stringBuf.toString() }, intBuf1); @@ -1143,7 +1141,7 @@ public class GLRenderer implements Renderer { // If using GLSL 1.5, we bind the outputs for the user // For versions 3.3 and up, user should use layout qualifiers instead. boolean bindFragDataRequired = false; - + for (ShaderSource source : shader.getSources()) { if (source.isUpdateNeeded()) { updateShaderSourceData(source); @@ -1252,8 +1250,8 @@ public class GLRenderer implements Renderer { } /*********************************************************************\ - |* Framebuffers *| - \*********************************************************************/ + |* Framebuffers *| + \*********************************************************************/ public void copyFrameBuffer(FrameBuffer src, FrameBuffer dst) { copyFrameBuffer(src, dst, true); } @@ -1290,24 +1288,24 @@ public class GLRenderer implements Renderer { } if (src == null) { - glfbo.glBindFramebufferEXT(GLExt.GL_READ_FRAMEBUFFER_EXT, 0); + glfbo.glBindFramebufferEXT(GLFbo.GL_READ_FRAMEBUFFER_EXT, 0); srcX0 = vpX; srcY0 = vpY; srcX1 = vpX + vpW; srcY1 = vpY + vpH; } else { - glfbo.glBindFramebufferEXT(GLExt.GL_READ_FRAMEBUFFER_EXT, src.getId()); + glfbo.glBindFramebufferEXT(GLFbo.GL_READ_FRAMEBUFFER_EXT, src.getId()); srcX1 = src.getWidth(); srcY1 = src.getHeight(); } if (dst == null) { - glfbo.glBindFramebufferEXT(GLExt.GL_DRAW_FRAMEBUFFER_EXT, 0); + glfbo.glBindFramebufferEXT(GLFbo.GL_DRAW_FRAMEBUFFER_EXT, 0); dstX0 = vpX; dstY0 = vpY; dstX1 = vpX + vpW; dstY1 = vpY + vpH; } else { - glfbo.glBindFramebufferEXT(GLExt.GL_DRAW_FRAMEBUFFER_EXT, dst.getId()); + glfbo.glBindFramebufferEXT(GLFbo.GL_DRAW_FRAMEBUFFER_EXT, dst.getId()); dstX1 = dst.getWidth(); dstY1 = dst.getHeight(); } @@ -1315,19 +1313,12 @@ public class GLRenderer implements Renderer { if (copyDepth) { mask |= GL.GL_DEPTH_BUFFER_BIT; } - glext.glBlitFramebufferEXT(srcX0, srcY0, srcX1, srcY1, + glfbo.glBlitFramebufferEXT(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, GL.GL_NEAREST); - glfbo.glBindFramebufferEXT(GLExt.GL_FRAMEBUFFER_EXT, prevFBO); - try { - checkFrameBufferError(); - } catch (IllegalStateException ex) { - logger.log(Level.SEVERE, "Source FBO:\n{0}", src); - logger.log(Level.SEVERE, "Dest FBO:\n{0}", dst); - throw ex; - } + glfbo.glBindFramebufferEXT(GLFbo.GL_FRAMEBUFFER_EXT, prevFBO); } else { throw new RendererException("Framebuffer blitting not supported by the video hardware"); } @@ -1373,7 +1364,7 @@ public class GLRenderer implements Renderer { } if (context.boundRB != id) { - glfbo.glBindRenderbufferEXT(GLExt.GL_RENDERBUFFER_EXT, id); + glfbo.glBindRenderbufferEXT(GLFbo.GL_RENDERBUFFER_EXT, id); context.boundRB = id; } @@ -1391,13 +1382,13 @@ public class GLRenderer implements Renderer { if (maxSamples < samples) { samples = maxSamples; } - glext.glRenderbufferStorageMultisampleEXT(GLExt.GL_RENDERBUFFER_EXT, + glfbo.glRenderbufferStorageMultisampleEXT(GLFbo.GL_RENDERBUFFER_EXT, samples, glFmt.internalFormat, fb.getWidth(), fb.getHeight()); } else { - glfbo.glRenderbufferStorageEXT(GLExt.GL_RENDERBUFFER_EXT, + glfbo.glRenderbufferStorageEXT(GLFbo.GL_RENDERBUFFER_EXT, glFmt.internalFormat, fb.getWidth(), fb.getHeight()); @@ -1407,7 +1398,7 @@ public class GLRenderer implements Renderer { private int convertAttachmentSlot(int attachmentSlot) { // can also add support for stencil here if (attachmentSlot == FrameBuffer.SLOT_DEPTH) { - return GLExt.GL_DEPTH_ATTACHMENT_EXT; + return GLFbo.GL_DEPTH_ATTACHMENT_EXT; } else if (attachmentSlot == FrameBuffer.SLOT_DEPTH_STENCIL) { // NOTE: Using depth stencil format requires GL3, this is already // checked via render caps. @@ -1415,8 +1406,8 @@ public class GLRenderer implements Renderer { } else if (attachmentSlot < 0 || attachmentSlot >= 16) { throw new UnsupportedOperationException("Invalid FBO attachment slot: " + attachmentSlot); } - - return GLExt.GL_COLOR_ATTACHMENT0_EXT + attachmentSlot; + + return GLFbo.GL_COLOR_ATTACHMENT0_EXT + attachmentSlot; } public void updateRenderTexture(FrameBuffer fb, RenderBuffer rb) { @@ -1425,8 +1416,8 @@ public class GLRenderer implements Renderer { if (image.isUpdateNeeded()) { // Check NPOT requirements checkNonPowerOfTwo(tex); - - updateTexImageData(image, tex.getType(), 0); + + updateTexImageData(image, tex.getType(), 0, false); // NOTE: For depth textures, sets nearest/no-mips mode // Required to fix "framebuffer unsupported" @@ -1434,7 +1425,7 @@ public class GLRenderer implements Renderer { setupTextureParams(tex); } - glfbo.glFramebufferTexture2DEXT(GLExt.GL_FRAMEBUFFER_EXT, + glfbo.glFramebufferTexture2DEXT(GLFbo.GL_FRAMEBUFFER_EXT, convertAttachmentSlot(rb.getSlot()), convertTextureType(tex.getType(), image.getMultiSamples(), rb.getFace()), image.getId(), @@ -1452,9 +1443,9 @@ public class GLRenderer implements Renderer { updateRenderTexture(fb, rb); } if (needAttach) { - glfbo.glFramebufferRenderbufferEXT(GLExt.GL_FRAMEBUFFER_EXT, + glfbo.glFramebufferRenderbufferEXT(GLFbo.GL_FRAMEBUFFER_EXT, convertAttachmentSlot(rb.getSlot()), - GLExt.GL_RENDERBUFFER_EXT, + GLFbo.GL_RENDERBUFFER_EXT, rb.getId()); } } @@ -1472,7 +1463,7 @@ public class GLRenderer implements Renderer { } if (context.boundFBO != id) { - glfbo.glBindFramebufferEXT(GLExt.GL_FRAMEBUFFER_EXT, id); + glfbo.glBindFramebufferEXT(GLFbo.GL_FRAMEBUFFER_EXT, id); // binding an FBO automatically sets draw buf to GL_COLOR_ATTACHMENT0 context.boundDrawBuf = 0; context.boundFBO = id; @@ -1488,6 +1479,8 @@ public class GLRenderer implements Renderer { updateFrameBufferAttachment(fb, colorBuf); } + checkFrameBufferError(); + fb.clearUpdateNeeded(); } @@ -1542,13 +1535,7 @@ public class GLRenderer implements Renderer { setTexture(0, rb.getTexture()); int textureType = convertTextureType(tex.getType(), tex.getImage().getMultiSamples(), rb.getFace()); - if (gl2 != null) { - gl2.glEnable(textureType); - } glfbo.glGenerateMipmapEXT(textureType); - if (gl2 != null) { - gl2.glDisable(textureType); - } } } } @@ -1556,7 +1543,7 @@ public class GLRenderer implements Renderer { if (fb == null) { // unbind any fbos if (context.boundFBO != 0) { - glfbo.glBindFramebufferEXT(GLExt.GL_FRAMEBUFFER_EXT, 0); + glfbo.glBindFramebufferEXT(GLFbo.GL_FRAMEBUFFER_EXT, 0); statistics.onFrameBufferUse(null, true); context.boundFBO = 0; @@ -1586,9 +1573,9 @@ public class GLRenderer implements Renderer { // update viewport to reflect framebuffer's resolution setViewPort(0, 0, fb.getWidth(), fb.getHeight()); - + if (context.boundFBO != fb.getId()) { - glfbo.glBindFramebufferEXT(GLExt.GL_FRAMEBUFFER_EXT, fb.getId()); + glfbo.glBindFramebufferEXT(GLFbo.GL_FRAMEBUFFER_EXT, fb.getId()); statistics.onFrameBufferUse(fb, true); context.boundFBO = fb.getId(); @@ -1628,7 +1615,7 @@ public class GLRenderer implements Renderer { if (context.boundDrawBuf != 100 + fb.getNumColorBuffers()) { intBuf16.clear(); for (int i = 0; i < fb.getNumColorBuffers(); i++) { - intBuf16.put(GLExt.GL_COLOR_ATTACHMENT0_EXT + i); + intBuf16.put(GLFbo.GL_COLOR_ATTACHMENT0_EXT + i); } intBuf16.flip(); @@ -1640,7 +1627,7 @@ public class GLRenderer implements Renderer { // select this draw buffer if (gl2 != null) { if (context.boundDrawBuf != rb.getSlot()) { - gl2.glDrawBuffer(GLExt.GL_COLOR_ATTACHMENT0_EXT + rb.getSlot()); + gl2.glDrawBuffer(GLFbo.GL_COLOR_ATTACHMENT0_EXT + rb.getSlot()); context.boundDrawBuf = rb.getSlot(); } } @@ -1651,15 +1638,13 @@ public class GLRenderer implements Renderer { assert context.boundFBO == fb.getId(); context.boundFB = fb; - - checkFrameBufferError(); } } public void readFrameBuffer(FrameBuffer fb, ByteBuffer byteBuf) { readFrameBufferWithGLFormat(fb, byteBuf, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE); } - + private void readFrameBufferWithGLFormat(FrameBuffer fb, ByteBuffer byteBuf, int glFormat, int dataType) { if (fb != null) { RenderBuffer rb = fb.getColorBuffer(); @@ -1671,7 +1656,7 @@ public class GLRenderer implements Renderer { setFrameBuffer(fb); if (gl2 != null) { if (context.boundReadBuf != rb.getSlot()) { - gl2.glReadBuffer(GLExt.GL_COLOR_ATTACHMENT0_EXT + rb.getSlot()); + gl2.glReadBuffer(GLFbo.GL_COLOR_ATTACHMENT0_EXT + rb.getSlot()); context.boundReadBuf = rb.getSlot(); } } @@ -1681,8 +1666,8 @@ public class GLRenderer implements Renderer { gl.glReadPixels(vpX, vpY, vpW, vpH, glFormat, dataType, byteBuf); } - - public void readFrameBufferWithFormat(FrameBuffer fb, ByteBuffer byteBuf, Image.Format format) { + + public void readFrameBufferWithFormat(FrameBuffer fb, ByteBuffer byteBuf, Image.Format format) { GLImageFormat glFormat = texUtil.getImageFormatWithError(format, false); readFrameBufferWithGLFormat(fb, byteBuf, glFormat.format, glFormat.dataType); } @@ -1695,7 +1680,7 @@ public class GLRenderer implements Renderer { public void deleteFrameBuffer(FrameBuffer fb) { if (fb.getId() != -1) { if (context.boundFBO == fb.getId()) { - glfbo.glBindFramebufferEXT(GLExt.GL_FRAMEBUFFER_EXT, 0); + glfbo.glBindFramebufferEXT(GLFbo.GL_FRAMEBUFFER_EXT, 0); context.boundFBO = 0; } @@ -1715,14 +1700,14 @@ public class GLRenderer implements Renderer { } /*********************************************************************\ - |* Textures *| - \*********************************************************************/ + |* Textures *| + \*********************************************************************/ private int convertTextureType(Texture.Type type, int samples, int face) { if (samples > 1 && !caps.contains(Caps.TextureMultisample)) { - throw new RendererException("Multisample textures are not supported" + - " by the video hardware."); + throw new RendererException("Multisample textures are not supported" + + " by the video hardware."); } - + switch (type) { case TwoDimensional: if (samples > 1) { @@ -1742,8 +1727,8 @@ public class GLRenderer implements Renderer { } case ThreeDimensional: if (!caps.contains(Caps.OpenGL20)) { - throw new RendererException("3D textures are not supported" + - " by the video hardware."); + throw new RendererException("3D textures are not supported" + + " by the video hardware."); } return GL2.GL_TEXTURE_3D; case CubeMap: @@ -1826,11 +1811,11 @@ public class GLRenderer implements Renderer { int target = convertTextureType(tex.getType(), image != null ? image.getMultiSamples() : 1, -1); boolean haveMips = true; - + if (image != null) { haveMips = image.isGeneratedMipmapsRequired() || image.hasMipmaps(); } - + // filter things if (image.getLastTextureState().magFilter != tex.getMagFilter()) { int magFilter = convertMagFilter(tex.getMagFilter()); @@ -1853,7 +1838,7 @@ public class GLRenderer implements Renderer { context.seamlessCubemap = false; } } - + if (tex.getAnisotropicFilter() > 1) { if (caps.contains(Caps.TextureFilterAnisotropic)) { gl.glTexParameterf(target, @@ -1862,10 +1847,6 @@ public class GLRenderer implements Renderer { } } - if (context.pointSprite) { - return; // Attempt to fix glTexParameter crash for some ATI GPUs - } - // repeat modes switch (tex.getType()) { case ThreeDimensional: @@ -1894,15 +1875,15 @@ public class GLRenderer implements Renderer { // R to Texture compare mode if (tex.getShadowCompareMode() != Texture.ShadowCompareMode.Off) { gl2.glTexParameteri(target, GL2.GL_TEXTURE_COMPARE_MODE, GL2.GL_COMPARE_R_TO_TEXTURE); - gl2.glTexParameteri(target, GL2.GL_DEPTH_TEXTURE_MODE, GL2.GL_INTENSITY); + gl2.glTexParameteri(target, GL2.GL_DEPTH_TEXTURE_MODE, GL2.GL_INTENSITY); if (tex.getShadowCompareMode() == Texture.ShadowCompareMode.GreaterOrEqual) { gl2.glTexParameteri(target, GL2.GL_TEXTURE_COMPARE_FUNC, GL.GL_GEQUAL); } else { gl2.glTexParameteri(target, GL2.GL_TEXTURE_COMPARE_FUNC, GL.GL_LEQUAL); } }else{ - //restoring default value - gl2.glTexParameteri(target, GL2.GL_TEXTURE_COMPARE_MODE, GL.GL_NONE); + //restoring default value + gl2.glTexParameteri(target, GL2.GL_TEXTURE_COMPARE_MODE, GL.GL_NONE); } tex.compareModeUpdated(); } @@ -1914,7 +1895,7 @@ public class GLRenderer implements Renderer { * Textures with power-of-2 dimensions are supported on all hardware, however * non-power-of-2 textures may or may not be supported depending on which * texturing features are used. - * + * * @param tex The texture to validate. * @throws RendererException If the texture is not supported by the hardware */ @@ -1923,23 +1904,23 @@ public class GLRenderer implements Renderer { // Texture is power-of-2, safe to use. return; } - + if (caps.contains(Caps.NonPowerOfTwoTextures)) { // Texture is NPOT but it is supported by video hardware. return; } - + // Maybe we have some / partial support for NPOT? if (!caps.contains(Caps.PartialNonPowerOfTwoTextures)) { // Cannot use any type of NPOT texture (uncommon) throw new RendererException("non-power-of-2 textures are not " - + "supported by the video hardware"); + + "supported by the video hardware"); } - + // Partial NPOT supported.. if (tex.getMinFilter().usesMipMapLevels()) { throw new RendererException("non-power-of-2 textures with mip-maps " - + "are not supported by the video hardware"); + + "are not supported by the video hardware"); } switch (tex.getType()) { @@ -1947,7 +1928,7 @@ public class GLRenderer implements Renderer { case ThreeDimensional: if (tex.getWrap(WrapAxis.R) != Texture.WrapMode.EdgeClamp) { throw new RendererException("repeating non-power-of-2 textures " - + "are not supported by the video hardware"); + + "are not supported by the video hardware"); } // fallthrough intentional!!! case TwoDimensionalArray: @@ -1955,22 +1936,24 @@ public class GLRenderer implements Renderer { if (tex.getWrap(WrapAxis.S) != Texture.WrapMode.EdgeClamp || tex.getWrap(WrapAxis.T) != Texture.WrapMode.EdgeClamp) { throw new RendererException("repeating non-power-of-2 textures " - + "are not supported by the video hardware"); + + "are not supported by the video hardware"); } break; default: throw new UnsupportedOperationException("unrecongized texture type"); } } - + /** * Uploads the given image to the GL driver. - * + * * @param img The image to upload * @param type How the data in the image argument should be interpreted. * @param unit The texture slot to be used to upload the image, not important + * @param scaleToPot If true, the image will be scaled to power-of-2 dimensions + * before being uploaded. */ - public void updateTexImageData(Image img, Texture.Type type, int unit) { + public void updateTexImageData(Image img, Texture.Type type, int unit, boolean scaleToPot) { int texId = img.getId(); if (texId == -1) { // create texture @@ -1989,7 +1972,7 @@ public class GLRenderer implements Renderer { gl.glActiveTexture(GL.GL_TEXTURE0 + unit); context.boundTextureUnit = unit; } - + gl.glBindTexture(target, texId); context.boundTextures[unit] = img; @@ -2000,7 +1983,7 @@ public class GLRenderer implements Renderer { // Image does not have mipmaps, but they are required. // Generate from base level. - if (!caps.contains(Caps.OpenGL30) && gl2 != null) { + if (!caps.contains(Caps.FrameBuffer) && gl2 != null) { gl2.glTexParameteri(target, GL2.GL_GENERATE_MIPMAP, GL.GL_TRUE); img.setMipmapsGenerated(true); } else { @@ -2032,12 +2015,12 @@ public class GLRenderer implements Renderer { throw new RendererException("Multisample textures are not supported by the video hardware"); } } - + // Check if graphics card doesn't support depth textures if (img.getFormat().isDepthFormat() && !caps.contains(Caps.DepthTexture)) { throw new RendererException("Depth textures are not supported by the video hardware"); } - + if (target == GL.GL_TEXTURE_CUBE_MAP) { // Check max texture size before upload int cubeSize = limits.get(Limits.CubemapSize); @@ -2054,44 +2037,48 @@ public class GLRenderer implements Renderer { } } + Image imageForUpload; + if (scaleToPot) { + imageForUpload = MipMapGenerator.resizeToPowerOf2(img); + } else { + imageForUpload = img; + } if (target == GL.GL_TEXTURE_CUBE_MAP) { - List data = img.getData(); + List data = imageForUpload.getData(); if (data.size() != 6) { logger.log(Level.WARNING, "Invalid texture: {0}\n" + "Cubemap textures must contain 6 data units.", img); return; } for (int i = 0; i < 6; i++) { - texUtil.uploadTexture(img, GL.GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, i, linearizeSrgbImages); + texUtil.uploadTexture(imageForUpload, GL.GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, i, linearizeSrgbImages); } } else if (target == GLExt.GL_TEXTURE_2D_ARRAY_EXT) { if (!caps.contains(Caps.TextureArray)) { throw new RendererException("Texture arrays not supported by graphics hardware"); } - - List data = img.getData(); - + + List data = imageForUpload.getData(); + // -1 index specifies prepare data for 2D Array - texUtil.uploadTexture(img, target, -1, linearizeSrgbImages); - + texUtil.uploadTexture(imageForUpload, target, -1, linearizeSrgbImages); + for (int i = 0; i < data.size(); i++) { // upload each slice of 2D array in turn // this time with the appropriate index - texUtil.uploadTexture(img, target, i, linearizeSrgbImages); + texUtil.uploadTexture(imageForUpload, target, i, linearizeSrgbImages); } } else { - texUtil.uploadTexture(img, target, 0, linearizeSrgbImages); + texUtil.uploadTexture(imageForUpload, target, 0, linearizeSrgbImages); } if (img.getMultiSamples() != imageSamples) { img.setMultiSamples(imageSamples); } - if (caps.contains(Caps.OpenGL30) || gl2 == null) { + if (caps.contains(Caps.FrameBuffer) || gl2 == null) { if (!img.hasMipmaps() && img.isGeneratedMipmapsRequired() && img.getData(0) != null) { - if (gl2 != null) gl2.glEnable(target); // XXX: Required for ATI glfbo.glGenerateMipmapEXT(target); - if (gl2 != null) gl2.glDisable(target); img.setMipmapsGenerated(true); } } @@ -2103,9 +2090,23 @@ public class GLRenderer implements Renderer { Image image = tex.getImage(); if (image.isUpdateNeeded() || (image.isGeneratedMipmapsRequired() && !image.isMipmapsGenerated())) { // Check NPOT requirements - checkNonPowerOfTwo(tex); - - updateTexImageData(image, tex.getType(), unit); + boolean scaleToPot = false; + + try { + checkNonPowerOfTwo(tex); + } catch (RendererException ex) { + if (logger.isLoggable(Level.WARNING)) { + int nextWidth = FastMath.nearestPowerOfTwo(tex.getImage().getWidth()); + int nextHeight = FastMath.nearestPowerOfTwo(tex.getImage().getHeight()); + logger.log(Level.WARNING, + "Non-power-of-2 textures are not supported! Scaling texture '" + tex.getName() + + "' of size " + tex.getImage().getWidth() + "x" + tex.getImage().getHeight() + + " to " + nextWidth + "x" + nextHeight); + } + scaleToPot = true; + } + + updateTexImageData(image, tex.getType(), unit, scaleToPot); } int texId = image.getId(); @@ -2150,8 +2151,8 @@ public class GLRenderer implements Renderer { } /*********************************************************************\ - |* Vertex Buffers and Attributes *| - \*********************************************************************/ + |* Vertex Buffers and Attributes *| + \*********************************************************************/ private int convertUsage(Usage usage) { switch (usage) { case Static: @@ -2225,57 +2226,29 @@ public class GLRenderer implements Renderer { //statistics.onVertexBufferUse(vb, false); } } - + int usage = convertUsage(vb.getUsage()); vb.getData().rewind(); -// if (created || vb.hasDataSizeChanged()) { - // upload data based on format - switch (vb.getFormat()) { - case Byte: - case UnsignedByte: - gl.glBufferData(target, (ByteBuffer) vb.getData(), usage); - break; - // case Half: - case Short: - case UnsignedShort: - gl.glBufferData(target, (ShortBuffer) vb.getData(), usage); - break; - case Int: - case UnsignedInt: - glext.glBufferData(target, (IntBuffer) vb.getData(), usage); - break; - case Float: - gl.glBufferData(target, (FloatBuffer) vb.getData(), usage); - break; - default: - throw new UnsupportedOperationException("Unknown buffer format."); - } -// } else { -// // Invalidate buffer data (orphan) before uploading new data. -// switch (vb.getFormat()) { -// case Byte: -// case UnsignedByte: -// gl.glBufferSubData(target, 0, (ByteBuffer) vb.getData()); -// break; -// case Short: -// case UnsignedShort: -// gl.glBufferSubData(target, 0, (ShortBuffer) vb.getData()); -// break; -// case Int: -// case UnsignedInt: -// gl.glBufferSubData(target, 0, (IntBuffer) vb.getData()); -// break; -// case Float: -// gl.glBufferSubData(target, 0, (FloatBuffer) vb.getData()); -// break; -// case Double: -// gl.glBufferSubData(target, 0, (DoubleBuffer) vb.getData()); -// break; -// default: -// throw new UnsupportedOperationException("Unknown buffer format."); -// } -// } + switch (vb.getFormat()) { + case Byte: + case UnsignedByte: + gl.glBufferData(target, (ByteBuffer) vb.getData(), usage); + break; + case Short: + case UnsignedShort: + gl.glBufferData(target, (ShortBuffer) vb.getData(), usage); + break; + case Int: + case UnsignedInt: + glext.glBufferData(target, (IntBuffer) vb.getData(), usage); + break; + case Float: + gl.glBufferData(target, (FloatBuffer) vb.getData(), usage); + break; + default: + throw new UnsupportedOperationException("Unknown buffer format."); + } vb.clearUpdateNeeded(); } @@ -2314,7 +2287,7 @@ public class GLRenderer implements Renderer { if (context.boundShaderProgram <= 0) { throw new IllegalStateException("Cannot render mesh without shader bound"); } - + Attribute attrib = context.boundShader.getAttribute(vb.getBufferType()); int loc = attrib.getLocation(); if (loc == -1) { @@ -2444,7 +2417,7 @@ public class GLRenderer implements Renderer { // What is this? throw new RendererException("Unexpected format for index buffer: " + indexBuf.getFormat()); } - + if (indexBuf.isUpdateNeeded()) { updateBufferData(indexBuf); } @@ -2518,8 +2491,8 @@ public class GLRenderer implements Renderer { } /*********************************************************************\ - |* Render Calls *| - \*********************************************************************/ + |* Render Calls *| + \*********************************************************************/ public int convertElementMode(Mesh.Mode mode) { switch (mode) { case Points: @@ -2561,7 +2534,7 @@ public class GLRenderer implements Renderer { if (interleavedData != null && interleavedData.isUpdateNeeded()) { updateBufferData(interleavedData); } - + if (instanceData != null) { setVertexAttrib(instanceData, null); } @@ -2611,11 +2584,11 @@ public class GLRenderer implements Renderer { } private void renderMeshDefault(Mesh mesh, int lod, int count, VertexBuffer[] instanceData) { - + // Here while count is still passed in. Can be removed when/if // the method is collapsed again. -pspeed count = Math.max(mesh.getInstanceCount(), count); - + VertexBuffer interleavedData = mesh.getBuffer(Type.InterleavedData); if (interleavedData != null && interleavedData.isUpdateNeeded()) { updateBufferData(interleavedData); @@ -2633,7 +2606,7 @@ public class GLRenderer implements Renderer { setVertexAttrib(vb, null); } } - + for (VertexBuffer vb : mesh.getBufferList().getArray()) { if (vb.getBufferType() == Type.InterleavedData || vb.getUsage() == Usage.CpuOnly // ignore cpu-only buffers @@ -2663,32 +2636,13 @@ public class GLRenderer implements Renderer { return; } - if (context.pointSprite && mesh.getMode() != Mode.Points) { - // XXX: Hack, disable point sprite mode if mesh not in point mode - if (context.boundTextures[0] != null) { - if (context.boundTextureUnit != 0) { - gl.glActiveTexture(GL.GL_TEXTURE0); - context.boundTextureUnit = 0; - } - if (gl2 != null) { - gl2.glDisable(GL2.GL_POINT_SPRITE); - gl2.glDisable(GL2.GL_VERTEX_PROGRAM_POINT_SIZE); - } - context.pointSprite = false; - } - } - if (gl2 != null) { - if (context.pointSize != mesh.getPointSize()) { - gl2.glPointSize(mesh.getPointSize()); - context.pointSize = mesh.getPointSize(); - } - } if (context.lineWidth != mesh.getLineWidth()) { gl.glLineWidth(mesh.getLineWidth()); context.lineWidth = mesh.getLineWidth(); } - if(gl4!=null && mesh.getMode().equals(Mode.Patch)){ + + if (gl4 != null && mesh.getMode().equals(Mode.Patch)) { gl4.glPatchParameter(mesh.getPatchVertexCount()); } statistics.onMeshDrawn(mesh, lod, count); @@ -2701,14 +2655,14 @@ public class GLRenderer implements Renderer { public void setMainFrameBufferSrgb(boolean enableSrgb) { // Gamma correction - if (!caps.contains(Caps.Srgb)) { + if (!caps.contains(Caps.Srgb) && enableSrgb) { // Not supported, sorry. - logger.warning("sRGB framebuffer is not supported " + - "by video hardware, but was requested."); - + logger.warning("sRGB framebuffer is not supported " + + "by video hardware, but was requested."); + return; } - + setFrameBuffer(null); if (enableSrgb) { diff --git a/jme3-core/src/main/java/com/jme3/renderer/opengl/GLTiming.java b/jme3-core/src/main/java/com/jme3/renderer/opengl/GLTiming.java new file mode 100644 index 000000000..7e6833b8b --- /dev/null +++ b/jme3-core/src/main/java/com/jme3/renderer/opengl/GLTiming.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.renderer.opengl; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.Arrays; +import java.util.Comparator; +import java.util.Map; + +public class GLTiming implements InvocationHandler { + + private final Object obj; + private final GLTimingState state; + + public GLTiming(Object obj, GLTimingState state) { + this.obj = obj; + this.state = state; + } + + public static Object createGLTiming(Object glInterface, GLTimingState state, Class ... glInterfaceClasses) { + return Proxy.newProxyInstance(glInterface.getClass().getClassLoader(), + glInterfaceClasses, + new GLTiming(glInterface, state)); + } + + private static class CallTimingComparator implements Comparator> { + @Override + public int compare(Map.Entry o1, Map.Entry o2) { + return (int) (o2.getValue() - o1.getValue()); + } + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + String methodName = method.getName(); + if (methodName.equals("resetStats")) { + if (state.lastPrintOutTime + 1000000000 <= System.nanoTime() && state.sampleCount > 0) { + state.timeSpentInGL /= state.sampleCount; + System.out.println("--- TOTAL TIME SPENT IN GL CALLS: " + (state.timeSpentInGL/1000) + "us"); + + Map.Entry[] callTimes = new Map.Entry[state.callTiming.size()]; + int i = 0; + for (Map.Entry callTime : state.callTiming.entrySet()) { + callTimes[i++] = callTime; + } + Arrays.sort(callTimes, new CallTimingComparator()); + int limit = 10; + for (Map.Entry callTime : callTimes) { + long val = callTime.getValue() / state.sampleCount; + String name = callTime.getKey(); + String pad = " ".substring(0, 30 - name.length()); + System.out.println("\t" + callTime.getKey() + pad + (val/1000) + "us"); + if (limit-- == 0) break; + } + for (Map.Entry callTime : callTimes) { + state.callTiming.put(callTime.getKey(), Long.valueOf(0)); + } + + state.sampleCount = 0; + state.timeSpentInGL = 0; + state.lastPrintOutTime = System.nanoTime(); + } else { + state.sampleCount++; + } + return null; + } else { + Long currentTimeObj = state.callTiming.get(methodName); + long currentTime = 0; + if (currentTimeObj != null) currentTime = currentTimeObj; + + + long startTime = System.nanoTime(); + Object result = method.invoke(obj, args); + long delta = System.nanoTime() - startTime; + + currentTime += delta; + state.timeSpentInGL += delta; + + state.callTiming.put(methodName, currentTime); + + if (delta > 1000000 && !methodName.equals("glClear")) { + // More than 1ms + // Ignore glClear as it cannot be avoided. + System.out.println("GL call " + methodName + " took " + (delta/1000) + "us to execute!"); + } + + return result; + } + } + +} diff --git a/jme3-core/src/main/java/com/jme3/renderer/opengl/GLTimingState.java b/jme3-core/src/main/java/com/jme3/renderer/opengl/GLTimingState.java new file mode 100644 index 000000000..ca25810d4 --- /dev/null +++ b/jme3-core/src/main/java/com/jme3/renderer/opengl/GLTimingState.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.renderer.opengl; + +import java.util.HashMap; + +public class GLTimingState { + long timeSpentInGL = 0; + int sampleCount = 0; + long lastPrintOutTime = 0; + final HashMap callTiming = new HashMap(); +} \ No newline at end of file diff --git a/jme3-core/src/main/java/com/jme3/renderer/opengl/GLTracer.java b/jme3-core/src/main/java/com/jme3/renderer/opengl/GLTracer.java index 459e2d3a3..1b0d70749 100644 --- a/jme3-core/src/main/java/com/jme3/renderer/opengl/GLTracer.java +++ b/jme3-core/src/main/java/com/jme3/renderer/opengl/GLTracer.java @@ -64,12 +64,14 @@ public final class GLTracer implements InvocationHandler { noEnumArgs("glScissor", 0, 1, 2, 3); noEnumArgs("glClear", 0); noEnumArgs("glGetInteger", 1); + noEnumArgs("glGetString", 1); noEnumArgs("glBindTexture", 1); noEnumArgs("glPixelStorei", 1); // noEnumArgs("glTexParameteri", 2); noEnumArgs("glTexImage2D", 1, 3, 4, 5); noEnumArgs("glTexImage3D", 1, 3, 4, 5, 6); + noEnumArgs("glTexSubImage2D", 1, 2, 3, 4, 5); noEnumArgs("glTexSubImage3D", 1, 2, 3, 4, 5, 6, 7); noEnumArgs("glCompressedTexImage2D", 1, 3, 4, 5); noEnumArgs("glCompressedTexSubImage3D", 1, 2, 3, 4, 5, 6, 7); @@ -83,6 +85,8 @@ public final class GLTracer implements InvocationHandler { noEnumArgs("glDrawRangeElements", 1, 2, 3, 5); noEnumArgs("glDrawArrays", 1, 2); noEnumArgs("glDeleteBuffers", 0); + noEnumArgs("glBindVertexArray", 0); + noEnumArgs("glGenVertexArrays", 0); noEnumArgs("glBindFramebufferEXT", 1); noEnumArgs("glBindRenderbufferEXT", 1); @@ -92,8 +96,6 @@ public final class GLTracer implements InvocationHandler { noEnumArgs("glFramebufferTexture2DEXT", 3, 4); noEnumArgs("glBlitFramebufferEXT", 0, 1, 2, 3, 4, 5, 6, 7, 8); - - noEnumArgs("glCreateProgram", -1); noEnumArgs("glCreateShader", -1); noEnumArgs("glShaderSource", 0); @@ -110,6 +112,7 @@ public final class GLTracer implements InvocationHandler { noEnumArgs("glUniform1f", 0); noEnumArgs("glUniform2f", 0); noEnumArgs("glUniform3f", 0); + noEnumArgs("glUniform4", 0); noEnumArgs("glUniform4f", 0); noEnumArgs("glGetAttribLocation", 0, -1); noEnumArgs("glDetachShader", 0, 1); @@ -151,7 +154,7 @@ public final class GLTracer implements InvocationHandler { * @return A tracer that implements the given interface */ public static Object createGlesTracer(Object glInterface, Class glInterfaceClass) { - IntMap constMap = generateConstantMap(GL.class, GLExt.class); + IntMap constMap = generateConstantMap(GL.class, GLFbo.class, GLExt.class); return Proxy.newProxyInstance(glInterface.getClass().getClassLoader(), new Class[] { glInterfaceClass }, new GLTracer(glInterface, constMap)); @@ -165,7 +168,7 @@ public final class GLTracer implements InvocationHandler { * @return A tracer that implements the given interface */ public static Object createDesktopGlTracer(Object glInterface, Class ... glInterfaceClasses) { - IntMap constMap = generateConstantMap(GL2.class, GLExt.class); + IntMap constMap = generateConstantMap(GL2.class, GL3.class, GL4.class, GLFbo.class, GLExt.class); return Proxy.newProxyInstance(glInterface.getClass().getClassLoader(), glInterfaceClasses, new GLTracer(glInterface, constMap)); diff --git a/jme3-core/src/main/java/com/jme3/renderer/opengl/TextureUtil.java b/jme3-core/src/main/java/com/jme3/renderer/opengl/TextureUtil.java index 37ffe5ed3..a2f21ceaa 100644 --- a/jme3-core/src/main/java/com/jme3/renderer/opengl/TextureUtil.java +++ b/jme3-core/src/main/java/com/jme3/renderer/opengl/TextureUtil.java @@ -54,14 +54,12 @@ final class TextureUtil { private final GL gl; private final GL2 gl2; private final GLExt glext; - private final RenderContext context; private GLImageFormat[][] formats; - - public TextureUtil(GL gl, GL2 gl2, GLExt glext, RenderContext context) { + + public TextureUtil(GL gl, GL2 gl2, GLExt glext) { this.gl = gl; this.gl2 = gl2; this.glext = glext; - this.context = context; } public void initialize(EnumSet caps) { @@ -103,6 +101,33 @@ final class TextureUtil { return glFmt; } + private void setupTextureSwizzle(int target, Format format) { + // Needed for OpenGL 3.3 to support luminance / alpha formats + switch (format) { + case Alpha8: + gl.glTexParameteri(target, GL3.GL_TEXTURE_SWIZZLE_R, GL.GL_ZERO); + gl.glTexParameteri(target, GL3.GL_TEXTURE_SWIZZLE_G, GL.GL_ZERO); + gl.glTexParameteri(target, GL3.GL_TEXTURE_SWIZZLE_B, GL.GL_ZERO); + gl.glTexParameteri(target, GL3.GL_TEXTURE_SWIZZLE_A, GL.GL_RED); + break; + case Luminance8: + case Luminance16F: + case Luminance32F: + gl.glTexParameteri(target, GL3.GL_TEXTURE_SWIZZLE_R, GL.GL_RED); + gl.glTexParameteri(target, GL3.GL_TEXTURE_SWIZZLE_G, GL.GL_RED); + gl.glTexParameteri(target, GL3.GL_TEXTURE_SWIZZLE_B, GL.GL_RED); + gl.glTexParameteri(target, GL3.GL_TEXTURE_SWIZZLE_A, GL.GL_ONE); + break; + case Luminance8Alpha8: + case Luminance16FAlpha16F: + gl.glTexParameteri(target, GL3.GL_TEXTURE_SWIZZLE_R, GL.GL_RED); + gl.glTexParameteri(target, GL3.GL_TEXTURE_SWIZZLE_G, GL.GL_RED); + gl.glTexParameteri(target, GL3.GL_TEXTURE_SWIZZLE_B, GL.GL_RED); + gl.glTexParameteri(target, GL3.GL_TEXTURE_SWIZZLE_A, GL.GL_GREEN); + break; + } + } + private void uploadTextureLevel(GLImageFormat format, int target, int level, int slice, int sliceCount, int width, int height, int depth, int samples, ByteBuffer data) { if (format.compressed && data != null) { if (target == GL2.GL_TEXTURE_3D) { @@ -242,6 +267,11 @@ final class TextureUtil { } int samples = image.getMultiSamples(); + + // For OGL3 core: setup texture swizzle. + if (oglFormat.swizzleRequired) { + setupTextureSwizzle(target, jmeFormat); + } for (int i = 0; i < mipSizes.length; i++) { int mipWidth = Math.max(1, width >> i); diff --git a/jme3-core/src/main/java/com/jme3/scene/BatchNode.java b/jme3-core/src/main/java/com/jme3/scene/BatchNode.java index 8cfed4244..9a920093d 100644 --- a/jme3-core/src/main/java/com/jme3/scene/BatchNode.java +++ b/jme3-core/src/main/java/com/jme3/scene/BatchNode.java @@ -64,7 +64,7 @@ import java.util.logging.Logger; * TODO more automagic (batch when needed in the updateLogicalState) * @author Nehon */ -public class BatchNode extends GeometryGroupNode implements Savable { +public class BatchNode extends GeometryGroupNode { private static final Logger logger = Logger.getLogger(BatchNode.class.getName()); /** @@ -119,19 +119,6 @@ public class BatchNode extends GeometryGroupNode implements Savable { setNeedsFullRebatch(true); } - @Override - public void updateGeometricState() { - if (!children.isEmpty()) { - for (Batch batch : batches.getArray()) { - if (batch.needMeshUpdate) { - batch.geometry.updateModelBound(); - batch.geometry.updateWorldBound(); - batch.needMeshUpdate = false; - } - } - } - super.updateGeometricState(); - } protected Matrix4f getTransformMatrix(Geometry g){ return g.cachedWorldMat; @@ -169,7 +156,7 @@ public class BatchNode extends GeometryGroupNode implements Savable { nvb.updateData(normBuf); - batch.needMeshUpdate = true; + batch.geometry.updateModelBound(); } } @@ -234,7 +221,7 @@ public class BatchNode extends GeometryGroupNode implements Savable { batch.geometry.setMesh(m); batch.geometry.getMesh().updateCounts(); - batch.geometry.getMesh().updateBound(); + batch.geometry.updateModelBound(); batches.add(batch); } if (batches.size() > 0) { @@ -583,11 +570,13 @@ public class BatchNode extends GeometryGroupNode implements Savable { useTangents = true; } } else { - inBuf.copyElements(0, outBuf, globalVertIndex, geomVertCount); -// for (int vert = 0; vert < geomVertCount; vert++) { -// int curGlobalVertIndex = globalVertIndex + vert; -// inBuf.copyElement(vert, outBuf, curGlobalVertIndex); -// } + if (inBuf == null) { + throw new IllegalArgumentException("Geometry " + geom.getName() + " has no " + outBuf.getBufferType() + " buffer whereas other geoms have. all geometries should have the same types of buffers.\n Try to use GeometryBatchFactory.alignBuffer() on the BatchNode before batching"); + } else if (outBuf == null) { + throw new IllegalArgumentException("Geometry " + geom.getName() + " has a " + outBuf.getBufferType() + " buffer whereas other geoms don't. all geometries should have the same types of buffers.\n Try to use GeometryBatchFactory.alignBuffer() on the BatchNode before batching"); + } else { + inBuf.copyElements(0, outBuf, globalVertIndex, geomVertCount); + } } } @@ -745,8 +734,7 @@ public class BatchNode extends GeometryGroupNode implements Savable { } } } - Geometry geometry; - boolean needMeshUpdate = false; + Geometry geometry; } protected void setNeedsFullRebatch(boolean needsFullRebatch) { diff --git a/jme3-core/src/main/java/com/jme3/scene/Node.java b/jme3-core/src/main/java/com/jme3/scene/Node.java index 816140e21..5edfa021b 100644 --- a/jme3-core/src/main/java/com/jme3/scene/Node.java +++ b/jme3-core/src/main/java/com/jme3/scene/Node.java @@ -58,7 +58,7 @@ import java.util.logging.Logger; * @author Gregg Patton * @author Joshua Slack */ -public class Node extends Spatial implements Savable { +public class Node extends Spatial { private static final Logger logger = Logger.getLogger(Node.class.getName()); diff --git a/jme3-core/src/main/java/com/jme3/scene/UserData.java b/jme3-core/src/main/java/com/jme3/scene/UserData.java index 4b5d70404..3047618fc 100644 --- a/jme3-core/src/main/java/com/jme3/scene/UserData.java +++ b/jme3-core/src/main/java/com/jme3/scene/UserData.java @@ -33,6 +33,12 @@ package com.jme3.scene; import com.jme3.export.*; import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; /** * UserData is used to contain user data objects @@ -48,28 +54,40 @@ public final class UserData implements Savable { * shape generation should ignore them. */ public static final String JME_PHYSICSIGNORE = "JmePhysicsIgnore"; - + /** * For geometries using shared mesh, this will specify the shared * mesh reference. */ - public static final String JME_SHAREDMESH = "JmeSharedMesh"; - - protected byte type; - protected Object value; + public static final String JME_SHAREDMESH = "JmeSharedMesh"; + + private static final int TYPE_INTEGER = 0; + private static final int TYPE_FLOAT = 1; + private static final int TYPE_BOOLEAN = 2; + private static final int TYPE_STRING = 3; + private static final int TYPE_LONG = 4; + private static final int TYPE_SAVABLE = 5; + private static final int TYPE_LIST = 6; + private static final int TYPE_MAP = 7; + private static final int TYPE_ARRAY = 8; + + protected byte type; + protected Object value; public UserData() { } /** - * Creates a new UserData with the given + * Creates a new UserData with the given * type and value. * - * @param type Type of data, should be between 0 and 4. - * @param value Value of the data + * @param type + * Type of data, should be between 0 and 8. + * @param value + * Value of the data */ public UserData(byte type, Object value) { - assert type >= 0 && type <= 4; + assert type >= 0 && type <= 8; this.type = type; this.value = value; } @@ -85,15 +103,23 @@ public final class UserData implements Savable { public static byte getObjectType(Object type) { if (type instanceof Integer) { - return 0; + return TYPE_INTEGER; } else if (type instanceof Float) { - return 1; + return TYPE_FLOAT; } else if (type instanceof Boolean) { - return 2; + return TYPE_BOOLEAN; } else if (type instanceof String) { - return 3; + return TYPE_STRING; } else if (type instanceof Long) { - return 4; + return TYPE_LONG; + } else if (type instanceof Savable) { + return TYPE_SAVABLE; + } else if (type instanceof List) { + return TYPE_LIST; + } else if (type instanceof Map) { + return TYPE_MAP; + } else if (type instanceof Object[]) { + return TYPE_ARRAY; } else { throw new IllegalArgumentException("Unsupported type: " + type.getClass().getName()); } @@ -101,56 +127,195 @@ public final class UserData implements Savable { public void write(JmeExporter ex) throws IOException { OutputCapsule oc = ex.getCapsule(this); - oc.write(type, "type", (byte)0); + oc.write(type, "type", (byte) 0); switch (type) { - case 0: + case TYPE_INTEGER: int i = (Integer) value; oc.write(i, "intVal", 0); break; - case 1: + case TYPE_FLOAT: float f = (Float) value; oc.write(f, "floatVal", 0f); break; - case 2: + case TYPE_BOOLEAN: boolean b = (Boolean) value; oc.write(b, "boolVal", false); break; - case 3: + case TYPE_STRING: String s = (String) value; oc.write(s, "strVal", null); break; - case 4: + case TYPE_LONG: Long l = (Long) value; oc.write(l, "longVal", 0l); break; + case TYPE_SAVABLE: + Savable sav = (Savable) value; + oc.write(sav, "savableVal", null); + break; + case TYPE_LIST: + this.writeList(oc, (List) value, "0"); + break; + case TYPE_MAP: + Map map = (Map) value; + this.writeList(oc, map.keySet(), "0"); + this.writeList(oc, map.values(), "1"); + break; + case TYPE_ARRAY: + this.writeList(oc, Arrays.asList((Object[]) value), "0"); + break; default: - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException("Unsupported value type: " + value.getClass()); } } public void read(JmeImporter im) throws IOException { InputCapsule ic = im.getCapsule(this); type = ic.readByte("type", (byte) 0); - switch (type) { - case 0: + case TYPE_INTEGER: value = ic.readInt("intVal", 0); break; - case 1: + case TYPE_FLOAT: value = ic.readFloat("floatVal", 0f); break; - case 2: + case TYPE_BOOLEAN: value = ic.readBoolean("boolVal", false); break; - case 3: + case TYPE_STRING: value = ic.readString("strVal", null); break; - case 4: + case TYPE_LONG: value = ic.readLong("longVal", 0l); break; + case TYPE_SAVABLE: + value = ic.readSavable("savableVal", null); + break; + case TYPE_LIST: + value = this.readList(ic, "0"); + break; + case TYPE_MAP: + Map map = new HashMap(); + List keys = this.readList(ic, "0"); + List values = this.readList(ic, "1"); + for (int i = 0; i < keys.size(); ++i) { + map.put(keys.get(i), values.get(i)); + } + value = map; + break; + case TYPE_ARRAY: + value = this.readList(ic, "0").toArray(); + break; default: - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException("Unknown type of stored data: " + type); + } + } + + /** + * The method stores a list in the capsule. + * @param oc + * output capsule + * @param list + * the list to be stored + * @throws IOException + */ + private void writeList(OutputCapsule oc, Collection list, String listName) throws IOException { + if (list != null) { + oc.write(list.size(), listName + "size", 0); + int counter = 0; + for (Object o : list) { + // t is for 'type'; v is for 'value' + if (o instanceof Integer) { + oc.write(TYPE_INTEGER, listName + "t" + counter, 0); + oc.write((Integer) o, listName + "v" + counter, 0); + } else if (o instanceof Float) { + oc.write(TYPE_FLOAT, listName + "t" + counter, 0); + oc.write((Float) o, listName + "v" + counter, 0f); + } else if (o instanceof Boolean) { + oc.write(TYPE_BOOLEAN, listName + "t" + counter, 0); + oc.write((Boolean) o, listName + "v" + counter, false); + } else if (o instanceof String || o == null) {// treat null's like Strings just to store them and keep the List like the user intended + oc.write(TYPE_STRING, listName + "t" + counter, 0); + oc.write((String) o, listName + "v" + counter, null); + } else if (o instanceof Long) { + oc.write(TYPE_LONG, listName + "t" + counter, 0); + oc.write((Long) o, listName + "v" + counter, 0L); + } else if (o instanceof Savable) { + oc.write(TYPE_SAVABLE, listName + "t" + counter, 0); + oc.write((Savable) o, listName + "v" + counter, null); + } else if(o instanceof Object[]) { + oc.write(TYPE_ARRAY, listName + "t" + counter, 0); + this.writeList(oc, Arrays.asList((Object[]) o), listName + "v" + counter); + } else if(o instanceof List) { + oc.write(TYPE_LIST, listName + "t" + counter, 0); + this.writeList(oc, (List) o, listName + "v" + counter); + } else if(o instanceof Map) { + oc.write(TYPE_MAP, listName + "t" + counter, 0); + Map map = (Map) o; + this.writeList(oc, map.keySet(), listName + "v(keys)" + counter); + this.writeList(oc, map.values(), listName + "v(vals)" + counter); + } else { + throw new UnsupportedOperationException("Unsupported type stored in the list: " + o.getClass()); + } + + ++counter; + } + } else { + oc.write(0, "size", 0); + } + } + + /** + * The method loads a list from the given input capsule. + * @param ic + * the input capsule + * @return loaded list (an empty list in case its size is 0) + * @throws IOException + */ + private List readList(InputCapsule ic, String listName) throws IOException { + int size = ic.readInt(listName + "size", 0); + List list = new ArrayList(size); + for (int i = 0; i < size; ++i) { + int type = ic.readInt(listName + "t" + i, 0); + switch (type) { + case TYPE_INTEGER: + list.add(ic.readInt(listName + "v" + i, 0)); + break; + case TYPE_FLOAT: + list.add(ic.readFloat(listName + "v" + i, 0)); + break; + case TYPE_BOOLEAN: + list.add(ic.readBoolean(listName + "v" + i, false)); + break; + case TYPE_STRING: + list.add(ic.readString(listName + "v" + i, null)); + break; + case TYPE_LONG: + list.add(ic.readLong(listName + "v" + i, 0L)); + break; + case TYPE_SAVABLE: + list.add(ic.readSavable(listName + "v" + i, null)); + break; + case TYPE_ARRAY: + list.add(this.readList(ic, listName + "v" + i).toArray()); + break; + case TYPE_LIST: + list.add(this.readList(ic, listName + "v" + i)); + break; + case TYPE_MAP: + Map map = new HashMap(); + List keys = this.readList(ic, listName + "v(keys)" + i); + List values = this.readList(ic, listName + "v(vals)" + i); + for (int j = 0; j < keys.size(); ++j) { + map.put(keys.get(j), values.get(j)); + } + list.add(map); + break; + default: + throw new UnsupportedOperationException("Unknown type of stored data in a list: " + type); + } } + return list; } } diff --git a/jme3-core/src/main/java/com/jme3/scene/instancing/InstancedNode.java b/jme3-core/src/main/java/com/jme3/scene/instancing/InstancedNode.java index b3cb26da0..554b8606a 100644 --- a/jme3-core/src/main/java/com/jme3/scene/instancing/InstancedNode.java +++ b/jme3-core/src/main/java/com/jme3/scene/instancing/InstancedNode.java @@ -57,7 +57,7 @@ public class InstancedNode extends GeometryGroupNode { setGeometryStartIndex(geom, startIndex); } - private static class InstanceTypeKey implements Cloneable { + private static final class InstanceTypeKey implements Cloneable { Mesh mesh; Material material; diff --git a/jme3-core/src/main/java/com/jme3/scene/shape/AbstractBox.java b/jme3-core/src/main/java/com/jme3/scene/shape/AbstractBox.java index 35f078eeb..ab5db2462 100644 --- a/jme3-core/src/main/java/com/jme3/scene/shape/AbstractBox.java +++ b/jme3-core/src/main/java/com/jme3/scene/shape/AbstractBox.java @@ -149,6 +149,7 @@ public abstract class AbstractBox extends Mesh { duUpdateGeometryNormals(); duUpdateGeometryTextures(); duUpdateGeometryIndices(); + setStatic(); } /** diff --git a/jme3-core/src/main/java/com/jme3/scene/shape/Dome.java b/jme3-core/src/main/java/com/jme3/scene/shape/Dome.java index 3e2cfb031..8060498f9 100644 --- a/jme3-core/src/main/java/com/jme3/scene/shape/Dome.java +++ b/jme3-core/src/main/java/com/jme3/scene/shape/Dome.java @@ -266,7 +266,7 @@ public class Dome extends Mesh { vars.release(); // pole - vb.put(center.x).put(center.y + radius).put(center.z); + vb.put(this.center.x).put(this.center.y + radius).put(this.center.z); nb.put(0).put(insideView ? -1 : 1).put(0); tb.put(0.5f).put(1.0f); diff --git a/jme3-core/src/main/java/com/jme3/shader/DefineList.java b/jme3-core/src/main/java/com/jme3/shader/DefineList.java index 93d4cbeaf..dd605fc7e 100644 --- a/jme3-core/src/main/java/com/jme3/shader/DefineList.java +++ b/jme3-core/src/main/java/com/jme3/shader/DefineList.java @@ -40,7 +40,7 @@ import java.io.IOException; import java.util.Map; import java.util.TreeMap; -public class DefineList implements Savable, Cloneable { +public final class DefineList implements Savable, Cloneable { private static final String ONE = "1"; diff --git a/jme3-core/src/main/java/com/jme3/shader/Glsl100ShaderGenerator.java b/jme3-core/src/main/java/com/jme3/shader/Glsl100ShaderGenerator.java index ed53e89bc..a7a53b915 100644 --- a/jme3-core/src/main/java/com/jme3/shader/Glsl100ShaderGenerator.java +++ b/jme3-core/src/main/java/com/jme3/shader/Glsl100ShaderGenerator.java @@ -127,6 +127,7 @@ public class Glsl100ShaderGenerator extends ShaderGenerator { unIndent(); startCondition(shaderNode.getCondition(), source); source.append(nodeSource); + source.append("\n"); endCondition(shaderNode.getCondition(), source); indent(); } diff --git a/jme3-core/src/main/java/com/jme3/shadow/AbstractShadowRenderer.java b/jme3-core/src/main/java/com/jme3/shadow/AbstractShadowRenderer.java index 5fac9c834..bd70465cb 100644 --- a/jme3-core/src/main/java/com/jme3/shadow/AbstractShadowRenderer.java +++ b/jme3-core/src/main/java/com/jme3/shadow/AbstractShadowRenderer.java @@ -424,7 +424,7 @@ public abstract class AbstractShadowRenderer implements SceneProcessor, Savable renderManager.setCamera(shadowCam, false); renderManager.getRenderer().setFrameBuffer(shadowFB[shadowMapIndex]); - renderManager.getRenderer().clearBuffers(false, true, false); + renderManager.getRenderer().clearBuffers(true, true, true); // render shadow casters to shadow map viewPort.getQueue().renderShadowQueue(shadowMapOccluders, renderManager, shadowCam, true); @@ -459,7 +459,7 @@ public abstract class AbstractShadowRenderer implements SceneProcessor, Savable debug = true; } - abstract void getReceivers(GeometryList lightReceivers); + protected abstract void getReceivers(GeometryList lightReceivers); public void postFrame(FrameBuffer out) { if (skipPostPass) { diff --git a/jme3-core/src/main/java/com/jme3/shadow/BasicShadowRenderer.java b/jme3-core/src/main/java/com/jme3/shadow/BasicShadowRenderer.java index bc4273db7..1410574ea 100644 --- a/jme3-core/src/main/java/com/jme3/shadow/BasicShadowRenderer.java +++ b/jme3-core/src/main/java/com/jme3/shadow/BasicShadowRenderer.java @@ -190,7 +190,7 @@ public class BasicShadowRenderer implements SceneProcessor { renderManager.setForcedMaterial(preshadowMat); r.setFrameBuffer(shadowFB); - r.clearBuffers(false, true, false); + r.clearBuffers(true, true, true); viewPort.getQueue().renderShadowQueue(shadowOccluders, renderManager, shadowCam, true); r.setFrameBuffer(viewPort.getOutputFrameBuffer()); diff --git a/jme3-core/src/main/java/com/jme3/shadow/DirectionalLightShadowRenderer.java b/jme3-core/src/main/java/com/jme3/shadow/DirectionalLightShadowRenderer.java index d0189e854..acf8a9677 100644 --- a/jme3-core/src/main/java/com/jme3/shadow/DirectionalLightShadowRenderer.java +++ b/jme3-core/src/main/java/com/jme3/shadow/DirectionalLightShadowRenderer.java @@ -192,7 +192,7 @@ public class DirectionalLightShadowRenderer extends AbstractShadowRenderer { } @Override - void getReceivers(GeometryList lightReceivers) { + protected void getReceivers(GeometryList lightReceivers) { if (lightReceivers.size()==0) { for (Spatial scene : viewPort.getScenes()) { ShadowUtil.getGeometriesInCamFrustum(scene, viewPort.getCamera(), RenderQueue.ShadowMode.Receive, lightReceivers); diff --git a/jme3-core/src/main/java/com/jme3/shadow/PointLightShadowRenderer.java b/jme3-core/src/main/java/com/jme3/shadow/PointLightShadowRenderer.java index 2976a2460..f4a6455f1 100644 --- a/jme3-core/src/main/java/com/jme3/shadow/PointLightShadowRenderer.java +++ b/jme3-core/src/main/java/com/jme3/shadow/PointLightShadowRenderer.java @@ -139,7 +139,7 @@ public class PointLightShadowRenderer extends AbstractShadowRenderer { } @Override - void getReceivers(GeometryList lightReceivers) { + protected void getReceivers(GeometryList lightReceivers) { lightReceivers.clear(); for (Spatial scene : viewPort.getScenes()) { ShadowUtil.getLitGeometriesInViewPort(scene, viewPort.getCamera(), shadowCams, RenderQueue.ShadowMode.Receive, lightReceivers); diff --git a/jme3-core/src/main/java/com/jme3/shadow/PssmShadowRenderer.java b/jme3-core/src/main/java/com/jme3/shadow/PssmShadowRenderer.java index 182052e13..e06b5c337 100644 --- a/jme3-core/src/main/java/com/jme3/shadow/PssmShadowRenderer.java +++ b/jme3-core/src/main/java/com/jme3/shadow/PssmShadowRenderer.java @@ -450,7 +450,7 @@ public class PssmShadowRenderer implements SceneProcessor { } r.setFrameBuffer(shadowFB[i]); - r.clearBuffers(false, true, false); + r.clearBuffers(true, true, true); // render shadow casters to shadow map viewPort.getQueue().renderShadowQueue(splitOccluders, renderManager, shadowCam, true); diff --git a/jme3-core/src/main/java/com/jme3/shadow/SpotLightShadowRenderer.java b/jme3-core/src/main/java/com/jme3/shadow/SpotLightShadowRenderer.java index dafd25ac4..b291e722e 100644 --- a/jme3-core/src/main/java/com/jme3/shadow/SpotLightShadowRenderer.java +++ b/jme3-core/src/main/java/com/jme3/shadow/SpotLightShadowRenderer.java @@ -151,7 +151,7 @@ public class SpotLightShadowRenderer extends AbstractShadowRenderer { } @Override - void getReceivers(GeometryList lightReceivers) { + protected void getReceivers(GeometryList lightReceivers) { lightReceivers.clear(); Camera[] cameras = new Camera[1]; cameras[0] = shadowCam; diff --git a/jme3-core/src/main/java/com/jme3/system/JmeSystem.java b/jme3-core/src/main/java/com/jme3/system/JmeSystem.java index 1ec695388..51c2173fd 100644 --- a/jme3-core/src/main/java/com/jme3/system/JmeSystem.java +++ b/jme3-core/src/main/java/com/jme3/system/JmeSystem.java @@ -172,15 +172,6 @@ public class JmeSystem { return systemDelegate.getPlatformAssetConfigURL(); } - /** - * @deprecated Directly create an image raster via {@link DefaultImageRaster}. - */ - @Deprecated - public static ImageRaster createImageRaster(Image image, int slice) { - checkDelegate(); - return systemDelegate.createImageRaster(image, slice); - } - /** * Displays an error message to the user in whichever way the context * feels is appropriate. If this is a headless or an offscreen surface diff --git a/jme3-core/src/main/java/com/jme3/system/JmeSystemDelegate.java b/jme3-core/src/main/java/com/jme3/system/JmeSystemDelegate.java index a3f75bd9a..150275d46 100644 --- a/jme3-core/src/main/java/com/jme3/system/JmeSystemDelegate.java +++ b/jme3-core/src/main/java/com/jme3/system/JmeSystemDelegate.java @@ -132,11 +132,6 @@ public abstract class JmeSystemDelegate { return new DesktopAssetManager(null); } - @Deprecated - public final ImageRaster createImageRaster(Image image, int slice) { - return new DefaultImageRaster(image, slice); - } - public abstract void writeImageFile(OutputStream outStream, String format, ByteBuffer imageData, int width, int height) throws IOException; public abstract void showErrorDialog(String message); diff --git a/jme3-core/src/main/java/com/jme3/system/NullContext.java b/jme3-core/src/main/java/com/jme3/system/NullContext.java index f7d4b3d5a..41204e6c9 100644 --- a/jme3-core/src/main/java/com/jme3/system/NullContext.java +++ b/jme3-core/src/main/java/com/jme3/system/NullContext.java @@ -46,6 +46,8 @@ public class NullContext implements JmeContext, Runnable { protected static final Logger logger = Logger.getLogger(NullContext.class.getName()); + protected static final String THREAD_NAME = "jME3 Headless Main"; + protected AtomicBoolean created = new AtomicBoolean(false); protected AtomicBoolean needClose = new AtomicBoolean(false); protected final Object createdLock = new Object(); @@ -150,7 +152,7 @@ public class NullContext implements JmeContext, Runnable { return; } - new Thread(this, "Headless Application Thread").start(); + new Thread(this, THREAD_NAME).start(); if (waitFor) waitFor(true); } diff --git a/jme3-core/src/main/java/com/jme3/texture/FrameBuffer.java b/jme3-core/src/main/java/com/jme3/texture/FrameBuffer.java index ed053339c..bc21fd82b 100644 --- a/jme3-core/src/main/java/com/jme3/texture/FrameBuffer.java +++ b/jme3-core/src/main/java/com/jme3/texture/FrameBuffer.java @@ -72,9 +72,10 @@ import java.util.ArrayList; * @author Kirill Vainer */ public class FrameBuffer extends NativeObject { - public static int SLOT_UNDEF = -1; - public static int SLOT_DEPTH = -100; - public static int SLOT_DEPTH_STENCIL = -101; + + public static final int SLOT_UNDEF = -1; + public static final int SLOT_DEPTH = -100; + public static final int SLOT_DEPTH_STENCIL = -101; private int width = 0; private int height = 0; diff --git a/jme3-core/src/main/java/com/jme3/texture/Image.java b/jme3-core/src/main/java/com/jme3/texture/Image.java index 2bbf746ff..ca9404720 100644 --- a/jme3-core/src/main/java/com/jme3/texture/Image.java +++ b/jme3-core/src/main/java/com/jme3/texture/Image.java @@ -367,7 +367,6 @@ public class Image extends NativeObject implements Savable /*, Cloneable*/ { protected int width, height, depth; protected int[] mipMapSizes; protected ArrayList data; - protected transient Object efficientData; protected int multiSamples = 1; protected ColorSpace colorSpace = null; // protected int mipOffset = 0; @@ -375,7 +374,7 @@ public class Image extends NativeObject implements Savable /*, Cloneable*/ { // attributes relating to GL object protected boolean mipsWereGenerated = false; protected boolean needGeneratedMips = false; - protected final LastTextureState lastTextureState = new LastTextureState(); + protected LastTextureState lastTextureState = new LastTextureState(); /** * Internal use only. @@ -421,7 +420,8 @@ public class Image extends NativeObject implements Savable /*, Cloneable*/ { /** * @return True if the image needs to have mipmaps generated - * for it (as requested by the texture). + * for it (as requested by the texture). This stays true even + * after mipmaps have been generated. */ public boolean isGeneratedMipmapsRequired() { return needGeneratedMips; @@ -434,8 +434,9 @@ public class Image extends NativeObject implements Savable /*, Cloneable*/ { @Override public void setUpdateNeeded() { super.setUpdateNeeded(); - if (!isGeneratedMipmapsRequired() && !hasMipmaps()) { - setNeedGeneratedMipmaps(); + if (isGeneratedMipmapsRequired() && !hasMipmaps()) { + // Mipmaps are no longer valid, since the image was changed. + setMipmapsGenerated(false); } } @@ -488,6 +489,7 @@ public class Image extends NativeObject implements Savable /*, Cloneable*/ { Image clone = (Image) super.clone(); clone.mipMapSizes = mipMapSizes != null ? mipMapSizes.clone() : null; clone.data = data != null ? new ArrayList(data) : null; + clone.lastTextureState = new LastTextureState(); clone.setUpdateNeeded(); return clone; } @@ -527,11 +529,13 @@ public class Image extends NativeObject implements Savable /*, Cloneable*/ { this(); - if (mipMapSizes != null && mipMapSizes.length <= 1) { - mipMapSizes = null; - } else { - needGeneratedMips = false; - mipsWereGenerated = true; + if (mipMapSizes != null) { + if (mipMapSizes.length <= 1) { + mipMapSizes = null; + } else { + needGeneratedMips = false; + mipsWereGenerated = true; + } } setFormat(format); @@ -756,8 +760,6 @@ public class Image extends NativeObject implements Savable /*, Cloneable*/ { */ @Deprecated public void setEfficentData(Object efficientData){ - this.efficientData = efficientData; - setUpdateNeeded(); } /** @@ -765,7 +767,7 @@ public class Image extends NativeObject implements Savable /*, Cloneable*/ { */ @Deprecated public Object getEfficentData(){ - return efficientData; + return null; } /** @@ -787,8 +789,8 @@ public class Image extends NativeObject implements Savable /*, Cloneable*/ { needGeneratedMips = false; mipsWereGenerated = false; } else { - needGeneratedMips = false; - mipsWereGenerated = true; + needGeneratedMips = true; + mipsWereGenerated = false; } setUpdateNeeded(); diff --git a/jme3-core/src/main/java/com/jme3/texture/Texture.java b/jme3-core/src/main/java/com/jme3/texture/Texture.java index b41d2ac10..582d06565 100644 --- a/jme3-core/src/main/java/com/jme3/texture/Texture.java +++ b/jme3-core/src/main/java/com/jme3/texture/Texture.java @@ -488,7 +488,8 @@ public abstract class Texture implements CloneableSmartAsset, Savable, Cloneable /** * @return the anisotropic filtering level for this texture. Default value - * is 1 (no anisotrophy), 2 means x2, 4 is x4, etc. + * is 0 (use value from config), + * 1 means 1x (no anisotrophy), 2 means x2, 4 is x4, etc. */ public int getAnisotropicFilter() { return anisotropicFilter; @@ -499,11 +500,7 @@ public abstract class Texture implements CloneableSmartAsset, Savable, Cloneable * the anisotropic filtering level for this texture. */ public void setAnisotropicFilter(int level) { - if (level < 1) { - anisotropicFilter = 1; - } else { - anisotropicFilter = level; - } + anisotropicFilter = Math.max(0, level); } @Override diff --git a/jme3-core/src/main/java/com/jme3/texture/image/DefaultImageRaster.java b/jme3-core/src/main/java/com/jme3/texture/image/DefaultImageRaster.java index 4cbfc3b57..c79a4675d 100644 --- a/jme3-core/src/main/java/com/jme3/texture/image/DefaultImageRaster.java +++ b/jme3-core/src/main/java/com/jme3/texture/image/DefaultImageRaster.java @@ -44,7 +44,9 @@ public class DefaultImageRaster extends ImageRaster { private final ImageCodec codec; private final int width; private final int height; + private final int offset; private final byte[] temp; + private final boolean convertToLinear; private int slice; private void rangeCheck(int x, int y) { @@ -53,13 +55,40 @@ public class DefaultImageRaster extends ImageRaster { } } - public DefaultImageRaster(Image image, int slice) { + public DefaultImageRaster(Image image, int slice, int mipMapLevel, boolean convertToLinear) { + int[] mipMapSizes = image.getMipMapSizes(); + int availableMips = mipMapSizes != null ? mipMapSizes.length : 1; + + if (mipMapLevel >= availableMips) { + throw new IllegalStateException("Cannot create image raster for mipmap level #" + mipMapLevel + ". " + + "Image only has " + availableMips + " mipmap levels."); + } + + if (image.hasMipmaps()) { + this.width = Math.max(1, image.getWidth() >> mipMapLevel); + this.height = Math.max(1, image.getHeight() >> mipMapLevel); + + int mipOffset = 0; + for (int i = 0; i < mipMapLevel; i++) { + mipOffset += mipMapSizes[i]; + } + + this.offset = mipOffset; + } else { + this.width = image.getWidth(); + this.height = image.getHeight(); + this.offset = 0; + } + this.image = image; this.slice = slice; + + // Conversion to linear only needed if image's color space is sRGB. + this.convertToLinear = convertToLinear && image.getColorSpace() == ColorSpace.sRGB; + this.buffer = image.getData(slice); this.codec = ImageCodec.lookup(image.getFormat()); - this.width = image.getWidth(); - this.height = image.getHeight(); + if (codec instanceof ByteAlignedImageCodec || codec instanceof ByteOffsetImageCodec) { this.temp = new byte[codec.bpp]; } else { @@ -86,6 +115,12 @@ public class DefaultImageRaster extends ImageRaster { public void setPixel(int x, int y, ColorRGBA color) { rangeCheck(x, y); + if (convertToLinear) { + // Input is linear, needs to be converted to sRGB before writing + // into image. + color = color.getAsSrgb(); + } + // Check flags for grayscale if (codec.isGray) { float gray = color.r * 0.27f + color.g * 0.67f + color.b * 0.06f; @@ -113,7 +148,7 @@ public class DefaultImageRaster extends ImageRaster { components[3] = Math.min( (int) (color.b * codec.maxBlue + 0.5f), codec.maxBlue); break; } - codec.writeComponents(getBuffer(), x, y, width, 0, components, temp); + codec.writeComponents(getBuffer(), x, y, width, offset, components, temp); image.setUpdateNeeded(); } @@ -128,7 +163,7 @@ public class DefaultImageRaster extends ImageRaster { public ColorRGBA getPixel(int x, int y, ColorRGBA store) { rangeCheck(x, y); - codec.readComponents(getBuffer(), x, y, width, 0, components, temp); + codec.readComponents(getBuffer(), x, y, width, offset, components, temp); if (store == null) { store = new ColorRGBA(); } @@ -169,6 +204,12 @@ public class DefaultImageRaster extends ImageRaster { store.a = 1; } } + + if (convertToLinear) { + // Input image is sRGB, need to convert to linear. + store.setAsSrgb(store.r, store.g, store.b, store.a); + } + return store; } } diff --git a/jme3-core/src/main/java/com/jme3/texture/image/ImageRaster.java b/jme3-core/src/main/java/com/jme3/texture/image/ImageRaster.java index b4e583c35..92bbb3315 100644 --- a/jme3-core/src/main/java/com/jme3/texture/image/ImageRaster.java +++ b/jme3-core/src/main/java/com/jme3/texture/image/ImageRaster.java @@ -71,21 +71,42 @@ public abstract class ImageRaster { * @param image The image to read / write to. * @param slice Which slice to use. Only applies to 3D images, 2D image * arrays or cubemaps. + * @param mipMapLevel The mipmap level to read / write to. To access levels + * other than 0, the image must have + * {@link Image#setMipMapSizes(int[]) mipmap sizes} set. + * @param convertToLinear If true, the application expects read or written + * colors to be in linear color space (ImageRaster will + * automatically perform a conversion as needed). If false, the application expects + * colors to be in the image's native {@link Image#getColorSpace() color space}. + * @return An ImageRaster to read / write to the image. + */ + public static ImageRaster create(Image image, int slice, int mipMapLevel, boolean convertToLinear) { + return new DefaultImageRaster(image, slice, mipMapLevel, convertToLinear); + } + + /** + * Create new image reader / writer. + * + * @param image The image to read / write to. + * @param slice Which slice to use. Only applies to 3D images, 2D image + * arrays or cubemaps. + * @return An ImageRaster to read / write to the image. */ public static ImageRaster create(Image image, int slice) { - return JmeSystem.createImageRaster(image, slice); + return create(image, slice, 0, false); } /** * Create new image reader / writer for 2D images. * * @param image The image to read / write to. + * @return An ImageRaster to read / write to the image. */ public static ImageRaster create(Image image) { if (image.getData().size() > 1) { throw new IllegalStateException("Use constructor that takes slices argument to read from multislice image"); } - return JmeSystem.createImageRaster(image, 0); + return create(image, 0, 0, false); } public ImageRaster() { diff --git a/jme3-core/src/main/java/com/jme3/util/IntMap.java b/jme3-core/src/main/java/com/jme3/util/IntMap.java index fed91be06..38ffb2431 100644 --- a/jme3-core/src/main/java/com/jme3/util/IntMap.java +++ b/jme3-core/src/main/java/com/jme3/util/IntMap.java @@ -34,6 +34,7 @@ package com.jme3.util; import com.jme3.util.IntMap.Entry; import java.util.Iterator; import java.util.Map; +import java.util.NoSuchElementException; /** * Similar to a {@link Map} except that ints are used as keys. @@ -234,7 +235,7 @@ public final class IntMap implements Iterable>, Cloneable { public Entry next() { if (el >= size) - throw new IllegalStateException("No more elements!"); + throw new NoSuchElementException("No more elements!"); if (cur != null){ Entry e = cur; diff --git a/jme3-core/src/main/java/com/jme3/util/MaterialDebugAppState.java b/jme3-core/src/main/java/com/jme3/util/MaterialDebugAppState.java index 1c512e41b..6197aca35 100644 --- a/jme3-core/src/main/java/com/jme3/util/MaterialDebugAppState.java +++ b/jme3-core/src/main/java/com/jme3/util/MaterialDebugAppState.java @@ -36,7 +36,7 @@ import com.jme3.app.state.AbstractAppState; import com.jme3.app.state.AppStateManager; import com.jme3.asset.AssetInfo; import com.jme3.asset.AssetKey; -import com.jme3.asset.DesktopAssetManager; +import com.jme3.asset.AssetManager; import com.jme3.asset.plugins.UrlAssetInfo; import com.jme3.input.InputManager; import com.jme3.input.controls.ActionListener; @@ -96,7 +96,7 @@ import java.util.logging.Logger; public class MaterialDebugAppState extends AbstractAppState { private RenderManager renderManager; - private DesktopAssetManager assetManager; + private AssetManager assetManager; private InputManager inputManager; private List bindings = new ArrayList(); private Map> fileTriggers = new HashMap> (); @@ -105,7 +105,7 @@ public class MaterialDebugAppState extends AbstractAppState { @Override public void initialize(AppStateManager stateManager, Application app) { renderManager = app.getRenderManager(); - assetManager = (DesktopAssetManager) app.getAssetManager(); + assetManager = app.getAssetManager(); inputManager = app.getInputManager(); for (Binding binding : bindings) { bind(binding); @@ -197,7 +197,7 @@ public class MaterialDebugAppState extends AbstractAppState { public Material reloadMaterial(Material mat) { //clear the entire cache, there might be more clever things to do, like clearing only the matdef, and the associated shaders. - ((DesktopAssetManager) assetManager).clearCache(); + assetManager.clearCache(); //creating a dummy mat with the mat def of the mat to reload Material dummy = new Material(mat.getMaterialDef()); diff --git a/jme3-core/src/main/java/com/jme3/util/MipMapGenerator.java b/jme3-core/src/main/java/com/jme3/util/MipMapGenerator.java new file mode 100644 index 000000000..3ac6a7ecd --- /dev/null +++ b/jme3-core/src/main/java/com/jme3/util/MipMapGenerator.java @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2009-2012 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.util; + +import com.jme3.math.ColorRGBA; +import com.jme3.math.FastMath; +import com.jme3.texture.Image; +import com.jme3.texture.Image.Format; +import com.jme3.texture.image.ImageRaster; +import java.nio.ByteBuffer; +import java.util.ArrayList; + +public class MipMapGenerator { + + private MipMapGenerator() { + } + + public static Image scaleImage(Image inputImage, int outputWidth, int outputHeight) { + int size = outputWidth * outputHeight * inputImage.getFormat().getBitsPerPixel() / 8; + ByteBuffer buffer = BufferUtils.createByteBuffer(size); + Image outputImage = new Image(inputImage.getFormat(), + outputWidth, + outputHeight, + buffer, + inputImage.getColorSpace()); + + ImageRaster input = ImageRaster.create(inputImage, 0, 0, false); + ImageRaster output = ImageRaster.create(outputImage, 0, 0, false); + + float xRatio = ((float)(input.getWidth() - 1)) / output.getWidth(); + float yRatio = ((float)(input.getHeight() - 1)) / output.getHeight(); + + ColorRGBA outputColor = new ColorRGBA(); + ColorRGBA bottomLeft = new ColorRGBA(); + ColorRGBA bottomRight = new ColorRGBA(); + ColorRGBA topLeft = new ColorRGBA(); + ColorRGBA topRight = new ColorRGBA(); + + for (int y = 0; y < outputHeight; y++) { + for (int x = 0; x < outputWidth; x++) { + float x2f = x * xRatio; + float y2f = y * yRatio; + + int x2 = (int)x2f; + int y2 = (int)y2f; + + float xDiff = x2f - x2; + float yDiff = y2f - y2; + + input.getPixel(x2, y2, bottomLeft); + input.getPixel(x2 + 1, y2, bottomRight); + input.getPixel(x2, y2 + 1, topLeft); + input.getPixel(x2 + 1, y2 + 1, topRight); + + bottomLeft.multLocal( (1f - xDiff) * (1f - yDiff) ); + bottomRight.multLocal( (xDiff) * (1f - yDiff) ); + topLeft.multLocal( (1f - xDiff) * (yDiff) ); + topRight.multLocal( (xDiff) * (yDiff) ); + + outputColor.set(bottomLeft).addLocal(bottomRight) + .addLocal(topLeft).addLocal(topRight); + + output.setPixel(x, y, outputColor); + } + } + return outputImage; + } + + public static Image resizeToPowerOf2(Image original){ + int potWidth = FastMath.nearestPowerOfTwo(original.getWidth()); + int potHeight = FastMath.nearestPowerOfTwo(original.getHeight()); + return scaleImage(original, potWidth, potHeight); + } + + public static void generateMipMaps(Image image){ + int width = image.getWidth(); + int height = image.getHeight(); + + Image current = image; + ArrayList output = new ArrayList(); + int totalSize = 0; + + while (height >= 1 || width >= 1){ + output.add(current.getData(0)); + totalSize += current.getData(0).capacity(); + + if (height == 1 || width == 1) { + break; + } + + height /= 2; + width /= 2; + + current = scaleImage(current, width, height); + } + + ByteBuffer combinedData = BufferUtils.createByteBuffer(totalSize); + int[] mipSizes = new int[output.size()]; + for (int i = 0; i < output.size(); i++){ + ByteBuffer data = output.get(i); + data.clear(); + combinedData.put(data); + mipSizes[i] = data.capacity(); + } + combinedData.flip(); + + // insert mip data into image + image.setData(0, combinedData); + image.setMipMapSizes(mipSizes); + } +} diff --git a/jme3-core/src/main/java/com/jme3/util/TangentBinormalGenerator.java b/jme3-core/src/main/java/com/jme3/util/TangentBinormalGenerator.java index ae82b3422..5e85378ff 100644 --- a/jme3-core/src/main/java/com/jme3/util/TangentBinormalGenerator.java +++ b/jme3-core/src/main/java/com/jme3/util/TangentBinormalGenerator.java @@ -274,11 +274,9 @@ public class TangentBinormalGenerator { triData.setIndex(index); triData.triangleOffset = i * 3 ; } - if (triData != null) { - vertices.get(index[0]).triangles.add(triData); - vertices.get(index[1]).triangles.add(triData); - vertices.get(index[2]).triangles.add(triData); - } + vertices.get(index[0]).triangles.add(triData); + vertices.get(index[1]).triangles.add(triData); + vertices.get(index[2]).triangles.add(triData); } return vertices; @@ -483,7 +481,7 @@ public class TangentBinormalGenerator { boolean isDegenerate = isDegenerateTriangle(v[0], v[1], v[2]); TriangleData triData = processTriangle(index, v, t); - if (triData != null && !isDegenerate) { + if (!isDegenerate) { vertices.get(index[0]).triangles.add(triData); vertices.get(index[1]).triangles.add(triData); vertices.get(index[2]).triangles.add(triData); @@ -529,11 +527,9 @@ public class TangentBinormalGenerator { populateFromBuffer(t[2], textureBuffer, index[2]); TriangleData triData = processTriangle(index, v, t); - if (triData != null) { - vertices.get(index[0]).triangles.add(triData); - vertices.get(index[1]).triangles.add(triData); - vertices.get(index[2]).triangles.add(triData); - } + vertices.get(index[0]).triangles.add(triData); + vertices.get(index[1]).triangles.add(triData); + vertices.get(index[2]).triangles.add(triData); Vector3f vTemp = v[1]; v[1] = v[2]; @@ -616,9 +612,9 @@ public class TangentBinormalGenerator { normal.normalizeLocal(); return new TriangleData( - tangent, - binormal, - normal); + tangent.clone(), + binormal.clone(), + normal.clone()); } finally { tmp.release(); } diff --git a/jme3-core/src/main/java/com/jme3/util/blockparser/BlockLanguageParser.java b/jme3-core/src/main/java/com/jme3/util/blockparser/BlockLanguageParser.java index 16968aad2..7718a0f4b 100644 --- a/jme3-core/src/main/java/com/jme3/util/blockparser/BlockLanguageParser.java +++ b/jme3-core/src/main/java/com/jme3/util/blockparser/BlockLanguageParser.java @@ -71,7 +71,7 @@ public class BlockLanguageParser { private void load(InputStream in) throws IOException{ reset(); - reader = new InputStreamReader(in); + reader = new InputStreamReader(in, "UTF-8"); StringBuilder buffer = new StringBuilder(); boolean insideComment = false; diff --git a/jme3-core/src/main/resources/Common/MatDefs/Light/Lighting.frag b/jme3-core/src/main/resources/Common/MatDefs/Light/Lighting.frag index 107597047..d2ade5199 100644 --- a/jme3-core/src/main/resources/Common/MatDefs/Light/Lighting.frag +++ b/jme3-core/src/main/resources/Common/MatDefs/Light/Lighting.frag @@ -37,6 +37,7 @@ varying vec3 SpecularSum; #endif #if (defined(PARALLAXMAP) || (defined(NORMALMAP_PARALLAX) && defined(NORMALMAP))) && !defined(VERTEX_LIGHTING) uniform float m_ParallaxHeight; + varying vec3 vViewDirPrlx; #endif #ifdef LIGHTMAP @@ -78,18 +79,18 @@ void main(){ #ifdef STEEP_PARALLAX #ifdef NORMALMAP_PARALLAX //parallax map is stored in the alpha channel of the normal map - newTexCoord = steepParallaxOffset(m_NormalMap, vViewDir, texCoord, m_ParallaxHeight); + newTexCoord = steepParallaxOffset(m_NormalMap, vViewDirPrlx, texCoord, m_ParallaxHeight); #else //parallax map is a texture - newTexCoord = steepParallaxOffset(m_ParallaxMap, vViewDir, texCoord, m_ParallaxHeight); + newTexCoord = steepParallaxOffset(m_ParallaxMap, vViewDirPrlx, texCoord, m_ParallaxHeight); #endif #else #ifdef NORMALMAP_PARALLAX //parallax map is stored in the alpha channel of the normal map - newTexCoord = classicParallaxOffset(m_NormalMap, vViewDir, texCoord, m_ParallaxHeight); + newTexCoord = classicParallaxOffset(m_NormalMap, vViewDirPrlx, texCoord, m_ParallaxHeight); #else //parallax map is a texture - newTexCoord = classicParallaxOffset(m_ParallaxMap, vViewDir, texCoord, m_ParallaxHeight); + newTexCoord = classicParallaxOffset(m_ParallaxMap, vViewDirPrlx, texCoord, m_ParallaxHeight); #endif #endif #else diff --git a/jme3-core/src/main/resources/Common/MatDefs/Light/Lighting.j3md b/jme3-core/src/main/resources/Common/MatDefs/Light/Lighting.j3md index df841ddde..0e9e9850b 100644 --- a/jme3-core/src/main/resources/Common/MatDefs/Light/Lighting.j3md +++ b/jme3-core/src/main/resources/Common/MatDefs/Light/Lighting.j3md @@ -7,7 +7,7 @@ MaterialDef Phong Lighting { Boolean VertexLighting // Alpha threshold for fragment discarding - Float AlphaDiscardThreshold (AlphaTestFallOff) + Float AlphaDiscardThreshold // Use the provided ambient, diffuse, and specular colors Boolean UseMaterialColors @@ -16,16 +16,16 @@ MaterialDef Phong Lighting { Boolean UseVertexColor // Ambient color - Color Ambient (MaterialAmbient) + Color Ambient // Diffuse color - Color Diffuse (MaterialDiffuse) + Color Diffuse // Specular color - Color Specular (MaterialSpecular) + Color Specular // Specular power/shininess - Float Shininess (MaterialShininess) : 1 + Float Shininess : 1 // Diffuse map Texture2D DiffuseMap diff --git a/jme3-core/src/main/resources/Common/MatDefs/Light/Lighting.vert b/jme3-core/src/main/resources/Common/MatDefs/Light/Lighting.vert index 3ee6f38c6..df441ed59 100644 --- a/jme3-core/src/main/resources/Common/MatDefs/Light/Lighting.vert +++ b/jme3-core/src/main/resources/Common/MatDefs/Light/Lighting.vert @@ -48,6 +48,10 @@ varying vec3 lightVec; uniform vec4 g_LightDirection; #endif +#if (defined(PARALLAXMAP) || (defined(NORMALMAP_PARALLAX) && defined(NORMALMAP))) && !defined(VERTEX_LIGHTING) + varying vec3 vViewDirPrlx; +#endif + #ifdef USE_REFLECTION uniform vec3 g_CameraPosition; @@ -107,17 +111,25 @@ void main(){ wvLightPos.w = g_LightPosition.w; vec4 lightColor = g_LightColor; - #if defined(NORMALMAP) && !defined(VERTEX_LIGHTING) + #if (defined(NORMALMAP) || defined(PARALLAXMAP)) && !defined(VERTEX_LIGHTING) vec3 wvTangent = normalize(TransformNormal(modelSpaceTan)); vec3 wvBinormal = cross(wvNormal, wvTangent); mat3 tbnMat = mat3(wvTangent, wvBinormal * inTangent.w,wvNormal); + #endif - vViewDir = -wvPosition * tbnMat; + #if defined(NORMALMAP) && !defined(VERTEX_LIGHTING) + vViewDir = -wvPosition * tbnMat; + #if (defined(PARALLAXMAP) || (defined(NORMALMAP_PARALLAX) && defined(NORMALMAP))) + vViewDirPrlx = vViewDir; + #endif lightComputeDir(wvPosition, lightColor.w, wvLightPos, vLightDir, lightVec); vLightDir.xyz = (vLightDir.xyz * tbnMat).xyz; #elif !defined(VERTEX_LIGHTING) vNormal = wvNormal; vViewDir = viewDir; + #if defined(PARALLAXMAP) + vViewDirPrlx = -wvPosition * tbnMat; + #endif lightComputeDir(wvPosition, lightColor.w, wvLightPos, vLightDir, lightVec); #endif @@ -126,7 +138,8 @@ void main(){ DiffuseSum = m_Diffuse * vec4(lightColor.rgb, 1.0); SpecularSum = (m_Specular * lightColor).rgb; #else - AmbientSum = g_AmbientLightColor.rgb; // Default: ambient color is dark gray + // Defaults: Ambient and diffuse are white, specular is black. + AmbientSum = g_AmbientLightColor.rgb; DiffuseSum = vec4(lightColor.rgb, 1.0); SpecularSum = vec3(0.0); #endif diff --git a/jme3-core/src/main/resources/Common/MatDefs/Light/SPLighting.frag b/jme3-core/src/main/resources/Common/MatDefs/Light/SPLighting.frag index 5d207cf83..254806d87 100644 --- a/jme3-core/src/main/resources/Common/MatDefs/Light/SPLighting.frag +++ b/jme3-core/src/main/resources/Common/MatDefs/Light/SPLighting.frag @@ -17,10 +17,7 @@ varying vec3 SpecularSum; #ifndef VERTEX_LIGHTING uniform mat4 g_ViewMatrix; uniform vec4 g_LightData[NB_LIGHTS]; - varying vec3 vPos; -#else - varying vec3 specularAccum; - varying vec4 diffuseAccum; + varying vec3 vPos; #endif #ifdef DIFFUSEMAP @@ -72,17 +69,19 @@ uniform float m_Shininess; #endif void main(){ - #ifdef NORMALMAP - mat3 tbnMat = mat3(normalize(vTangent.xyz) , normalize(vBinormal.xyz) , normalize(vNormal.xyz)); + #if !defined(VERTEX_LIGHTING) + #if defined(NORMALMAP) + mat3 tbnMat = mat3(normalize(vTangent.xyz) , normalize(vBinormal.xyz) , normalize(vNormal.xyz)); - if (!gl_FrontFacing) - { - tbnMat[2] = -tbnMat[2]; - } + if (!gl_FrontFacing) + { + tbnMat[2] = -tbnMat[2]; + } - vec3 viewDir = normalize(-vPos.xyz * tbnMat); - #else - vec3 viewDir = normalize(-vPos.xyz); + vec3 viewDir = normalize(-vPos.xyz * tbnMat); + #else + vec3 viewDir = normalize(-vPos.xyz); + #endif #endif vec2 newTexCoord; @@ -165,10 +164,9 @@ void main(){ #endif #ifdef VERTEX_LIGHTING - gl_FragColor.rgb = AmbientSum * diffuseColor.rgb - +diffuseAccum.rgb *diffuseColor.rgb - +specularAccum.rgb * specularColor.rgb; - gl_FragColor.a=1.0; + gl_FragColor.rgb = AmbientSum.rgb * diffuseColor.rgb + + DiffuseSum.rgb * diffuseColor.rgb + + SpecularSum.rgb * specularColor.rgb; #else int i = 0; diff --git a/jme3-core/src/main/resources/Common/MatDefs/Light/SPLighting.vert b/jme3-core/src/main/resources/Common/MatDefs/Light/SPLighting.vert index b0d8828a5..1fde8e13d 100644 --- a/jme3-core/src/main/resources/Common/MatDefs/Light/SPLighting.vert +++ b/jme3-core/src/main/resources/Common/MatDefs/Light/SPLighting.vert @@ -43,8 +43,9 @@ attribute vec3 inNormal; varying vec3 vBinormal; #endif #else - varying vec3 specularAccum; - varying vec4 diffuseAccum; + #ifdef COLORRAMP + uniform sampler2D m_ColorRamp; + #endif #endif #ifdef USE_REFLECTION @@ -117,6 +118,7 @@ void main(){ SpecularSum = m_Specular.rgb; DiffuseSum = m_Diffuse; #else + // Defaults: Ambient and diffuse are white, specular is black. AmbientSum = g_AmbientLightColor.rgb; SpecularSum = vec3(0.0); DiffuseSum = vec4(1.0); @@ -127,14 +129,13 @@ void main(){ #endif #ifdef VERTEX_LIGHTING int i = 0; - diffuseAccum = vec4(0.0); - specularAccum = vec3(0.0); + vec3 diffuseAccum = vec3(0.0); + vec3 specularAccum = vec3(0.0); vec4 diffuseColor; vec3 specularColor; for (int i =0;i < NB_LIGHTS; i+=3){ vec4 lightColor = g_LightData[i]; vec4 lightData1 = g_LightData[i+1]; - DiffuseSum = vec4(1.0); #ifdef MATERIAL_COLORS diffuseColor = m_Diffuse * vec4(lightColor.rgb, 1.0); specularColor = m_Specular.rgb * lightColor.rgb; @@ -159,16 +160,19 @@ void main(){ #if __VERSION__ >= 110 } #endif - vec2 v = computeLighting(wvNormal, viewDir, lightDir.xyz, lightDir.w * spotFallOff, m_Shininess); + vec2 light = computeLighting(wvNormal, viewDir, lightDir.xyz, lightDir.w * spotFallOff, m_Shininess); #ifdef COLORRAMP - diffuseAccum += texture2D(m_ColorRamp, vec2(light.x, 0.0)).rgb * diffuseColor; + diffuseAccum += texture2D(m_ColorRamp, vec2(light.x, 0.0)).rgb * diffuseColor.rgb; specularAccum += texture2D(m_ColorRamp, vec2(light.y, 0.0)).rgb * specularColor; #else - diffuseAccum += v.x * diffuseColor; - specularAccum += v.y * specularColor; + diffuseAccum += light.x * diffuseColor.rgb; + specularAccum += light.y * specularColor; #endif } + + DiffuseSum.rgb *= diffuseAccum.rgb; + SpecularSum.rgb *= specularAccum.rgb; #endif diff --git a/jme3-core/src/main/resources/Common/MatDefs/Misc/UnshadedNodes.j3md b/jme3-core/src/main/resources/Common/MatDefs/Misc/UnshadedNodes.j3md index f9fb05288..b35c17a9d 100644 --- a/jme3-core/src/main/resources/Common/MatDefs/Misc/UnshadedNodes.j3md +++ b/jme3-core/src/main/resources/Common/MatDefs/Misc/UnshadedNodes.j3md @@ -1,97 +1,121 @@ -MaterialDef UnshadedNodes { - - MaterialParameters { - Texture2D ColorMap - Texture2D LightMap - Color Color (Color) - Boolean VertexColor (UseVertexColor) - Boolean SeparateTexCoord - - // Alpha threshold for fragment discarding - Float AlphaDiscardThreshold (AlphaTestFallOff) - - // For hardware skinning - Int NumberOfBones - Matrix4Array BoneMatrices - - } - - Technique { - - WorldParameters { - WorldViewProjectionMatrix - //used for fog - WorldViewMatrix - } - - VertexShaderNodes{ - ShaderNode GpuSkinning{ - Definition: BasicGPUSkinning : Common/MatDefs/ShaderNodes/HardwareSkinning/HardwareSkinning.j3sn - Condition : NumberOfBones - InputMapping{ - modelPosition = Global.position; - boneMatrices = MatParam.BoneMatrices - boneWeight = Attr.inHWBoneWeight - boneIndex = Attr.inHWBoneIndex - } - OutputMapping{ - Global.position = modModelPosition - } - } - ShaderNode UnshadedVert{ - Definition: CommonVert : Common/MatDefs/ShaderNodes/Common/CommonVert.j3sn - InputMapping{ - worldViewProjectionMatrix = WorldParam.WorldViewProjectionMatrix - modelPosition = Global.position.xyz - texCoord1 = Attr.inTexCoord: ColorMap || (LightMap && !SeparateTexCoord) - texCoord2 = Attr.inTexCoord2: SeparateTexCoord - vertColor = Attr.inColor: VertexColor - } - OutputMapping{ - Global.position = projPosition - } - } - } - FragmentShaderNodes{ - ShaderNode UnshadedFrag{ - Definition: Unshaded : Common/MatDefs/ShaderNodes/Common/Unshaded.j3sn - InputMapping{ - texCoord = UnshadedVert.texCoord1: ColorMap - vertColor = UnshadedVert.vertColor: VertexColor - matColor = MatParam.Color: Color - colorMap = MatParam.ColorMap: ColorMap - color = Global.outColor - } - OutputMapping{ - Global.outColor = color - } - } - - ShaderNode AlphaDiscardThreshold{ - Definition: AlphaDiscard : Common/MatDefs/ShaderNodes/Basic/AlphaDiscard.j3sn - Condition : AlphaDiscardThreshold - InputMapping{ - alpha = Global.outColor.a - threshold = MatParam.AlphaDiscardThreshold - } - } - ShaderNode LightMap{ - Definition: LightMapping : Common/MatDefs/ShaderNodes/LightMapping/LightMapping.j3sn - Condition: LightMap - InputMapping{ - texCoord = UnshadedVert.texCoord1: !SeparateTexCoord - texCoord = UnshadedVert.texCoord2: SeparateTexCoord - lightMap = MatParam.LightMap - color = Global.outColor - } - OutputMapping{ - Global.outColor = color - } - } - - } - - } - - +MaterialDef UnshadedNodes { + MaterialParameters { + Texture2D ColorMap + Texture2D LightMap + Color Color (Color) + Boolean VertexColor (UseVertexColor) + Boolean SeparateTexCoord + Float AlphaDiscardThreshold (AlphaTestFallOff) + Int NumberOfBones + Matrix4Array BoneMatrices + } + Technique { + WorldParameters { + WorldViewProjectionMatrix + WorldViewMatrix + } + VertexShaderNodes { + ShaderNode GpuSkinning { + Definition : BasicGPUSkinning : Common/MatDefs/ShaderNodes/HardwareSkinning/HardwareSkinning.j3sn + Condition : NumberOfBones + InputMapping { + modelPosition = Global.position + boneMatrices = MatParam.BoneMatrices + boneWeight = Attr.inHWBoneWeight + boneIndex = Attr.inHWBoneIndex + } + OutputMapping { + Global.position = modModelPosition + } + } + ShaderNode UnshadedVert { + Definition : CommonVert : Common/MatDefs/ShaderNodes/Common/CommonVert.j3sn + InputMapping { + worldViewProjectionMatrix = WorldParam.WorldViewProjectionMatrix + modelPosition = Global.position.xyz + texCoord1 = Attr.inTexCoord : ColorMap || (LightMap && !SeparateTexCoord) + texCoord2 = Attr.inTexCoord2 : SeparateTexCoord + vertColor = Attr.inColor : VertexColor + } + OutputMapping { + Global.position = projPosition + } + } + } + FragmentShaderNodes { + ShaderNode MatColorMult { + Definition : ColorMult : Common/MatDefs/ShaderNodes/Basic/ColorMult.j3sn + InputMappings { + color1 = MatParam.Color + color2 = Global.outColor + } + OutputMappings { + Global.outColor = outColor + } + Condition : Color + } + ShaderNode VertColorMult { + Definition : ColorMult : Common/MatDefs/ShaderNodes/Basic/ColorMult.j3sn + InputMappings { + color1 = UnshadedVert.vertColor + color2 = Global.outColor + } + OutputMappings { + Global.outColor = outColor + } + Condition : VertexColor + } + ShaderNode ColorMapTF { + Definition : TextureFetch : Common/MatDefs/ShaderNodes/Basic/TextureFetch.j3sn + InputMappings { + texCoord = UnshadedVert.texCoord1 + textureMap = MatParam.ColorMap + } + OutputMappings { + } + Condition : ColorMap + } + ShaderNode ColorMapMult { + Definition : ColorMult : Common/MatDefs/ShaderNodes/Basic/ColorMult.j3sn + InputMappings { + color1 = ColorMapTF.outColor + color2 = Global.outColor + } + OutputMappings { + Global.outColor = outColor + } + Condition : ColorMap + } + ShaderNode AlphaDiscardThreshold { + Definition : AlphaDiscard : Common/MatDefs/ShaderNodes/Basic/AlphaDiscard.j3sn + Condition : AlphaDiscardThreshold + InputMapping { + alpha = Global.outColor.a + threshold = MatParam.AlphaDiscardThreshold + } + } + ShaderNode LightMapTF { + Definition : TextureFetch : Common/MatDefs/ShaderNodes/Basic/TextureFetch.j3sn + InputMappings { + textureMap = MatParam.LightMap + texCoord = UnshadedVert.texCoord2 : SeparateTexCoord + texCoord = UnshadedVert.texCoord1 : !SeparateTexCoord + } + OutputMappings { + } + Condition : LightMap + } + ShaderNode LightMapMult { + Definition : ColorMult : Common/MatDefs/ShaderNodes/Basic/ColorMult.j3sn + OutputMappings { + Global.outColor = outColor + } + InputMappings { + color1 = LightMapTF.outColor + color2 = Global.outColor + } + Condition : LightMap + } + } + } } \ No newline at end of file diff --git a/jme3-core/src/main/resources/Common/MatDefs/ShaderNodes/Basic/TextureFetch.j3sn b/jme3-core/src/main/resources/Common/MatDefs/ShaderNodes/Basic/TextureFetch.j3sn index b4ccd3640..034fcd116 100644 --- a/jme3-core/src/main/resources/Common/MatDefs/ShaderNodes/Basic/TextureFetch.j3sn +++ b/jme3-core/src/main/resources/Common/MatDefs/ShaderNodes/Basic/TextureFetch.j3sn @@ -2,14 +2,15 @@ ShaderNodeDefinitions{ ShaderNodeDefinition TextureFetch { Type: Fragment Shader GLSL100: Common/MatDefs/ShaderNodes/Basic/texture.frag + Shader GLSL150: Common/MatDefs/ShaderNodes/Basic/texture15.frag Documentation{ Fetches a color value in the given texture acording to given texture coordinates - @input texture the texture to read + @input textureMap the texture to read @input texCoord the texture coordinates @output outColor the fetched color } Input { - sampler2D texture + sampler2D textureMap vec2 texCoord } Output { diff --git a/jme3-core/src/main/resources/Common/MatDefs/ShaderNodes/Basic/texture.frag b/jme3-core/src/main/resources/Common/MatDefs/ShaderNodes/Basic/texture.frag index eb83a7b1f..163fbc123 100644 --- a/jme3-core/src/main/resources/Common/MatDefs/ShaderNodes/Basic/texture.frag +++ b/jme3-core/src/main/resources/Common/MatDefs/ShaderNodes/Basic/texture.frag @@ -1,3 +1,3 @@ void main(){ - outColor = texture2D(texture,texCoord); + outColor = texture2D(textureMap,texCoord); } \ No newline at end of file diff --git a/jme3-core/src/main/resources/Common/MatDefs/ShaderNodes/Basic/texture15.frag b/jme3-core/src/main/resources/Common/MatDefs/ShaderNodes/Basic/texture15.frag new file mode 100644 index 000000000..2ece0a646 --- /dev/null +++ b/jme3-core/src/main/resources/Common/MatDefs/ShaderNodes/Basic/texture15.frag @@ -0,0 +1,3 @@ +void main(){ + outColor = texture(textureMap,texCoord); +} \ No newline at end of file diff --git a/jme3-core/src/main/resources/Common/ShaderLib/GLSL150Compat.glsllib b/jme3-core/src/main/resources/Common/ShaderLib/GLSL150Compat.glsllib new file mode 100644 index 000000000..336490696 --- /dev/null +++ b/jme3-core/src/main/resources/Common/ShaderLib/GLSL150Compat.glsllib @@ -0,0 +1,14 @@ +#if _VERSION_ >= 150 +out vec4 outFragColor; +# define texture1D texture +# define texture2D texture +# define texture3D texture +# define texture2DLod texture +# if defined VERTEX_SHADER +# define varying out +# define attribute in +# elif defined FRAGMENT_SHADER +# define varying in +# define gl_FragColor outFragColor +# endif +#endif \ No newline at end of file diff --git a/jme3-core/src/main/resources/Common/ShaderLib/Lighting.glsllib b/jme3-core/src/main/resources/Common/ShaderLib/Lighting.glsllib index 6ac1fce5c..fb8f40524 100644 --- a/jme3-core/src/main/resources/Common/ShaderLib/Lighting.glsllib +++ b/jme3-core/src/main/resources/Common/ShaderLib/Lighting.glsllib @@ -30,6 +30,14 @@ float computeSpotFalloff(in vec4 lightDirection, in vec3 lightVector){ float innerAngleCos = floor(lightDirection.w) * 0.001; float outerAngleCos = fract(lightDirection.w); float innerMinusOuter = innerAngleCos - outerAngleCos; - return clamp((curAngleCos - outerAngleCos) / innerMinusOuter, step(lightDirection.w, 0.001), 1.0); + float falloff = clamp((curAngleCos - outerAngleCos) / innerMinusOuter, step(lightDirection.w, 0.001), 1.0); + +#ifdef SRGB + // Use quadratic falloff (notice the ^4) + return pow(clamp((curAngleCos - outerAngleCos) / innerMinusOuter, 0.0, 1.0), 4.0); +#else + // Use linear falloff + return falloff; +#endif } diff --git a/jme3-core/src/main/resources/Common/ShaderLib/MultiSample.glsllib b/jme3-core/src/main/resources/Common/ShaderLib/MultiSample.glsllib index bea736f9d..3b06e6441 100644 --- a/jme3-core/src/main/resources/Common/ShaderLib/MultiSample.glsllib +++ b/jme3-core/src/main/resources/Common/ShaderLib/MultiSample.glsllib @@ -15,8 +15,14 @@ uniform int m_NumSamplesDepth; #define DEPTHTEXTURE sampler2D #endif -// NOTE: Only define multisample functions if multisample is available and is being used! -#if defined(GL_ARB_texture_multisample) && (defined(RESOLVE_MS) || defined(RESOLVE_DEPTH_MS)) +#if __VERSION__ >= 150 + #define TEXTURE texture +#else + #define TEXTURE texture2D +#endif + +// NOTE: Only define multisample functions if multisample is available +#if defined(GL_ARB_texture_multisample) vec4 textureFetch(in sampler2DMS tex,in vec2 texC, in int numSamples){ ivec2 iTexC = ivec2(texC * vec2(textureSize(tex))); vec4 color = vec4(0.0); @@ -44,40 +50,21 @@ vec4 getDepth(in sampler2DMS tex,in vec2 texC){ return textureFetch(tex,texC,m_NumSamplesDepth); } -#elif __VERSION__ >= 150 - -vec4 fetchTextureSample(in sampler2D tex,in vec2 texC,in int sample){ - return texture(tex,texC); -} - -vec4 getColor(in sampler2D tex, in vec2 texC){ - return texture(tex,texC); -} - -vec4 getColorSingle(in sampler2D tex, in vec2 texC){ - return texture(tex, texC); -} - -vec4 getDepth(in sampler2D tex,in vec2 texC){ - return texture(tex,texC); -} - -#else +#endif vec4 fetchTextureSample(in sampler2D tex,in vec2 texC,in int sample){ - return texture2D(tex,texC); + return TEXTURE(tex,texC); } vec4 getColor(in sampler2D tex, in vec2 texC){ - return texture2D(tex,texC); + return TEXTURE(tex,texC); } vec4 getColorSingle(in sampler2D tex, in vec2 texC){ - return texture2D(tex, texC); + return TEXTURE(tex, texC); } vec4 getDepth(in sampler2D tex,in vec2 texC){ - return texture2D(tex,texC); + return TEXTURE(tex,texC); } -#endif \ No newline at end of file diff --git a/jme3-core/src/main/resources/com/jme3/asset/Desktop.cfg b/jme3-core/src/main/resources/com/jme3/asset/Desktop.cfg index df72654a1..28727d070 100644 --- a/jme3-core/src/main/resources/com/jme3/asset/Desktop.cfg +++ b/jme3-core/src/main/resources/com/jme3/asset/Desktop.cfg @@ -2,26 +2,4 @@ INCLUDE com/jme3/asset/General.cfg # Desktop-specific loaders LOADER com.jme3.texture.plugins.AWTLoader : jpg, bmp, gif, png, jpeg -LOADER com.jme3.audio.plugins.OGGLoader : oggLOADER com.jme3.audio.plugins.WAVLoader : wav LOADER com.jme3.audio.plugins.OGGLoader : ogg -LOADER com.jme3.cursors.plugins.CursorLoader : ani, cur, ico -LOADER com.jme3.material.plugins.J3MLoader : j3m -LOADER com.jme3.material.plugins.J3MLoader : j3md -LOADER com.jme3.material.plugins.ShaderNodeDefinitionLoader : j3sn -LOADER com.jme3.font.plugins.BitmapFontLoader : fnt -LOADER com.jme3.texture.plugins.DDSLoader : dds -LOADER com.jme3.texture.plugins.PFMLoader : pfm -LOADER com.jme3.texture.plugins.HDRLoader : hdr -LOADER com.jme3.texture.plugins.TGALoader : tga -LOADER com.jme3.export.binary.BinaryImporter : j3o -LOADER com.jme3.export.binary.BinaryImporter : j3f -LOADER com.jme3.scene.plugins.OBJLoader : obj -LOADER com.jme3.scene.plugins.MTLLoader : mtl -LOADER com.jme3.scene.plugins.ogre.MeshLoader : meshxml, mesh.xml -LOADER com.jme3.scene.plugins.ogre.SkeletonLoader : skeletonxml, skeleton.xml -LOADER com.jme3.scene.plugins.ogre.MaterialLoader : material -LOADER com.jme3.scene.plugins.ogre.SceneLoader : scene -LOADER com.jme3.scene.plugins.blender.BlenderModelLoader : blend -LOADER com.jme3.shader.plugins.GLSLLoader : vert, frag,geom,tsctrl,tseval, glsl, glsllib -LOADER com.jme3.scene.plugins.fbx.SceneLoader : fbx -LOADER com.jme3.scene.plugins.fbx.SceneWithAnimationLoader : fba diff --git a/jme3-core/src/main/resources/com/jme3/asset/General.cfg b/jme3-core/src/main/resources/com/jme3/asset/General.cfg index c0098ffe5..c56b62146 100644 --- a/jme3-core/src/main/resources/com/jme3/asset/General.cfg +++ b/jme3-core/src/main/resources/com/jme3/asset/General.cfg @@ -21,6 +21,6 @@ LOADER com.jme3.scene.plugins.ogre.SkeletonLoader : skeletonxml, skeleton.xml LOADER com.jme3.scene.plugins.ogre.MaterialLoader : material LOADER com.jme3.scene.plugins.ogre.SceneLoader : scene LOADER com.jme3.scene.plugins.blender.BlenderModelLoader : blend -LOADER com.jme3.shader.plugins.GLSLLoader : vert, frag, glsl, glsllib +LOADER com.jme3.shader.plugins.GLSLLoader : vert, frag, geom, tsctrl, tseval, glsl, glsllib LOADER com.jme3.scene.plugins.fbx.SceneLoader : fbx LOADER com.jme3.scene.plugins.fbx.SceneWithAnimationLoader : fba diff --git a/jme3-core/src/main/resources/joystick-mapping.properties b/jme3-core/src/main/resources/joystick-mapping.properties index 5f29e4105..d7ce2f50a 100644 --- a/jme3-core/src/main/resources/joystick-mapping.properties +++ b/jme3-core/src/main/resources/joystick-mapping.properties @@ -6,7 +6,7 @@ # the new name as it will be reported through the Joystick # interface. # -# Keys with spaces in them should have those spaces escaped. +# Keys with spaces in them should have those spaces escaped. # Values do not need their spaces escaped. For example: # # Some\ Joystick.0=3 @@ -37,22 +37,29 @@ Controller\ (Xbox\ 360\ Wireless\ Receiver\ for\ Windows).ry=rz # requires custom code to support trigger buttons but this # keeps it from confusing the .rx mapping. Controller\ (Xbox\ 360\ Wireless\ Receiver\ for\ Windows).z=trigger - + # Xbox 360 Controller (copied from wireless version) Controller\ (XBOX\ 360\ For\ Windows).0=2 Controller\ (XBOX\ 360\ For\ Windows).1=1 Controller\ (XBOX\ 360\ For\ Windows).2=3 Controller\ (XBOX\ 360\ For\ Windows).3=0 - + Controller\ (XBOX\ 360\ For\ Windows).6=8 Controller\ (XBOX\ 360\ For\ Windows).7=9 - + Controller\ (XBOX\ 360\ For\ Windows).8=10 Controller\ (XBOX\ 360\ For\ Windows).9=11 - + Controller\ (XBOX\ 360\ For\ Windows).rx=z Controller\ (XBOX\ 360\ For\ Windows).ry=rz - + # requires custom code to support trigger buttons but this # keeps it from confusing the .rx mapping. Controller\ (XBOX\ 360\ For\ Windows).z=trigger + +# XBOX 360 Controller connected to Android using +# the USB dongle +Xbox\ 360\ Wireless\ Receiver.AXIS_RX=z +Xbox\ 360\ Wireless\ Receiver.AXIS_RY=rz +Xbox\ 360\ Wireless\ Receiver.z=AXIS_RX +Xbox\ 360\ Wireless\ Receiver.rz=AXIS_RY diff --git a/jme3-core/src/plugins/java/com/jme3/asset/plugins/ZipLocator.java b/jme3-core/src/plugins/java/com/jme3/asset/plugins/ZipLocator.java index d20816f34..22e7cc244 100644 --- a/jme3-core/src/plugins/java/com/jme3/asset/plugins/ZipLocator.java +++ b/jme3-core/src/plugins/java/com/jme3/asset/plugins/ZipLocator.java @@ -82,6 +82,7 @@ public class ZipLocator implements AssetLocator { public AssetInfo locate(AssetManager manager, AssetKey key) { String name = key.getName(); + if(name.startsWith("/"))name=name.substring(1); ZipEntry entry = zipfile.getEntry(name); if (entry == null) return null; diff --git a/jme3-core/src/plugins/java/com/jme3/audio/plugins/WAVLoader.java b/jme3-core/src/plugins/java/com/jme3/audio/plugins/WAVLoader.java index 098de7a15..997a8f4fb 100644 --- a/jme3-core/src/plugins/java/com/jme3/audio/plugins/WAVLoader.java +++ b/jme3-core/src/plugins/java/com/jme3/audio/plugins/WAVLoader.java @@ -196,7 +196,7 @@ public class WAVLoader implements AssetLoader { break; case i_data: // Compute duration based on data chunk size - duration = len / bytesPerSec; + duration = (float)(len / bytesPerSec); if (readStream) { readDataChunkForStream(inOffset, len); diff --git a/jme3-core/src/plugins/java/com/jme3/export/binary/BinaryExporter.java b/jme3-core/src/plugins/java/com/jme3/export/binary/BinaryExporter.java index c02f7088a..eb12bf908 100644 --- a/jme3-core/src/plugins/java/com/jme3/export/binary/BinaryExporter.java +++ b/jme3-core/src/plugins/java/com/jme3/export/binary/BinaryExporter.java @@ -31,6 +31,7 @@ */ package com.jme3.export.binary; +import com.jme3.asset.AssetManager; import com.jme3.export.FormatVersion; import com.jme3.export.JmeExporter; import com.jme3.export.Savable; @@ -167,8 +168,33 @@ public class BinaryExporter implements JmeExporter { public static BinaryExporter getInstance() { return new BinaryExporter(); } + + /** + * Saves the object into memory then loads it from memory. + * + * Used by tests to check if the persistence system is working. + * + * @param The type of savable. + * @param assetManager AssetManager to load assets from. + * @param object The object to save and then load. + * @return A new instance that has been saved and loaded from the + * original object. + */ + public static T saveAndLoad(AssetManager assetManager, T object) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try { + BinaryExporter exporter = new BinaryExporter(); + exporter.save(object, baos); + BinaryImporter importer = new BinaryImporter(); + importer.setAssetManager(assetManager); + return (T) importer.load(baos.toByteArray()); + } catch (IOException ex) { + // Should never happen. + throw new AssertionError(ex); + } + } - public boolean save(Savable object, OutputStream os) throws IOException { + public void save(Savable object, OutputStream os) throws IOException { // reset some vars aliasCount = 1; idCount = 1; @@ -286,7 +312,7 @@ public class BinaryExporter implements JmeExporter { out = null; os = null; - if (debug ) { + if (debug) { logger.fine("Stats:"); logger.log(Level.FINE, "classes: {0}", classNum); logger.log(Level.FINE, "class table: {0} bytes", classTableSize); @@ -294,8 +320,6 @@ public class BinaryExporter implements JmeExporter { logger.log(Level.FINE, "location table: {0} bytes", locationTableSize); logger.log(Level.FINE, "data: {0} bytes", location); } - - return true; } protected String getChunk(BinaryIdContentPair pair) { @@ -325,7 +349,7 @@ public class BinaryExporter implements JmeExporter { return bytes; } - public boolean save(Savable object, File f) throws IOException { + public void save(Savable object, File f) throws IOException { File parentDirectory = f.getParentFile(); if (parentDirectory != null && !parentDirectory.exists()) { parentDirectory.mkdirs(); @@ -333,11 +357,9 @@ public class BinaryExporter implements JmeExporter { FileOutputStream fos = new FileOutputStream(f); try { - return save(object, fos); + save(object, fos); } finally { - if (fos != null) { - fos.close(); - } + fos.close(); } } diff --git a/jme3-core/src/plugins/java/com/jme3/export/binary/BinaryImporter.java b/jme3-core/src/plugins/java/com/jme3/export/binary/BinaryImporter.java index 933bee721..b34adbca6 100644 --- a/jme3-core/src/plugins/java/com/jme3/export/binary/BinaryImporter.java +++ b/jme3-core/src/plugins/java/com/jme3/export/binary/BinaryImporter.java @@ -270,9 +270,7 @@ public final class BinaryImporter implements JmeImporter { try { return load(fis, listener); } finally { - if (fis != null) { - fis.close(); - } + fis.close(); } } diff --git a/jme3-core/src/plugins/java/com/jme3/material/plugins/J3MLoader.java b/jme3-core/src/plugins/java/com/jme3/material/plugins/J3MLoader.java index 449802161..d0620ca59 100644 --- a/jme3-core/src/plugins/java/com/jme3/material/plugins/J3MLoader.java +++ b/jme3-core/src/plugins/java/com/jme3/material/plugins/J3MLoader.java @@ -63,7 +63,7 @@ public class J3MLoader implements AssetLoader { // private ErrorLogger errors; private ShaderNodeLoaderDelegate nodesLoaderDelegate; boolean isUseNodes = false; - + private AssetManager assetManager; private AssetKey key; @@ -168,14 +168,15 @@ public class J3MLoader implements AssetLoader { if (tex != null){ if (repeat){ tex.setWrap(WrapMode.Repeat); - } + } }else{ tex = new Texture2D(PlaceholderAssets.getPlaceholderImage(assetManager)); if (repeat){ tex.setWrap(WrapMode.Repeat); } tex.setKey(texKey); - } + tex.setName(texKey.getName()); + } return tex; }else{ String[] split = value.trim().split(whitespacePattern); @@ -221,15 +222,15 @@ public class J3MLoader implements AssetLoader { } } } - - // [ "(" ")" ] [-LINEAR] [ ":" ] + + // [ "(" ")" ] [-LINEAR] [ ":" ] private void readParam(String statement) throws IOException{ String name; String defaultVal = null; ColorSpace colorSpace = null; - + String[] split = statement.split(":"); - + // Parse default val if (split.length == 1){ // Doesn't contain default value @@ -238,14 +239,14 @@ public class J3MLoader implements AssetLoader { throw new IOException("Parameter statement syntax incorrect"); } statement = split[0].trim(); - defaultVal = split[1].trim(); + defaultVal = split[1].trim(); } - + if (statement.endsWith("-LINEAR")) { colorSpace = ColorSpace.Linear; statement = statement.substring(0, statement.length() - "-LINEAR".length()); } - + // Parse ffbinding int startParen = statement.indexOf("("); if (startParen != -1){ @@ -255,32 +256,32 @@ public class J3MLoader implements AssetLoader { // don't care about bindingStr statement = statement.substring(0, startParen); } - + // Parse type + name split = statement.split(whitespacePattern); if (split.length != 2){ throw new IOException("Parameter statement syntax incorrect"); } - + VarType type; if (split[0].equals("Color")){ type = VarType.Vector4; }else{ type = VarType.valueOf(split[0]); } - + name = split[1]; - + Object defaultValObj = null; - if (defaultVal != null){ + if (defaultVal != null){ defaultValObj = readValue(type, defaultVal); } if(type.isTextureType()){ - materialDef.addMaterialParamTexture(type, name, colorSpace); + materialDef.addMaterialParamTexture(type, name, colorSpace); }else{ materialDef.addMaterialParam(type, name, defaultValObj); } - + } private void readValueParam(String statement) throws IOException{ @@ -375,7 +376,7 @@ public class J3MLoader implements AssetLoader { technique.setRenderState(renderState); renderState = null; } - + private void readForcedRenderState(List renderStates) throws IOException{ renderState = new RenderState(); for (Statement statement : renderStates){ @@ -384,7 +385,7 @@ public class J3MLoader implements AssetLoader { technique.setForcedRenderState(renderState); renderState = null; } - + // [ ":" ] private void readDefine(String statement) throws IOException{ String[] split = statement.split(":"); @@ -404,9 +405,9 @@ public class J3MLoader implements AssetLoader { } } - + private void readTechniqueStatement(Statement statement) throws IOException{ - String[] split = statement.getLine().split("[ \\{]"); + String[] split = statement.getLine().split("[ \\{]"); if (split[0].equals("VertexShader") || split[0].equals("FragmentShader") || split[0].equals("GeometryShader") || @@ -419,12 +420,12 @@ public class J3MLoader implements AssetLoader { readShadowMode(statement.getLine()); }else if (split[0].equals("WorldParameters")){ readWorldParams(statement.getContents()); - }else if (split[0].equals("RenderState")){ + }else if (split[0].equals("RenderState")){ readRenderState(statement.getContents()); - }else if (split[0].equals("ForcedRenderState")){ + }else if (split[0].equals("ForcedRenderState")){ readForcedRenderState(statement.getContents()); - }else if (split[0].equals("Defines")){ - readDefines(statement.getContents()); + }else if (split[0].equals("Defines")){ + readDefines(statement.getContents()); } else if (split[0].equals("ShaderNodesDefinitions")) { initNodesLoader(); if (isUseNodes) { @@ -437,14 +438,16 @@ public class J3MLoader implements AssetLoader { } } else if (split[0].equals("FragmentShaderNodes")) { initNodesLoader(); - if (isUseNodes) { + if (isUseNodes) { nodesLoaderDelegate.readFragmentShaderNodes(statement.getContents()); } + } else if (split[0].equals("NoRender")) { + technique.setNoRender(true); } else { throw new MatParseException(null, split[0], statement); } } - + private void readTransparentStatement(String statement) throws IOException{ String[] split = statement.split(whitespacePattern); if (split.length != 2){ @@ -464,11 +467,11 @@ public class J3MLoader implements AssetLoader { } else { throw new IOException("Technique statement syntax incorrect"); } - + for (Statement statement : techStat.getContents()){ readTechniqueStatement(statement); } - + if(isUseNodes){ nodesLoaderDelegate.computeConditions(); //used for caching later, the shader here is not a file. @@ -478,14 +481,14 @@ public class J3MLoader implements AssetLoader { if (shaderName.containsKey(Shader.ShaderType.Vertex) && shaderName.containsKey(Shader.ShaderType.Fragment)) { technique.setShaderFile(shaderName, shaderLanguage); } - + materialDef.addTechniqueDef(technique); technique = null; shaderLanguage.clear(); shaderName.clear(); } - private void loadFromRoot(List roots) throws IOException{ + private void loadFromRoot(List roots) throws IOException{ if (roots.size() == 2){ Statement exception = roots.get(0); String line = exception.getLine(); @@ -497,7 +500,7 @@ public class J3MLoader implements AssetLoader { }else if (roots.size() != 1){ throw new IOException("Too many roots in J3M/J3MD file"); } - + boolean extending = false; Statement materialStat = roots.get(0); String materialName = materialStat.getLine(); @@ -510,16 +513,16 @@ public class J3MLoader implements AssetLoader { }else{ throw new IOException("Specified file is not a Material file"); } - + String[] split = materialName.split(":", 2); - + if (materialName.equals("")){ - throw new MatParseException("Material name cannot be empty", materialStat); + throw new MatParseException("Material name cannot be empty", materialStat); } if (split.length == 2){ if (!extending){ - throw new MatParseException("Must use 'Material' when extending.", materialStat); + throw new MatParseException("Must use 'Material' when extending.", materialStat); } String extendedMat = split[1].trim(); @@ -534,15 +537,15 @@ public class J3MLoader implements AssetLoader { // material.setAssetName(fileName); }else if (split.length == 1){ if (extending){ - throw new MatParseException("Expected ':', got '{'", materialStat); + throw new MatParseException("Expected ':', got '{'", materialStat); } materialDef = new MaterialDef(assetManager, materialName); // NOTE: pass file name for defs so they can be loaded later materialDef.setAssetName(key.getName()); }else{ - throw new MatParseException("Cannot use colon in material name/path", materialStat); + throw new MatParseException("Cannot use colon in material name/path", materialStat); } - + for (Statement statement : materialStat.getContents()){ split = statement.getLine().split("[ \\{]"); String statType = split[0]; @@ -560,29 +563,31 @@ public class J3MLoader implements AssetLoader { }else if (statType.equals("MaterialParameters")){ readMaterialParams(statement.getContents()); }else{ - throw new MatParseException("Expected material statement, got '"+statType+"'", statement); + throw new MatParseException("Expected material statement, got '"+statType+"'", statement); } } } } - public Object load(AssetInfo info) throws IOException { + public Object load(AssetInfo info) throws IOException { this.assetManager = info.getManager(); - InputStream in = info.openStream(); + InputStream in = info.openStream(); try { - key = info.getKey(); + key = info.getKey(); + if (key.getExtension().equals("j3m") && !(key instanceof MaterialKey)) { + throw new IOException("Material instances must be loaded via MaterialKey"); + } else if (key.getExtension().equals("j3md") && key instanceof MaterialKey) { + throw new IOException("Material definitions must be loaded via AssetKey"); + } loadFromRoot(BlockLanguageParser.parse(in)); } finally { if (in != null){ in.close(); } } - + if (material != null){ - if (!(info.getKey() instanceof MaterialKey)){ - throw new IOException("Material instances must be loaded via MaterialKey"); - } // material implementation return material; }else{ @@ -590,7 +595,7 @@ public class J3MLoader implements AssetLoader { return materialDef; } } - + public MaterialDef loadMaterialDef(List roots, AssetManager manager, AssetKey key) throws IOException { this.key = key; this.assetManager = manager; @@ -612,6 +617,6 @@ public class J3MLoader implements AssetLoader { nodesLoaderDelegate.setAssetManager(assetManager); } } - } + } } diff --git a/jme3-core/src/plugins/java/com/jme3/texture/plugins/DXTFlipper.java b/jme3-core/src/plugins/java/com/jme3/texture/plugins/DXTFlipper.java index 9c71aa132..726cf3e19 100644 --- a/jme3-core/src/plugins/java/com/jme3/texture/plugins/DXTFlipper.java +++ b/jme3-core/src/plugins/java/com/jme3/texture/plugins/DXTFlipper.java @@ -242,21 +242,12 @@ public class DXTFlipper { img.position(blockByteOffset); img.limit(blockByteOffset + bpb); - img.get(colorBlock); - if (type == 4 || type == 5) - flipDXT5Block(colorBlock, h); - else - flipDXT1orDXTA3Block(colorBlock, h); - - // write block (no need to flip block indexes, only pixels - // inside block - retImg.put(colorBlock); - if (alphaBlock != null){ img.get(alphaBlock); switch (type){ case 2: - flipDXT3Block(alphaBlock, h); break; + flipDXT3Block(alphaBlock, h); + break; case 3: case 4: flipDXT5Block(alphaBlock, h); @@ -264,6 +255,16 @@ public class DXTFlipper { } retImg.put(alphaBlock); } + + img.get(colorBlock); + if (type == 4 || type == 5) + flipDXT5Block(colorBlock, h); + else + flipDXT1orDXTA3Block(colorBlock, h); + + // write block (no need to flip block indexes, only pixels + // inside block + retImg.put(colorBlock); } retImg.rewind(); }else if (h >= 4){ diff --git a/jme3-core/src/tools/java/jme3tools/optimize/GeometryBatchFactory.java b/jme3-core/src/tools/java/jme3tools/optimize/GeometryBatchFactory.java index a7668dc56..9904b3283 100644 --- a/jme3-core/src/tools/java/jme3tools/optimize/GeometryBatchFactory.java +++ b/jme3-core/src/tools/java/jme3tools/optimize/GeometryBatchFactory.java @@ -16,6 +16,7 @@ import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import java.util.*; +import java.util.logging.Level; import java.util.logging.Logger; public class GeometryBatchFactory { @@ -453,4 +454,93 @@ public class GeometryBatchFactory { mergeGeometries(geoms, outMesh); printMesh(outMesh); } + + /** + * Options to align the buffers of geometries' meshes of a sub graph + * + */ + public static enum AlignOption { + + /** + * Will remove the buffers of a type that is not on all the geometries + */ + RemoveUnalignedBuffers, + /** + * Will create missing buffers and pad with dummy data + */ + CreateMissingBuffers + } + + /** + * Will ensure that all the geometries' meshes of the n sub graph have the + * same types of buffers + * @param n the node to gather geometries from + * @param option the align options + * @see AlignOption + * + * Very experimental for now. + */ + public static void alignBuffers(Node n, AlignOption option) { + List geoms = new ArrayList(); + gatherGeoms(n, geoms); + + //gather buffer types + Map types = new EnumMap(VertexBuffer.Type.class); + Map typesCount = new EnumMap(VertexBuffer.Type.class); + for (Geometry geom : geoms) { + for (VertexBuffer buffer : geom.getMesh().getBufferList()) { + if (types.get(buffer.getBufferType()) == null) { + types.put(buffer.getBufferType(), buffer); + logger.log(Level.FINE, buffer.getBufferType().toString()); + } + Integer count = typesCount.get(buffer.getBufferType()); + if (count == null) { + count = 0; + } + count++; + typesCount.put(buffer.getBufferType(), count); + } + } + + switch (option) { + case RemoveUnalignedBuffers: + for (Geometry geom : geoms) { + + for (VertexBuffer buffer : geom.getMesh().getBufferList()) { + Integer count = typesCount.get(buffer.getBufferType()); + if (count != null && count < geoms.size()) { + geom.getMesh().clearBuffer(buffer.getBufferType()); + logger.log(Level.FINE, "removing {0} from {1}", new Object[]{buffer.getBufferType(), geom.getName()}); + + } + } + } + break; + case CreateMissingBuffers: + for (Geometry geom : geoms) { + for (VertexBuffer.Type type : types.keySet()) { + if (geom.getMesh().getBuffer(type) == null) { + VertexBuffer vb = new VertexBuffer(type); + Buffer b; + switch (type) { + case Index: + case BoneIndex: + case HWBoneIndex: + b = BufferUtils.createIntBuffer(geom.getMesh().getVertexCount() * types.get(type).getNumComponents()); + break; + case InterleavedData: + b = BufferUtils.createByteBuffer(geom.getMesh().getVertexCount() * types.get(type).getNumComponents()); + break; + default: + b = BufferUtils.createFloatBuffer(geom.getMesh().getVertexCount() * types.get(type).getNumComponents()); + } + vb.setupData(types.get(type).getUsage(), types.get(type).getNumComponents(), types.get(type).getFormat(), b); + geom.getMesh().setBuffer(vb); + logger.log(Level.FINE, "geom {0} misses buffer {1}. Creating", new Object[]{geom.getName(), type}); + } + } + } + break; + } + } } diff --git a/jme3-desktop/src/main/java/com/jme3/app/state/VideoRecorderAppState.java b/jme3-desktop/src/main/java/com/jme3/app/state/VideoRecorderAppState.java index 9466b4a50..ccaecc580 100644 --- a/jme3-desktop/src/main/java/com/jme3/app/state/VideoRecorderAppState.java +++ b/jme3-desktop/src/main/java/com/jme3/app/state/VideoRecorderAppState.java @@ -71,7 +71,7 @@ public class VideoRecorderAppState extends AbstractAppState { public Thread newThread(Runnable r) { Thread th = new Thread(r); - th.setName("jME Video Processing Thread"); + th.setName("jME3 Video Processor"); th.setDaemon(true); return th; } diff --git a/jme3-effects/src/main/java/com/jme3/post/ssao/SSAOFilter.java b/jme3-effects/src/main/java/com/jme3/post/ssao/SSAOFilter.java index 75d6b1c86..7e9012b6d 100644 --- a/jme3-effects/src/main/java/com/jme3/post/ssao/SSAOFilter.java +++ b/jme3-effects/src/main/java/com/jme3/post/ssao/SSAOFilter.java @@ -162,8 +162,8 @@ public class SSAOFilter extends Filter { }; ssaoPass.init(renderManager.getRenderer(), (int) (screenWidth / downSampleFactor), (int) (screenHeight / downSampleFactor), Format.RGBA8, Format.Depth, 1, ssaoMat); - ssaoPass.getRenderedTexture().setMinFilter(Texture.MinFilter.Trilinear); - ssaoPass.getRenderedTexture().setMagFilter(Texture.MagFilter.Bilinear); +// ssaoPass.getRenderedTexture().setMinFilter(Texture.MinFilter.Trilinear); +// ssaoPass.getRenderedTexture().setMagFilter(Texture.MagFilter.Bilinear); postRenderPasses.add(ssaoPass); material = new Material(manager, "Common/MatDefs/SSAO/ssaoBlur.j3md"); material.setTexture("SSAOMap", ssaoPass.getRenderedTexture()); diff --git a/jme3-effects/src/main/resources/Common/MatDefs/Water/Water.frag b/jme3-effects/src/main/resources/Common/MatDefs/Water/Water.frag index 07a4c6429..cb393dbaa 100644 --- a/jme3-effects/src/main/resources/Common/MatDefs/Water/Water.frag +++ b/jme3-effects/src/main/resources/Common/MatDefs/Water/Water.frag @@ -413,10 +413,6 @@ void main(){ // to calculate the derivatives for all these pixels by using step()! // That way we won't get pixels around the edges of the terrain, // Where the derivatives are undefined - if(position.y > level){ - color = color2; - } - - gl_FragColor = vec4(color,1.0); + gl_FragColor = vec4(mix(color, color2, step(level, position.y)), 1.0); } \ No newline at end of file diff --git a/jme3-effects/src/main/resources/Common/MatDefs/Water/Water.j3md b/jme3-effects/src/main/resources/Common/MatDefs/Water/Water.j3md index 2f4b2b39c..2f188934b 100644 --- a/jme3-effects/src/main/resources/Common/MatDefs/Water/Water.j3md +++ b/jme3-effects/src/main/resources/Common/MatDefs/Water/Water.j3md @@ -77,6 +77,7 @@ MaterialDef Advanced Water { FragmentShader GLSL120 : Common/MatDefs/Water/Water.frag WorldParameters { + ViewProjectionMatrixInverse } Defines { ENABLE_RIPPLES : UseRipples diff --git a/jme3-examples/build.gradle b/jme3-examples/build.gradle index 186a6bc2d..de1c3931c 100644 --- a/jme3-examples/build.gradle +++ b/jme3-examples/build.gradle @@ -6,7 +6,10 @@ if (!hasProperty('mainClass')) { task run(dependsOn: 'build', type:JavaExec) { main = mainClass - classpath = sourceSets.main.runtimeClasspath + classpath = sourceSets.main.runtimeClasspath + if( assertions == "true" ){ + enableAssertions = true; + } } dependencies { diff --git a/jme3-examples/gradle.properties b/jme3-examples/gradle.properties new file mode 100644 index 000000000..6f0993120 --- /dev/null +++ b/jme3-examples/gradle.properties @@ -0,0 +1,5 @@ +# When running this project we don't need javadoc to be built. +buildJavaDoc = false + +# We want assertions, because this is the test project. +assertions = true diff --git a/jme3-examples/src/main/java/jme3test/bullet/TestAttachDriver.java b/jme3-examples/src/main/java/jme3test/bullet/TestAttachDriver.java index a4b4b92a3..8f9447ea1 100644 --- a/jme3-examples/src/main/java/jme3test/bullet/TestAttachDriver.java +++ b/jme3-examples/src/main/java/jme3test/bullet/TestAttachDriver.java @@ -69,7 +69,7 @@ public class TestAttachDriver extends SimpleApplication implements ActionListene private float accelerationValue = 0; private Vector3f jumpForce = new Vector3f(0, 3000, 0); private BulletAppState bulletAppState; - + public static void main(String[] args) { TestAttachDriver app = new TestAttachDriver(); app.start(); @@ -79,7 +79,7 @@ public class TestAttachDriver extends SimpleApplication implements ActionListene public void simpleInitApp() { bulletAppState = new BulletAppState(); stateManager.attach(bulletAppState); - bulletAppState.getPhysicsSpace().enableDebug(assetManager); + bulletAppState.setDebugEnabled(true); setupKeys(); setupFloor(); buildPlayer(); diff --git a/jme3-examples/src/main/java/jme3test/bullet/TestAttachGhostObject.java b/jme3-examples/src/main/java/jme3test/bullet/TestAttachGhostObject.java index 5b6992f3a..5fac3fc5f 100644 --- a/jme3-examples/src/main/java/jme3test/bullet/TestAttachGhostObject.java +++ b/jme3-examples/src/main/java/jme3test/bullet/TestAttachGhostObject.java @@ -85,7 +85,7 @@ public class TestAttachGhostObject extends SimpleApplication implements AnalogLi public void simpleInitApp() { bulletAppState = new BulletAppState(); stateManager.attach(bulletAppState); - bulletAppState.getPhysicsSpace().enableDebug(assetManager); + bulletAppState.setDebugEnabled(true); setupKeys(); setupJoint(); } diff --git a/jme3-examples/src/main/java/jme3test/bullet/TestCcd.java b/jme3-examples/src/main/java/jme3test/bullet/TestCcd.java index beb57bdec..cda07bc85 100644 --- a/jme3-examples/src/main/java/jme3test/bullet/TestCcd.java +++ b/jme3-examples/src/main/java/jme3test/bullet/TestCcd.java @@ -1,152 +1,152 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package jme3test.bullet; - -import com.jme3.app.SimpleApplication; -import com.jme3.bullet.BulletAppState; -import com.jme3.bullet.PhysicsSpace; -import com.jme3.bullet.collision.shapes.BoxCollisionShape; -import com.jme3.bullet.collision.shapes.MeshCollisionShape; -import com.jme3.bullet.collision.shapes.SphereCollisionShape; -import com.jme3.bullet.control.RigidBodyControl; -import com.jme3.input.MouseInput; -import com.jme3.input.controls.ActionListener; -import com.jme3.input.controls.MouseButtonTrigger; -import com.jme3.material.Material; -import com.jme3.math.ColorRGBA; -import com.jme3.math.Vector3f; -import com.jme3.renderer.RenderManager; -import com.jme3.renderer.queue.RenderQueue.ShadowMode; -import com.jme3.scene.Geometry; -import com.jme3.scene.Node; -import com.jme3.scene.shape.Box; -import com.jme3.scene.shape.Sphere; -import com.jme3.scene.shape.Sphere.TextureMode; - -/** - * - * @author normenhansen - */ -public class TestCcd extends SimpleApplication implements ActionListener { - - private Material mat; - private Material mat2; - private Sphere bullet; - private SphereCollisionShape bulletCollisionShape; - private BulletAppState bulletAppState; - - public static void main(String[] args) { - TestCcd app = new TestCcd(); - app.start(); - } - - private void setupKeys() { - inputManager.addMapping("shoot", new MouseButtonTrigger(MouseInput.BUTTON_LEFT)); - inputManager.addMapping("shoot2", new MouseButtonTrigger(MouseInput.BUTTON_RIGHT)); - inputManager.addListener(this, "shoot"); - inputManager.addListener(this, "shoot2"); - } - - @Override - public void simpleInitApp() { - bulletAppState = new BulletAppState(); - stateManager.attach(bulletAppState); - bulletAppState.getPhysicsSpace().enableDebug(assetManager); - bullet = new Sphere(32, 32, 0.4f, true, false); - bullet.setTextureMode(TextureMode.Projected); - bulletCollisionShape = new SphereCollisionShape(0.1f); - setupKeys(); - - mat = new Material(getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); - mat.getAdditionalRenderState().setWireframe(true); - mat.setColor("Color", ColorRGBA.Green); - - mat2 = new Material(getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); - mat2.getAdditionalRenderState().setWireframe(true); - mat2.setColor("Color", ColorRGBA.Red); - - // An obstacle mesh, does not move (mass=0) - Node node2 = new Node(); - node2.setName("mesh"); - node2.setLocalTranslation(new Vector3f(2.5f, 0, 0f)); - node2.addControl(new RigidBodyControl(new MeshCollisionShape(new Box(Vector3f.ZERO, 4, 4, 0.1f)), 0)); - rootNode.attachChild(node2); - getPhysicsSpace().add(node2); - - // The floor, does not move (mass=0) - Node node3 = new Node(); - node3.setLocalTranslation(new Vector3f(0f, -6, 0f)); - node3.addControl(new RigidBodyControl(new BoxCollisionShape(new Vector3f(100, 1, 100)), 0)); - rootNode.attachChild(node3); - getPhysicsSpace().add(node3); - - } - - private PhysicsSpace getPhysicsSpace() { - return bulletAppState.getPhysicsSpace(); - } - - @Override - public void simpleUpdate(float tpf) { - //TODO: add update code - } - - @Override - public void simpleRender(RenderManager rm) { - //TODO: add render code - } - - public void onAction(String binding, boolean value, float tpf) { - if (binding.equals("shoot") && !value) { - Geometry bulletg = new Geometry("bullet", bullet); - bulletg.setMaterial(mat); - bulletg.setName("bullet"); - bulletg.setLocalTranslation(cam.getLocation()); - bulletg.setShadowMode(ShadowMode.CastAndReceive); - bulletg.addControl(new RigidBodyControl(bulletCollisionShape, 1)); - bulletg.getControl(RigidBodyControl.class).setCcdMotionThreshold(0.1f); - bulletg.getControl(RigidBodyControl.class).setLinearVelocity(cam.getDirection().mult(40)); - rootNode.attachChild(bulletg); - getPhysicsSpace().add(bulletg); - } else if (binding.equals("shoot2") && !value) { - Geometry bulletg = new Geometry("bullet", bullet); - bulletg.setMaterial(mat2); - bulletg.setName("bullet"); - bulletg.setLocalTranslation(cam.getLocation()); - bulletg.setShadowMode(ShadowMode.CastAndReceive); - bulletg.addControl(new RigidBodyControl(bulletCollisionShape, 1)); - bulletg.getControl(RigidBodyControl.class).setLinearVelocity(cam.getDirection().mult(40)); - rootNode.attachChild(bulletg); - getPhysicsSpace().add(bulletg); - } - } -} +/* + * Copyright (c) 2009-2012 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package jme3test.bullet; + +import com.jme3.app.SimpleApplication; +import com.jme3.bullet.BulletAppState; +import com.jme3.bullet.PhysicsSpace; +import com.jme3.bullet.collision.shapes.BoxCollisionShape; +import com.jme3.bullet.collision.shapes.MeshCollisionShape; +import com.jme3.bullet.collision.shapes.SphereCollisionShape; +import com.jme3.bullet.control.RigidBodyControl; +import com.jme3.input.MouseInput; +import com.jme3.input.controls.ActionListener; +import com.jme3.input.controls.MouseButtonTrigger; +import com.jme3.material.Material; +import com.jme3.math.ColorRGBA; +import com.jme3.math.Vector3f; +import com.jme3.renderer.RenderManager; +import com.jme3.renderer.queue.RenderQueue.ShadowMode; +import com.jme3.scene.Geometry; +import com.jme3.scene.Node; +import com.jme3.scene.shape.Box; +import com.jme3.scene.shape.Sphere; +import com.jme3.scene.shape.Sphere.TextureMode; + +/** + * + * @author normenhansen + */ +public class TestCcd extends SimpleApplication implements ActionListener { + + private Material mat; + private Material mat2; + private Sphere bullet; + private SphereCollisionShape bulletCollisionShape; + private BulletAppState bulletAppState; + + public static void main(String[] args) { + TestCcd app = new TestCcd(); + app.start(); + } + + private void setupKeys() { + inputManager.addMapping("shoot", new MouseButtonTrigger(MouseInput.BUTTON_LEFT)); + inputManager.addMapping("shoot2", new MouseButtonTrigger(MouseInput.BUTTON_RIGHT)); + inputManager.addListener(this, "shoot"); + inputManager.addListener(this, "shoot2"); + } + + @Override + public void simpleInitApp() { + bulletAppState = new BulletAppState(); + stateManager.attach(bulletAppState); + bulletAppState.setDebugEnabled(true); + bullet = new Sphere(32, 32, 0.4f, true, false); + bullet.setTextureMode(TextureMode.Projected); + bulletCollisionShape = new SphereCollisionShape(0.1f); + setupKeys(); + + mat = new Material(getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); + mat.getAdditionalRenderState().setWireframe(true); + mat.setColor("Color", ColorRGBA.Green); + + mat2 = new Material(getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); + mat2.getAdditionalRenderState().setWireframe(true); + mat2.setColor("Color", ColorRGBA.Red); + + // An obstacle mesh, does not move (mass=0) + Node node2 = new Node(); + node2.setName("mesh"); + node2.setLocalTranslation(new Vector3f(2.5f, 0, 0f)); + node2.addControl(new RigidBodyControl(new MeshCollisionShape(new Box(Vector3f.ZERO, 4, 4, 0.1f)), 0)); + rootNode.attachChild(node2); + getPhysicsSpace().add(node2); + + // The floor, does not move (mass=0) + Node node3 = new Node(); + node3.setLocalTranslation(new Vector3f(0f, -6, 0f)); + node3.addControl(new RigidBodyControl(new BoxCollisionShape(new Vector3f(100, 1, 100)), 0)); + rootNode.attachChild(node3); + getPhysicsSpace().add(node3); + + } + + private PhysicsSpace getPhysicsSpace() { + return bulletAppState.getPhysicsSpace(); + } + + @Override + public void simpleUpdate(float tpf) { + //TODO: add update code + } + + @Override + public void simpleRender(RenderManager rm) { + //TODO: add render code + } + + public void onAction(String binding, boolean value, float tpf) { + if (binding.equals("shoot") && !value) { + Geometry bulletg = new Geometry("bullet", bullet); + bulletg.setMaterial(mat); + bulletg.setName("bullet"); + bulletg.setLocalTranslation(cam.getLocation()); + bulletg.setShadowMode(ShadowMode.CastAndReceive); + bulletg.addControl(new RigidBodyControl(bulletCollisionShape, 1)); + bulletg.getControl(RigidBodyControl.class).setCcdMotionThreshold(0.1f); + bulletg.getControl(RigidBodyControl.class).setLinearVelocity(cam.getDirection().mult(40)); + rootNode.attachChild(bulletg); + getPhysicsSpace().add(bulletg); + } else if (binding.equals("shoot2") && !value) { + Geometry bulletg = new Geometry("bullet", bullet); + bulletg.setMaterial(mat2); + bulletg.setName("bullet"); + bulletg.setLocalTranslation(cam.getLocation()); + bulletg.setShadowMode(ShadowMode.CastAndReceive); + bulletg.addControl(new RigidBodyControl(bulletCollisionShape, 1)); + bulletg.getControl(RigidBodyControl.class).setLinearVelocity(cam.getDirection().mult(40)); + rootNode.attachChild(bulletg); + getPhysicsSpace().add(bulletg); + } + } +} diff --git a/jme3-examples/src/main/java/jme3test/bullet/TestCollisionGroups.java b/jme3-examples/src/main/java/jme3test/bullet/TestCollisionGroups.java index 0bfa9f784..410c125d2 100644 --- a/jme3-examples/src/main/java/jme3test/bullet/TestCollisionGroups.java +++ b/jme3-examples/src/main/java/jme3test/bullet/TestCollisionGroups.java @@ -61,8 +61,8 @@ public class TestCollisionGroups extends SimpleApplication { public void simpleInitApp() { bulletAppState = new BulletAppState(); stateManager.attach(bulletAppState); - bulletAppState.getPhysicsSpace().enableDebug(assetManager); - + bulletAppState.setDebugEnabled(true); + // Add a physics sphere to the world Node physicsSphere = PhysicsTestHelper.createPhysicsTestNode(assetManager, new SphereCollisionShape(1), 1); physicsSphere.getControl(RigidBodyControl.class).setPhysicsLocation(new Vector3f(3, 6, 0)); diff --git a/jme3-examples/src/main/java/jme3test/bullet/TestCollisionListener.java b/jme3-examples/src/main/java/jme3test/bullet/TestCollisionListener.java index 1a13b09fb..3c9450f3d 100644 --- a/jme3-examples/src/main/java/jme3test/bullet/TestCollisionListener.java +++ b/jme3-examples/src/main/java/jme3test/bullet/TestCollisionListener.java @@ -1,98 +1,98 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package jme3test.bullet; - -import com.jme3.app.SimpleApplication; -import com.jme3.bullet.BulletAppState; -import com.jme3.bullet.PhysicsSpace; -import com.jme3.bullet.collision.PhysicsCollisionEvent; -import com.jme3.bullet.collision.PhysicsCollisionListener; -import com.jme3.bullet.collision.shapes.SphereCollisionShape; -import com.jme3.renderer.RenderManager; -import com.jme3.scene.shape.Sphere; -import com.jme3.scene.shape.Sphere.TextureMode; - -/** - * - * @author normenhansen - */ -public class TestCollisionListener extends SimpleApplication implements PhysicsCollisionListener { - - private BulletAppState bulletAppState; - private Sphere bullet; - private SphereCollisionShape bulletCollisionShape; - - public static void main(String[] args) { - TestCollisionListener app = new TestCollisionListener(); - app.start(); - } - - @Override - public void simpleInitApp() { - bulletAppState = new BulletAppState(); - stateManager.attach(bulletAppState); - bulletAppState.getPhysicsSpace().enableDebug(assetManager); - bullet = new Sphere(32, 32, 0.4f, true, false); - bullet.setTextureMode(TextureMode.Projected); - bulletCollisionShape = new SphereCollisionShape(0.4f); - - PhysicsTestHelper.createPhysicsTestWorld(rootNode, assetManager, bulletAppState.getPhysicsSpace()); - PhysicsTestHelper.createBallShooter(this, rootNode, bulletAppState.getPhysicsSpace()); - - // add ourselves as collision listener - getPhysicsSpace().addCollisionListener(this); - } - - private PhysicsSpace getPhysicsSpace(){ - return bulletAppState.getPhysicsSpace(); - } - - @Override - public void simpleUpdate(float tpf) { - //TODO: add update code - } - - @Override - public void simpleRender(RenderManager rm) { - //TODO: add render code - } - - public void collision(PhysicsCollisionEvent event) { - if ("Box".equals(event.getNodeA().getName()) || "Box".equals(event.getNodeB().getName())) { - if ("bullet".equals(event.getNodeA().getName()) || "bullet".equals(event.getNodeB().getName())) { - fpsText.setText("You hit the box!"); - } - } - } - -} +/* + * Copyright (c) 2009-2012 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package jme3test.bullet; + +import com.jme3.app.SimpleApplication; +import com.jme3.bullet.BulletAppState; +import com.jme3.bullet.PhysicsSpace; +import com.jme3.bullet.collision.PhysicsCollisionEvent; +import com.jme3.bullet.collision.PhysicsCollisionListener; +import com.jme3.bullet.collision.shapes.SphereCollisionShape; +import com.jme3.renderer.RenderManager; +import com.jme3.scene.shape.Sphere; +import com.jme3.scene.shape.Sphere.TextureMode; + +/** + * + * @author normenhansen + */ +public class TestCollisionListener extends SimpleApplication implements PhysicsCollisionListener { + + private BulletAppState bulletAppState; + private Sphere bullet; + private SphereCollisionShape bulletCollisionShape; + + public static void main(String[] args) { + TestCollisionListener app = new TestCollisionListener(); + app.start(); + } + + @Override + public void simpleInitApp() { + bulletAppState = new BulletAppState(); + stateManager.attach(bulletAppState); + bulletAppState.setDebugEnabled(true); + bullet = new Sphere(32, 32, 0.4f, true, false); + bullet.setTextureMode(TextureMode.Projected); + bulletCollisionShape = new SphereCollisionShape(0.4f); + + PhysicsTestHelper.createPhysicsTestWorld(rootNode, assetManager, bulletAppState.getPhysicsSpace()); + PhysicsTestHelper.createBallShooter(this, rootNode, bulletAppState.getPhysicsSpace()); + + // add ourselves as collision listener + getPhysicsSpace().addCollisionListener(this); + } + + private PhysicsSpace getPhysicsSpace(){ + return bulletAppState.getPhysicsSpace(); + } + + @Override + public void simpleUpdate(float tpf) { + //TODO: add update code + } + + @Override + public void simpleRender(RenderManager rm) { + //TODO: add render code + } + + public void collision(PhysicsCollisionEvent event) { + if ("Box".equals(event.getNodeA().getName()) || "Box".equals(event.getNodeB().getName())) { + if ("bullet".equals(event.getNodeA().getName()) || "bullet".equals(event.getNodeB().getName())) { + fpsText.setText("You hit the box!"); + } + } + } + +} diff --git a/jme3-examples/src/main/java/jme3test/bullet/TestCollisionShapeFactory.java b/jme3-examples/src/main/java/jme3test/bullet/TestCollisionShapeFactory.java index b2c44ce4e..2128149d2 100644 --- a/jme3-examples/src/main/java/jme3test/bullet/TestCollisionShapeFactory.java +++ b/jme3-examples/src/main/java/jme3test/bullet/TestCollisionShapeFactory.java @@ -67,7 +67,7 @@ public class TestCollisionShapeFactory extends SimpleApplication { public void simpleInitApp() { bulletAppState = new BulletAppState(); stateManager.attach(bulletAppState); - bulletAppState.getPhysicsSpace().enableDebug(assetManager); + bulletAppState.setDebugEnabled(true); createMaterial(); Node node = new Node("node1"); diff --git a/jme3-examples/src/main/java/jme3test/bullet/TestGhostObject.java b/jme3-examples/src/main/java/jme3test/bullet/TestGhostObject.java index dde9e530c..74a7c1e1e 100644 --- a/jme3-examples/src/main/java/jme3test/bullet/TestGhostObject.java +++ b/jme3-examples/src/main/java/jme3test/bullet/TestGhostObject.java @@ -62,7 +62,7 @@ public class TestGhostObject extends SimpleApplication { public void simpleInitApp() { bulletAppState = new BulletAppState(); stateManager.attach(bulletAppState); - bulletAppState.getPhysicsSpace().enableDebug(assetManager); + bulletAppState.setDebugEnabled(true); // Mesh to be shared across several boxes. Box boxGeom = new Box(Vector3f.ZERO, 1f, 1f, 1f); diff --git a/jme3-examples/src/main/java/jme3test/bullet/TestKinematicAddToPhysicsSpaceIssue.java b/jme3-examples/src/main/java/jme3test/bullet/TestKinematicAddToPhysicsSpaceIssue.java index 636122b4b..e63cd03e5 100644 --- a/jme3-examples/src/main/java/jme3test/bullet/TestKinematicAddToPhysicsSpaceIssue.java +++ b/jme3-examples/src/main/java/jme3test/bullet/TestKinematicAddToPhysicsSpaceIssue.java @@ -60,7 +60,7 @@ public class TestKinematicAddToPhysicsSpaceIssue extends SimpleApplication { bulletAppState = new BulletAppState(); stateManager.attach(bulletAppState); - bulletAppState.getPhysicsSpace().enableDebug(assetManager); + bulletAppState.setDebugEnabled(true); // Add a physics sphere to the world Node physicsSphere = PhysicsTestHelper.createPhysicsTestNode(assetManager, new SphereCollisionShape(1), 1); physicsSphere.getControl(RigidBodyControl.class).setPhysicsLocation(new Vector3f(3, 6, 0)); @@ -69,7 +69,7 @@ public class TestKinematicAddToPhysicsSpaceIssue extends SimpleApplication { //Setting the rigidBody to kinematic before adding it to the physic space physicsSphere.getControl(RigidBodyControl.class).setKinematic(true); //adding it to the physic space - getPhysicsSpace().add(physicsSphere); + getPhysicsSpace().add(physicsSphere); //Making it not kinematic again, it should fall under gravity, it doesn't physicsSphere.getControl(RigidBodyControl.class).setKinematic(false); @@ -77,7 +77,7 @@ public class TestKinematicAddToPhysicsSpaceIssue extends SimpleApplication { Node physicsSphere2 = PhysicsTestHelper.createPhysicsTestNode(assetManager, new SphereCollisionShape(1), 1); physicsSphere2.getControl(RigidBodyControl.class).setPhysicsLocation(new Vector3f(5, 6, 0)); rootNode.attachChild(physicsSphere2); - + //Adding the rigid body to physic space getPhysicsSpace().add(physicsSphere2); //making it kinematic @@ -85,7 +85,7 @@ public class TestKinematicAddToPhysicsSpaceIssue extends SimpleApplication { //Making it not kinematic again, it works properly, the rigidbody is affected by grvity. physicsSphere2.getControl(RigidBodyControl.class).setKinematic(false); - + // an obstacle mesh, does not move (mass=0) Node node2 = PhysicsTestHelper.createPhysicsTestNode(assetManager, new MeshCollisionShape(new Sphere(16, 16, 1.2f)), 0); diff --git a/jme3-examples/src/main/java/jme3test/bullet/TestLocalPhysics.java b/jme3-examples/src/main/java/jme3test/bullet/TestLocalPhysics.java index ed432da47..3835b1ca0 100644 --- a/jme3-examples/src/main/java/jme3test/bullet/TestLocalPhysics.java +++ b/jme3-examples/src/main/java/jme3test/bullet/TestLocalPhysics.java @@ -59,7 +59,7 @@ public class TestLocalPhysics extends SimpleApplication { public void simpleInitApp() { bulletAppState = new BulletAppState(); stateManager.attach(bulletAppState); - bulletAppState.getPhysicsSpace().enableDebug(assetManager); + bulletAppState.setDebugEnabled(true); // Add a physics sphere to the world Node physicsSphere = PhysicsTestHelper.createPhysicsTestNode(assetManager, new SphereCollisionShape(1), 1); diff --git a/jme3-examples/src/main/java/jme3test/bullet/TestPhysicsCar.java b/jme3-examples/src/main/java/jme3test/bullet/TestPhysicsCar.java index 26d7c1a8e..4ba4e060b 100644 --- a/jme3-examples/src/main/java/jme3test/bullet/TestPhysicsCar.java +++ b/jme3-examples/src/main/java/jme3test/bullet/TestPhysicsCar.java @@ -69,7 +69,7 @@ public class TestPhysicsCar extends SimpleApplication implements ActionListener public void simpleInitApp() { bulletAppState = new BulletAppState(); stateManager.attach(bulletAppState); - bulletAppState.getPhysicsSpace().enableDebug(assetManager); + bulletAppState.setDebugEnabled(true); PhysicsTestHelper.createPhysicsTestWorld(rootNode, assetManager, bulletAppState.getPhysicsSpace()); setupKeys(); buildPlayer(); diff --git a/jme3-examples/src/main/java/jme3test/bullet/TestPhysicsHingeJoint.java b/jme3-examples/src/main/java/jme3test/bullet/TestPhysicsHingeJoint.java index f01ad23f9..029892ad9 100644 --- a/jme3-examples/src/main/java/jme3test/bullet/TestPhysicsHingeJoint.java +++ b/jme3-examples/src/main/java/jme3test/bullet/TestPhysicsHingeJoint.java @@ -76,7 +76,7 @@ public class TestPhysicsHingeJoint extends SimpleApplication implements AnalogLi public void simpleInitApp() { bulletAppState = new BulletAppState(); stateManager.attach(bulletAppState); - bulletAppState.getPhysicsSpace().enableDebug(assetManager); + bulletAppState.setDebugEnabled(true); setupKeys(); setupJoint(); } @@ -102,7 +102,7 @@ public class TestPhysicsHingeJoint extends SimpleApplication implements AnalogLi @Override public void simpleUpdate(float tpf) { - + } diff --git a/jme3-examples/src/main/java/jme3test/bullet/TestPhysicsRayCast.java b/jme3-examples/src/main/java/jme3test/bullet/TestPhysicsRayCast.java index c51afd3cc..7a1ea5187 100644 --- a/jme3-examples/src/main/java/jme3test/bullet/TestPhysicsRayCast.java +++ b/jme3-examples/src/main/java/jme3test/bullet/TestPhysicsRayCast.java @@ -1,5 +1,5 @@ package jme3test.bullet; - + import com.jme3.app.SimpleApplication; import com.jme3.bullet.BulletAppState; import com.jme3.bullet.collision.PhysicsCollisionObject; @@ -16,30 +16,30 @@ import java.util.List; * @author @wezrule */ public class TestPhysicsRayCast extends SimpleApplication { - + private BulletAppState bulletAppState = new BulletAppState(); - + public static void main(String[] args) { new TestPhysicsRayCast().start(); } - + @Override public void simpleInitApp() { stateManager.attach(bulletAppState); initCrossHair(); - + Spatial s = assetManager.loadModel("Models/Elephant/Elephant.mesh.xml"); s.setLocalScale(0.1f); - + CollisionShape collisionShape = CollisionShapeFactory.createMeshShape(s); Node n = new Node("elephant"); n.addControl(new RigidBodyControl(collisionShape, 1)); n.getControl(RigidBodyControl.class).setKinematic(true); bulletAppState.getPhysicsSpace().add(n); rootNode.attachChild(n); - bulletAppState.getPhysicsSpace().enableDebug(assetManager); + bulletAppState.setDebugEnabled(true); } - + @Override public void simpleUpdate(float tpf) { List rayTest = bulletAppState.getPhysicsSpace().rayTest(cam.getLocation(), cam.getLocation().add(cam.getDirection())); @@ -50,7 +50,7 @@ public class TestPhysicsRayCast extends SimpleApplication { fpsText.setText(collisionObject.getUserObject().toString()); } } - + private void initCrossHair() { BitmapText bitmapText = new BitmapText(guiFont); bitmapText.setText("+"); diff --git a/jme3-examples/src/main/java/jme3test/bullet/TestPhysicsReadWrite.java b/jme3-examples/src/main/java/jme3test/bullet/TestPhysicsReadWrite.java index 5724f7a16..7d94e0570 100644 --- a/jme3-examples/src/main/java/jme3test/bullet/TestPhysicsReadWrite.java +++ b/jme3-examples/src/main/java/jme3test/bullet/TestPhysicsReadWrite.java @@ -69,7 +69,7 @@ public class TestPhysicsReadWrite extends SimpleApplication{ public void simpleInitApp() { bulletAppState = new BulletAppState(); stateManager.attach(bulletAppState); - bulletAppState.getPhysicsSpace().enableDebug(assetManager); + bulletAppState.setDebugEnabled(true); physicsRootNode=new Node("PhysicsRootNode"); rootNode.attachChild(physicsRootNode); diff --git a/jme3-examples/src/main/java/jme3test/bullet/TestRagDoll.java b/jme3-examples/src/main/java/jme3test/bullet/TestRagDoll.java index 5768bc021..2752ce5a8 100644 --- a/jme3-examples/src/main/java/jme3test/bullet/TestRagDoll.java +++ b/jme3-examples/src/main/java/jme3test/bullet/TestRagDoll.java @@ -64,7 +64,7 @@ public class TestRagDoll extends SimpleApplication implements ActionListener { public void simpleInitApp() { bulletAppState = new BulletAppState(); stateManager.attach(bulletAppState); - bulletAppState.getPhysicsSpace().enableDebug(assetManager); + bulletAppState.setDebugEnabled(true); inputManager.addMapping("Pull ragdoll up", new MouseButtonTrigger(0)); inputManager.addListener(this, "Pull ragdoll up"); PhysicsTestHelper.createPhysicsTestWorld(rootNode, assetManager, bulletAppState.getPhysicsSpace()); diff --git a/jme3-examples/src/main/java/jme3test/bullet/TestSimplePhysics.java b/jme3-examples/src/main/java/jme3test/bullet/TestSimplePhysics.java index 2045e5c77..9cf2808ae 100644 --- a/jme3-examples/src/main/java/jme3test/bullet/TestSimplePhysics.java +++ b/jme3-examples/src/main/java/jme3test/bullet/TestSimplePhysics.java @@ -59,7 +59,7 @@ public class TestSimplePhysics extends SimpleApplication { public void simpleInitApp() { bulletAppState = new BulletAppState(); stateManager.attach(bulletAppState); - bulletAppState.getPhysicsSpace().enableDebug(assetManager); + bulletAppState.setDebugEnabled(true); // Add a physics sphere to the world Node physicsSphere = PhysicsTestHelper.createPhysicsTestNode(assetManager, new SphereCollisionShape(1), 1); diff --git a/jme3-examples/src/main/java/jme3test/bullet/TestSweepTest.java b/jme3-examples/src/main/java/jme3test/bullet/TestSweepTest.java index 6f9e3fdd6..da9089cec 100644 --- a/jme3-examples/src/main/java/jme3test/bullet/TestSweepTest.java +++ b/jme3-examples/src/main/java/jme3test/bullet/TestSweepTest.java @@ -21,8 +21,8 @@ import java.util.List; public class TestSweepTest extends SimpleApplication { private BulletAppState bulletAppState = new BulletAppState(); - private CapsuleCollisionShape obstacleCollisionShape = new CapsuleCollisionShape(0.3f, 0.5f); - private CapsuleCollisionShape capsuleCollisionShape = new CapsuleCollisionShape(1f, 1f); + private CapsuleCollisionShape obstacleCollisionShape; + private CapsuleCollisionShape capsuleCollisionShape; private Node capsule; private Node obstacle; private float dist = .5f; @@ -33,6 +33,9 @@ public class TestSweepTest extends SimpleApplication { @Override public void simpleInitApp() { + obstacleCollisionShape = new CapsuleCollisionShape(0.3f, 0.5f); + capsuleCollisionShape = new CapsuleCollisionShape(1f, 1f); + stateManager.attach(bulletAppState); capsule = new Node("capsule"); @@ -49,21 +52,26 @@ public class TestSweepTest extends SimpleApplication { bulletAppState.getPhysicsSpace().add(obstacle); rootNode.attachChild(obstacle); - bulletAppState.getPhysicsSpace().enableDebug(assetManager); + bulletAppState.setDebugEnabled(true); } @Override public void simpleUpdate(float tpf) { float move = tpf * 1; + boolean colliding = false; List sweepTest = bulletAppState.getPhysicsSpace().sweepTest(capsuleCollisionShape, new Transform(capsule.getWorldTranslation()), new Transform(capsule.getWorldTranslation().add(dist, 0, 0))); - if (sweepTest.size() > 0) { - PhysicsSweepTestResult get = sweepTest.get(0); - PhysicsCollisionObject collisionObject = get.getCollisionObject(); - fpsText.setText("Almost colliding with " + collisionObject.getUserObject().toString()); - } else { + for (PhysicsSweepTestResult result : sweepTest) { + if (result.getCollisionObject().getCollisionShape() != capsuleCollisionShape) { + PhysicsCollisionObject collisionObject = result.getCollisionObject(); + fpsText.setText("Almost colliding with " + collisionObject.getUserObject().toString()); + colliding = true; + } + } + + if (!colliding) { // if the sweep is clear then move the spatial capsule.move(move, 0, 0); } diff --git a/jme3-examples/src/main/java/jme3test/bullet/TestWalkingChar.java b/jme3-examples/src/main/java/jme3test/bullet/TestWalkingChar.java index 6e793da61..a66a6ecc1 100644 --- a/jme3-examples/src/main/java/jme3test/bullet/TestWalkingChar.java +++ b/jme3-examples/src/main/java/jme3test/bullet/TestWalkingChar.java @@ -297,7 +297,7 @@ public class TestWalkingChar extends SimpleApplication implements ActionListener model = (Node) assetManager.loadModel("Models/Oto/Oto.mesh.xml"); //model.setLocalScale(0.5f); model.addControl(character); - character.setPhysicsLocation(new Vector3f(-140, 15, -10)); + character.setPhysicsLocation(new Vector3f(-140, 40, -10)); rootNode.attachChild(model); getPhysicsSpace().add(character); } diff --git a/jme3-examples/src/main/java/jme3test/effect/TestParticleExportingCloning.java b/jme3-examples/src/main/java/jme3test/effect/TestParticleExportingCloning.java index 552287f75..d245de23f 100644 --- a/jme3-examples/src/main/java/jme3test/effect/TestParticleExportingCloning.java +++ b/jme3-examples/src/main/java/jme3test/effect/TestParticleExportingCloning.java @@ -69,26 +69,9 @@ public class TestParticleExportingCloning extends SimpleApplication { rootNode.attachChild(emit); rootNode.attachChild(emit2); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - try { - BinaryExporter.getInstance().save(emit, out); - - BinaryImporter imp = new BinaryImporter(); - imp.setAssetManager(assetManager); - ParticleEmitter emit3 = (ParticleEmitter) imp.load(out.toByteArray()); - - emit3.move(-3, 0, 0); - rootNode.attachChild(emit3); - } catch (IOException ex) { - ex.printStackTrace(); - } - - // Camera cam2 = cam.clone(); - // cam.setViewPortTop(0.5f); - // cam2.setViewPortBottom(0.5f); - // ViewPort vp = renderManager.createMainView("SecondView", cam2); - // viewPort.setClearEnabled(false); - // vp.attachScene(rootNode); + ParticleEmitter emit3 = BinaryExporter.saveAndLoad(assetManager, emit); + emit3.move(-3, 0, 0); + rootNode.attachChild(emit3); } } diff --git a/jme3-examples/src/main/java/jme3test/material/TestParallax.java b/jme3-examples/src/main/java/jme3test/material/TestParallax.java index 37b5e09b0..f5af57f1f 100644 --- a/jme3-examples/src/main/java/jme3test/material/TestParallax.java +++ b/jme3-examples/src/main/java/jme3test/material/TestParallax.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009-2012 jMonkeyEngine + * Copyright (c) 2009-2015 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -39,20 +39,17 @@ import com.jme3.input.controls.KeyTrigger; import com.jme3.light.DirectionalLight; import com.jme3.material.Material; import com.jme3.math.*; -import com.jme3.post.FilterPostProcessor; -import com.jme3.post.filters.FXAAFilter; import com.jme3.renderer.queue.RenderQueue.ShadowMode; import com.jme3.scene.Geometry; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.jme3.scene.shape.Quad; -import com.jme3.texture.Texture.WrapMode; import com.jme3.util.SkyFactory; import com.jme3.util.TangentBinormalGenerator; public class TestParallax extends SimpleApplication { - private Vector3f lightDir = new Vector3f(-1, -1, .5f).normalizeLocal(); + private final Vector3f lightDir = new Vector3f(-1, -1, .5f).normalizeLocal(); public static void main(String[] args) { TestParallax app = new TestParallax(); @@ -60,7 +57,7 @@ public class TestParallax extends SimpleApplication { } public void setupSkyBox() { - rootNode.attachChild(SkyFactory.createSky(assetManager, "Scenes/Beach/FullskiesSunset0068.dds", false)); + rootNode.attachChild(SkyFactory.createSky(assetManager, "Scenes/Beach/FullskiesSunset0068.dds", SkyFactory.EnvMapType.CubeMap)); } DirectionalLight dl; @@ -75,12 +72,7 @@ public class TestParallax extends SimpleApplication { public void setupFloor() { mat = assetManager.loadMaterial("Textures/Terrain/BrickWall/BrickWall2.j3m"); - mat.getTextureParam("DiffuseMap").getTextureValue().setWrap(WrapMode.Repeat); - mat.getTextureParam("NormalMap").getTextureValue().setWrap(WrapMode.Repeat); - - // Node floorGeom = (Node) assetManager.loadAsset("Models/WaterTest/WaterTest.mesh.xml"); - //Geometry g = ((Geometry) floorGeom.getChild(0)); - //g.getMesh().scaleTextureCoordinates(new Vector2f(10, 10)); + //mat = assetManager.loadMaterial("Textures/Terrain/BrickWall/BrickWall.j3m"); Node floorGeom = new Node("floorGeom"); Quad q = new Quad(100, 100); @@ -100,9 +92,9 @@ public class TestParallax extends SimpleApplication { public void setupSignpost() { Spatial signpost = assetManager.loadModel("Models/Sign Post/Sign Post.mesh.xml"); - Material mat = assetManager.loadMaterial("Models/Sign Post/Sign Post.j3m"); + Material matSp = assetManager.loadMaterial("Models/Sign Post/Sign Post.j3m"); TangentBinormalGenerator.generate(signpost); - signpost.setMaterial(mat); + signpost.setMaterial(matSp); signpost.rotate(0, FastMath.HALF_PI, 0); signpost.setLocalTranslation(12, 23.5f, 30); signpost.setLocalScale(4); @@ -116,7 +108,6 @@ public class TestParallax extends SimpleApplication { cam.setRotation(new Quaternion(0.05173137f, 0.92363626f, -0.13454558f, 0.35513034f)); flyCam.setMoveSpeed(30); - setupLighting(); setupSkyBox(); setupFloor(); @@ -124,13 +115,14 @@ public class TestParallax extends SimpleApplication { inputManager.addListener(new AnalogListener() { + @Override public void onAnalog(String name, float value, float tpf) { if ("heightUP".equals(name)) { - parallaxHeigh += 0.0001; + parallaxHeigh += 0.01; mat.setFloat("ParallaxHeight", parallaxHeigh); } if ("heightDown".equals(name)) { - parallaxHeigh -= 0.0001; + parallaxHeigh -= 0.01; parallaxHeigh = Math.max(parallaxHeigh, 0); mat.setFloat("ParallaxHeight", parallaxHeigh); } @@ -142,6 +134,7 @@ public class TestParallax extends SimpleApplication { inputManager.addListener(new ActionListener() { + @Override public void onAction(String name, boolean isPressed, float tpf) { if (isPressed && "toggleSteep".equals(name)) { steep = !steep; diff --git a/jme3-examples/src/main/java/jme3test/model/anim/TestModelExportingCloning.java b/jme3-examples/src/main/java/jme3test/model/anim/TestModelExportingCloning.java new file mode 100644 index 000000000..de162907d --- /dev/null +++ b/jme3-examples/src/main/java/jme3test/model/anim/TestModelExportingCloning.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package jme3test.model.anim; + +import com.jme3.animation.AnimChannel; +import com.jme3.animation.AnimControl; +import com.jme3.app.SimpleApplication; +import com.jme3.export.binary.BinaryExporter; +import com.jme3.light.DirectionalLight; +import com.jme3.math.ColorRGBA; +import com.jme3.math.Vector3f; +import com.jme3.scene.Spatial; + +public class TestModelExportingCloning extends SimpleApplication { + + public static void main(String[] args) { + TestModelExportingCloning app = new TestModelExportingCloning(); + app.start(); + } + + @Override + public void simpleInitApp() { + cam.setLocation(new Vector3f(10f, 3f, 40f)); + cam.lookAtDirection(Vector3f.UNIT_Z.negate(), Vector3f.UNIT_Y); + + DirectionalLight dl = new DirectionalLight(); + dl.setDirection(new Vector3f(-0.1f, -0.7f, -1).normalizeLocal()); + dl.setColor(new ColorRGBA(1f, 1f, 1f, 1.0f)); + rootNode.addLight(dl); + + AnimControl control; + AnimChannel channel; + + Spatial originalModel = assetManager.loadModel("Models/Oto/Oto.mesh.xml"); + control = originalModel.getControl(AnimControl.class); + channel = control.createChannel(); + channel.setAnim("Walk"); + rootNode.attachChild(originalModel); + + Spatial clonedModel = originalModel.clone(); + clonedModel.move(10, 0, 0); + control = clonedModel.getControl(AnimControl.class); + channel = control.createChannel(); + channel.setAnim("push"); + rootNode.attachChild(clonedModel); + + Spatial exportedModel = BinaryExporter.saveAndLoad(assetManager, originalModel); + exportedModel.move(20, 0, 0); + control = exportedModel.getControl(AnimControl.class); + channel = control.createChannel(); + channel.setAnim("pull"); + rootNode.attachChild(exportedModel); + } +} diff --git a/jme3-examples/src/main/java/jme3test/post/TestCartoonEdge.java b/jme3-examples/src/main/java/jme3test/post/TestCartoonEdge.java index 1ca328a8a..ff6ab497f 100644 --- a/jme3-examples/src/main/java/jme3test/post/TestCartoonEdge.java +++ b/jme3-examples/src/main/java/jme3test/post/TestCartoonEdge.java @@ -80,7 +80,7 @@ public class TestCartoonEdge extends SimpleApplication { }else if (spatial instanceof Geometry){ Geometry g = (Geometry) spatial; Material m = g.getMaterial(); - if (m.getMaterialDef().getName().equals("Phong Lighting")){ + if (m.getMaterialDef().getMaterialParam("UseMaterialColors") != null) { Texture t = assetManager.loadTexture("Textures/ColorRamp/toon.png"); // t.setMinFilter(Texture.MinFilter.NearestNoMipMaps); // t.setMagFilter(Texture.MagFilter.Nearest); diff --git a/jme3-examples/src/main/java/jme3test/post/TestPostFiltersCompositing.java b/jme3-examples/src/main/java/jme3test/post/TestPostFiltersCompositing.java index f05276a81..81f9a3a28 100644 --- a/jme3-examples/src/main/java/jme3test/post/TestPostFiltersCompositing.java +++ b/jme3-examples/src/main/java/jme3test/post/TestPostFiltersCompositing.java @@ -32,16 +32,16 @@ package jme3test.post; import com.jme3.app.SimpleApplication; -import com.jme3.asset.plugins.ZipLocator; +import com.jme3.asset.plugins.HttpZipLocator; import com.jme3.light.DirectionalLight; import com.jme3.math.ColorRGBA; import com.jme3.math.Quaternion; import com.jme3.math.Vector3f; import com.jme3.post.FilterPostProcessor; -import com.jme3.post.filters.BloomFilter; import com.jme3.post.filters.ColorOverlayFilter; import com.jme3.post.filters.ComposeFilter; import com.jme3.scene.Spatial; +import com.jme3.system.AppSettings; import com.jme3.texture.FrameBuffer; import com.jme3.texture.Image; import com.jme3.texture.Texture2D; @@ -55,8 +55,12 @@ import com.jme3.util.SkyFactory; public class TestPostFiltersCompositing extends SimpleApplication { public static void main(String[] args) { - TestPostFiltersCompositing app = new TestPostFiltersCompositing(); - app.start(); + TestPostFiltersCompositing app = new TestPostFiltersCompositing(); + AppSettings settings = new AppSettings(true); + settings.putBoolean("GraphicsDebug", false); + app.setSettings(settings); + app.start(); + } public void simpleInitApp() { @@ -76,7 +80,7 @@ public class TestPostFiltersCompositing extends SimpleApplication { Texture2D mainVPTexture = new Texture2D(cam.getWidth(), cam.getHeight(), Image.Format.RGBA8); mainVPFrameBuffer.addColorTexture(mainVPTexture); mainVPFrameBuffer.setDepthBuffer(Image.Format.Depth); - viewPort.setOutputFrameBuffer(mainVPFrameBuffer); + viewPort.setOutputFrameBuffer(mainVPFrameBuffer); //creating the post processor for the gui viewport final FilterPostProcessor guifpp = new FilterPostProcessor(assetManager); @@ -87,17 +91,18 @@ public class TestPostFiltersCompositing extends SimpleApplication { guiViewPort.addProcessor(guifpp); - //compositing is done my mixing texture depending on the alpha channel, + //compositing is done by mixing texture depending on the alpha channel, //it's important that the guiviewport clear color alpha value is set to 0 - guiViewPort.setBackgroundColor(new ColorRGBA(0, 0, 0, 0)); + guiViewPort.setBackgroundColor(ColorRGBA.BlackNoAlpha); + guiViewPort.setClearColor(true); } private void makeScene() { // load sky - rootNode.attachChild(SkyFactory.createSky(assetManager, "Textures/Sky/Bright/BrightSky.dds", false)); - assetManager.registerLocator("wildhouse.zip", ZipLocator.class); + rootNode.attachChild(SkyFactory.createSky(assetManager, "Textures/Sky/Bright/BrightSky.dds", SkyFactory.EnvMapType.CubeMap)); + assetManager.registerLocator("http://jmonkeyengine.googlecode.com/files/wildhouse.zip", HttpZipLocator.class); Spatial scene = assetManager.loadModel("main.scene"); DirectionalLight sun = new DirectionalLight(); sun.setDirection(new Vector3f(-0.4790551f, -0.39247334f, -0.7851566f)); diff --git a/jme3-examples/src/main/java/jme3test/stress/TestShaderNodesStress.java b/jme3-examples/src/main/java/jme3test/stress/TestShaderNodesStress.java new file mode 100644 index 000000000..3364f5feb --- /dev/null +++ b/jme3-examples/src/main/java/jme3test/stress/TestShaderNodesStress.java @@ -0,0 +1,102 @@ +package jme3test.stress; + +import com.jme3.app.BasicProfilerState; +import com.jme3.app.SimpleApplication; +import com.jme3.material.Material; +import com.jme3.math.ColorRGBA; +import com.jme3.math.Quaternion; +import com.jme3.math.Vector3f; +import com.jme3.profile.AppProfiler; +import com.jme3.profile.AppStep; +import com.jme3.profile.VpStep; +import com.jme3.renderer.ViewPort; +import com.jme3.renderer.queue.RenderQueue; +import com.jme3.scene.Geometry; +import com.jme3.scene.shape.Quad; +import com.jme3.texture.Texture; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class TestShaderNodesStress extends SimpleApplication { + + public static void main(String[] args) { + TestShaderNodesStress app = new TestShaderNodesStress(); + app.start(); + } + + @Override + public void simpleInitApp() { + + Quad q = new Quad(1, 1); + Geometry g = new Geometry("quad", q); + g.setLocalTranslation(-500, -500, 0); + g.setLocalScale(1000); + + rootNode.attachChild(g); + cam.setLocation(new Vector3f(0.0f, 0.0f, 0.40647888f)); + cam.setRotation(new Quaternion(0.0f, 1.0f, 0.0f, 0.0f)); + + Texture tex = assetManager.loadTexture("Interface/Logo/Monkey.jpg"); + + Material mat = new Material(assetManager, "Common/MatDefs/Misc/UnshadedNodes.j3md"); + //Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); + + mat.setColor("Color", ColorRGBA.Yellow); + mat.setTexture("ColorMap", tex); + g.setMaterial(mat); + //place the geoms in the transparent bucket so that they are rendered back to front for maximum overdraw + g.setQueueBucket(RenderQueue.Bucket.Transparent); + + for (int i = 0; i < 1000; i++) { + Geometry cl = g.clone(false); + cl.move(0, 0, -(i + 1)); + rootNode.attachChild(cl); + } + + flyCam.setMoveSpeed(20); + Logger.getLogger("com.jme3").setLevel(Level.WARNING); + + this.setAppProfiler(new Profiler()); + + } + + private class Profiler implements AppProfiler { + + private long startTime; + private long updateTime; + private long renderTime; + private long sum; + private int nbFrames; + + @Override + public void appStep(AppStep step) { + + switch (step) { + case BeginFrame: + startTime = System.nanoTime(); + break; + case RenderFrame: + updateTime = System.nanoTime(); + // System.err.println("Update time : " + (updateTime - startTime)); + break; + case EndFrame: + nbFrames++; + if (nbFrames >= 150) { + renderTime = System.nanoTime(); + sum += renderTime - updateTime; + System.err.println("render time : " + (renderTime - updateTime)); + System.err.println("Average render time : " + ((float)sum / (float)(nbFrames-150))); + } + break; + + } + + } + + @Override + public void vpStep(VpStep step, ViewPort vp, RenderQueue.Bucket bucket) { + + } + + } +} diff --git a/jme3-examples/src/main/resources/jme3test/texture/UnshadedArray.frag b/jme3-examples/src/main/resources/jme3test/texture/UnshadedArray.frag index 4cd92cff9..355cf6092 100644 --- a/jme3-examples/src/main/resources/jme3test/texture/UnshadedArray.frag +++ b/jme3-examples/src/main/resources/jme3test/texture/UnshadedArray.frag @@ -1,5 +1,5 @@ #extension GL_EXT_texture_array : enable -#extension GL_EXT_gpu_shader4 : enable +// #extension GL_EXT_gpu_shader4 : enable uniform vec4 m_Color; @@ -8,7 +8,7 @@ uniform vec4 m_Color; #endif #ifdef HAS_COLORMAP - #if !defined(GL_EXT_texture_array) && !defined(GL_EXT_gpu_shader4) + #if !defined(GL_EXT_texture_array) #error Texture arrays are not supported, but required for this shader. #endif diff --git a/jme3-ios/src/main/java/com/jme3/asset/IOS.cfg b/jme3-ios/src/main/java/com/jme3/asset/IOS.cfg index 715eab985..e9d79a459 100644 --- a/jme3-ios/src/main/java/com/jme3/asset/IOS.cfg +++ b/jme3-ios/src/main/java/com/jme3/asset/IOS.cfg @@ -2,3 +2,9 @@ INCLUDE com/jme3/asset/General.cfg # IOS specific loaders LOADER com.jme3.system.ios.IosImageLoader : jpg, bmp, gif, png, jpeg +LOADER com.jme3.audio.plugins.OGGLoader : ogg +LOADER com.jme3.material.plugins.J3MLoader : j3m +LOADER com.jme3.material.plugins.J3MLoader : j3md +LOADER com.jme3.shader.plugins.GLSLLoader : vert, frag, glsl, glsllib +LOADER com.jme3.export.binary.BinaryImporter : j3o +LOADER com.jme3.font.plugins.BitmapFontLoader : fnt diff --git a/jme3-ios/src/main/java/com/jme3/audio/android/AL.java b/jme3-ios/src/main/java/com/jme3/audio/android/AL.java deleted file mode 100644 index d8fea3933..000000000 --- a/jme3-ios/src/main/java/com/jme3/audio/android/AL.java +++ /dev/null @@ -1,1054 +0,0 @@ -package com.jme3.audio.android; - -/** - * - * @author iwgeric - */ -public class AL { - - - - /* ********** */ - /* FROM ALC.h */ - /* ********** */ - -// typedef struct ALCdevice_struct ALCdevice; -// typedef struct ALCcontext_struct ALCcontext; - - - /** - * No error - */ - static final int ALC_NO_ERROR = 0; - - /** - * No device - */ - static final int ALC_INVALID_DEVICE = 0xA001; - - /** - * invalid context ID - */ - static final int ALC_INVALID_CONTEXT = 0xA002; - - /** - * bad enum - */ - static final int ALC_INVALID_ENUM = 0xA003; - - /** - * bad value - */ - static final int ALC_INVALID_VALUE = 0xA004; - - /** - * Out of memory. - */ - static final int ALC_OUT_OF_MEMORY = 0xA005; - - - /** - * The Specifier string for default device - */ - static final int ALC_DEFAULT_DEVICE_SPECIFIER = 0x1004; - static final int ALC_DEVICE_SPECIFIER = 0x1005; - static final int ALC_EXTENSIONS = 0x1006; - - static final int ALC_MAJOR_VERSION = 0x1000; - static final int ALC_MINOR_VERSION = 0x1001; - - static final int ALC_ATTRIBUTES_SIZE = 0x1002; - static final int ALC_ALL_ATTRIBUTES = 0x1003; - - - /** - * Capture extension - */ - static final int ALC_EXT_CAPTURE = 1; - static final int ALC_CAPTURE_DEVICE_SPECIFIER = 0x310; - static final int ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER = 0x311; - static final int ALC_CAPTURE_SAMPLES = 0x312; - - - /** - * ALC_ENUMERATE_ALL_EXT enums - */ - static final int ALC_ENUMERATE_ALL_EXT = 1; - static final int ALC_DEFAULT_ALL_DEVICES_SPECIFIER = 0x1012; - static final int ALC_ALL_DEVICES_SPECIFIER = 0x1013; - - - /* ********** */ - /* FROM AL.h */ - /* ********** */ - -/** Boolean False. */ - static final int AL_FALSE = 0; - -/** Boolean True. */ - static final int AL_TRUE = 1; - -/* "no distance model" or "no buffer" */ - static final int AL_NONE = 0; - -/** Indicate Source has relative coordinates. */ - static final int AL_SOURCE_RELATIVE = 0x202; - - - -/** - * Directional source, inner cone angle, in degrees. - * Range: [0-360] - * Default: 360 - */ - static final int AL_CONE_INNER_ANGLE = 0x1001; - -/** - * Directional source, outer cone angle, in degrees. - * Range: [0-360] - * Default: 360 - */ - static final int AL_CONE_OUTER_ANGLE = 0x1002; - -/** - * Specify the pitch to be applied at source. - * Range: [0.5-2.0] - * Default: 1.0 - */ - static final int AL_PITCH = 0x1003; - -/** - * Specify the current location in three dimensional space. - * OpenAL, like OpenGL, uses a right handed coordinate system, - * where in a frontal default view X (thumb) points right, - * Y points up (index finger), and Z points towards the - * viewer/camera (middle finger). - * To switch from a left handed coordinate system, flip the - * sign on the Z coordinate. - * Listener position is always in the world coordinate system. - */ - static final int AL_POSITION = 0x1004; - -/** Specify the current direction. */ - static final int AL_DIRECTION = 0x1005; - -/** Specify the current velocity in three dimensional space. */ - static final int AL_VELOCITY = 0x1006; - -/** - * Indicate whether source is looping. - * Type: ALboolean? - * Range: [AL_TRUE, AL_FALSE] - * Default: FALSE. - */ - static final int AL_LOOPING = 0x1007; - -/** - * Indicate the buffer to provide sound samples. - * Type: ALuint. - * Range: any valid Buffer id. - */ - static final int AL_BUFFER = 0x1009; - -/** - * Indicate the gain (volume amplification) applied. - * Type: ALfloat. - * Range: ]0.0- ] - * A value of 1.0 means un-attenuated/unchanged. - * Each division by 2 equals an attenuation of -6dB. - * Each multiplicaton with 2 equals an amplification of +6dB. - * A value of 0.0 is meaningless with respect to a logarithmic - * scale; it is interpreted as zero volume - the channel - * is effectively disabled. - */ - static final int AL_GAIN = 0x100A; - -/* - * Indicate minimum source attenuation - * Type: ALfloat - * Range: [0.0 - 1.0] - * - * Logarthmic - */ - static final int AL_MIN_GAIN = 0x100D; - -/** - * Indicate maximum source attenuation - * Type: ALfloat - * Range: [0.0 - 1.0] - * - * Logarthmic - */ - static final int AL_MAX_GAIN = 0x100E; - -/** - * Indicate listener orientation. - * - * at/up - */ - static final int AL_ORIENTATION = 0x100F; - -/** - * Source state information. - */ - static final int AL_SOURCE_STATE = 0x1010; - static final int AL_INITIAL = 0x1011; - static final int AL_PLAYING = 0x1012; - static final int AL_PAUSED = 0x1013; - static final int AL_STOPPED = 0x1014; - -/** - * Buffer Queue params - */ - static final int AL_BUFFERS_QUEUED = 0x1015; - static final int AL_BUFFERS_PROCESSED = 0x1016; - -/** - * Source buffer position information - */ - static final int AL_SEC_OFFSET = 0x1024; - static final int AL_SAMPLE_OFFSET = 0x1025; - static final int AL_BYTE_OFFSET = 0x1026; - -/* - * Source type (Static, Streaming or undetermined) - * Source is Static if a Buffer has been attached using AL_BUFFER - * Source is Streaming if one or more Buffers have been attached using alSourceQueueBuffers - * Source is undetermined when it has the NULL buffer attached - */ - static final int AL_SOURCE_TYPE = 0x1027; - static final int AL_STATIC = 0x1028; - static final int AL_STREAMING = 0x1029; - static final int AL_UNDETERMINED = 0x1030; - -/** Sound samples: format specifier. */ - static final int AL_FORMAT_MONO8 = 0x1100; - static final int AL_FORMAT_MONO16 = 0x1101; - static final int AL_FORMAT_STEREO8 = 0x1102; - static final int AL_FORMAT_STEREO16 = 0x1103; - -/** - * source specific reference distance - * Type: ALfloat - * Range: 0.0 - +inf - * - * At 0.0, no distance attenuation occurs. Default is - * 1.0. - */ - static final int AL_REFERENCE_DISTANCE = 0x1020; - -/** - * source specific rolloff factor - * Type: ALfloat - * Range: 0.0 - +inf - * - */ - static final int AL_ROLLOFF_FACTOR = 0x1021; - -/** - * Directional source, outer cone gain. - * - * Default: 0.0 - * Range: [0.0 - 1.0] - * Logarithmic - */ - static final int AL_CONE_OUTER_GAIN = 0x1022; - -/** - * Indicate distance above which sources are not - * attenuated using the inverse clamped distance model. - * - * Default: +inf - * Type: ALfloat - * Range: 0.0 - +inf - */ - static final int AL_MAX_DISTANCE = 0x1023; - -/** - * Sound samples: frequency, in units of Hertz [Hz]. - * This is the number of samples per second. Half of the - * sample frequency marks the maximum significant - * frequency component. - */ - static final int AL_FREQUENCY = 0x2001; - static final int AL_BITS = 0x2002; - static final int AL_CHANNELS = 0x2003; - static final int AL_SIZE = 0x2004; - -/** - * Buffer state. - * - * Not supported for public use (yet). - */ - static final int AL_UNUSED = 0x2010; - static final int AL_PENDING = 0x2011; - static final int AL_PROCESSED = 0x2012; - - -/** Errors: No Error. */ - static final int AL_NO_ERROR = 0; - -/** - * Invalid Name paramater passed to AL call. - */ - static final int AL_INVALID_NAME = 0xA001; - -/** - * Invalid parameter passed to AL call. - */ - static final int AL_INVALID_ENUM = 0xA002; - -/** - * Invalid enum parameter value. - */ - static final int AL_INVALID_VALUE = 0xA003; - -/** - * Illegal call. - */ - static final int AL_INVALID_OPERATION = 0xA004; - - -/** - * No mojo. - */ - static final int AL_OUT_OF_MEMORY = 0xA005; - - -/** Context strings: Vendor Name. */ - static final int AL_VENDOR = 0xB001; - static final int AL_VERSION = 0xB002; - static final int AL_RENDERER = 0xB003; - static final int AL_EXTENSIONS = 0xB004; - -/** Global tweakage. */ - -/** - * Doppler scale. Default 1.0 - */ - static final int AL_DOPPLER_FACTOR = 0xC000; - -/** - * Tweaks speed of propagation. - */ - static final int AL_DOPPLER_VELOCITY = 0xC001; - -/** - * Speed of Sound in units per second - */ - static final int AL_SPEED_OF_SOUND = 0xC003; - -/** - * Distance models - * - * used in conjunction with DistanceModel - * - * implicit: NONE, which disances distance attenuation. - */ - static final int AL_DISTANCE_MODEL = 0xD000; - static final int AL_INVERSE_DISTANCE = 0xD001; - static final int AL_INVERSE_DISTANCE_CLAMPED = 0xD002; - static final int AL_LINEAR_DISTANCE = 0xD003; - static final int AL_LINEAR_DISTANCE_CLAMPED = 0xD004; - static final int AL_EXPONENT_DISTANCE = 0xD005; - static final int AL_EXPONENT_DISTANCE_CLAMPED = 0xD006; - - /* ********** */ - /* FROM efx.h */ - /* ********** */ - - static final String ALC_EXT_EFX_NAME = "ALC_EXT_EFX"; - - static final int ALC_EFX_MAJOR_VERSION = 0x20001; - static final int ALC_EFX_MINOR_VERSION = 0x20002; - static final int ALC_MAX_AUXILIARY_SENDS = 0x20003; - - -///* Listener properties. */ -//#define AL_METERS_PER_UNIT 0x20004 -// -///* Source properties. */ - static final int AL_DIRECT_FILTER = 0x20005; - static final int AL_AUXILIARY_SEND_FILTER = 0x20006; -//#define AL_AIR_ABSORPTION_FACTOR 0x20007 -//#define AL_ROOM_ROLLOFF_FACTOR 0x20008 -//#define AL_CONE_OUTER_GAINHF 0x20009 - static final int AL_DIRECT_FILTER_GAINHF_AUTO = 0x2000A; -//#define AL_AUXILIARY_SEND_FILTER_GAIN_AUTO 0x2000B -//#define AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO 0x2000C -// -// -///* Effect properties. */ -// -///* Reverb effect parameters */ - static final int AL_REVERB_DENSITY = 0x0001; - static final int AL_REVERB_DIFFUSION = 0x0002; - static final int AL_REVERB_GAIN = 0x0003; - static final int AL_REVERB_GAINHF = 0x0004; - static final int AL_REVERB_DECAY_TIME = 0x0005; - static final int AL_REVERB_DECAY_HFRATIO = 0x0006; - static final int AL_REVERB_REFLECTIONS_GAIN = 0x0007; - static final int AL_REVERB_REFLECTIONS_DELAY = 0x0008; - static final int AL_REVERB_LATE_REVERB_GAIN = 0x0009; - static final int AL_REVERB_LATE_REVERB_DELAY = 0x000A; - static final int AL_REVERB_AIR_ABSORPTION_GAINHF = 0x000B; - static final int AL_REVERB_ROOM_ROLLOFF_FACTOR = 0x000C; - static final int AL_REVERB_DECAY_HFLIMIT = 0x000D; - -///* EAX Reverb effect parameters */ -//#define AL_EAXREVERB_DENSITY 0x0001 -//#define AL_EAXREVERB_DIFFUSION 0x0002 -//#define AL_EAXREVERB_GAIN 0x0003 -//#define AL_EAXREVERB_GAINHF 0x0004 -//#define AL_EAXREVERB_GAINLF 0x0005 -//#define AL_EAXREVERB_DECAY_TIME 0x0006 -//#define AL_EAXREVERB_DECAY_HFRATIO 0x0007 -//#define AL_EAXREVERB_DECAY_LFRATIO 0x0008 -//#define AL_EAXREVERB_REFLECTIONS_GAIN 0x0009 -//#define AL_EAXREVERB_REFLECTIONS_DELAY 0x000A -//#define AL_EAXREVERB_REFLECTIONS_PAN 0x000B -//#define AL_EAXREVERB_LATE_REVERB_GAIN 0x000C -//#define AL_EAXREVERB_LATE_REVERB_DELAY 0x000D -//#define AL_EAXREVERB_LATE_REVERB_PAN 0x000E -//#define AL_EAXREVERB_ECHO_TIME 0x000F -//#define AL_EAXREVERB_ECHO_DEPTH 0x0010 -//#define AL_EAXREVERB_MODULATION_TIME 0x0011 -//#define AL_EAXREVERB_MODULATION_DEPTH 0x0012 -//#define AL_EAXREVERB_AIR_ABSORPTION_GAINHF 0x0013 -//#define AL_EAXREVERB_HFREFERENCE 0x0014 -//#define AL_EAXREVERB_LFREFERENCE 0x0015 -//#define AL_EAXREVERB_ROOM_ROLLOFF_FACTOR 0x0016 -//#define AL_EAXREVERB_DECAY_HFLIMIT 0x0017 -// -///* Chorus effect parameters */ -//#define AL_CHORUS_WAVEFORM 0x0001 -//#define AL_CHORUS_PHASE 0x0002 -//#define AL_CHORUS_RATE 0x0003 -//#define AL_CHORUS_DEPTH 0x0004 -//#define AL_CHORUS_FEEDBACK 0x0005 -//#define AL_CHORUS_DELAY 0x0006 -// -///* Distortion effect parameters */ -//#define AL_DISTORTION_EDGE 0x0001 -//#define AL_DISTORTION_GAIN 0x0002 -//#define AL_DISTORTION_LOWPASS_CUTOFF 0x0003 -//#define AL_DISTORTION_EQCENTER 0x0004 -//#define AL_DISTORTION_EQBANDWIDTH 0x0005 -// -///* Echo effect parameters */ -//#define AL_ECHO_DELAY 0x0001 -//#define AL_ECHO_LRDELAY 0x0002 -//#define AL_ECHO_DAMPING 0x0003 -//#define AL_ECHO_FEEDBACK 0x0004 -//#define AL_ECHO_SPREAD 0x0005 -// -///* Flanger effect parameters */ -//#define AL_FLANGER_WAVEFORM 0x0001 -//#define AL_FLANGER_PHASE 0x0002 -//#define AL_FLANGER_RATE 0x0003 -//#define AL_FLANGER_DEPTH 0x0004 -//#define AL_FLANGER_FEEDBACK 0x0005 -//#define AL_FLANGER_DELAY 0x0006 -// -///* Frequency shifter effect parameters */ -//#define AL_FREQUENCY_SHIFTER_FREQUENCY 0x0001 -//#define AL_FREQUENCY_SHIFTER_LEFT_DIRECTION 0x0002 -//#define AL_FREQUENCY_SHIFTER_RIGHT_DIRECTION 0x0003 -// -///* Vocal morpher effect parameters */ -//#define AL_VOCAL_MORPHER_PHONEMEA 0x0001 -//#define AL_VOCAL_MORPHER_PHONEMEA_COARSE_TUNING 0x0002 -//#define AL_VOCAL_MORPHER_PHONEMEB 0x0003 -//#define AL_VOCAL_MORPHER_PHONEMEB_COARSE_TUNING 0x0004 -//#define AL_VOCAL_MORPHER_WAVEFORM 0x0005 -//#define AL_VOCAL_MORPHER_RATE 0x0006 -// -///* Pitchshifter effect parameters */ -//#define AL_PITCH_SHIFTER_COARSE_TUNE 0x0001 -//#define AL_PITCH_SHIFTER_FINE_TUNE 0x0002 -// -///* Ringmodulator effect parameters */ -//#define AL_RING_MODULATOR_FREQUENCY 0x0001 -//#define AL_RING_MODULATOR_HIGHPASS_CUTOFF 0x0002 -//#define AL_RING_MODULATOR_WAVEFORM 0x0003 -// -///* Autowah effect parameters */ -//#define AL_AUTOWAH_ATTACK_TIME 0x0001 -//#define AL_AUTOWAH_RELEASE_TIME 0x0002 -//#define AL_AUTOWAH_RESONANCE 0x0003 -//#define AL_AUTOWAH_PEAK_GAIN 0x0004 -// -///* Compressor effect parameters */ -//#define AL_COMPRESSOR_ONOFF 0x0001 -// -///* Equalizer effect parameters */ -//#define AL_EQUALIZER_LOW_GAIN 0x0001 -//#define AL_EQUALIZER_LOW_CUTOFF 0x0002 -//#define AL_EQUALIZER_MID1_GAIN 0x0003 -//#define AL_EQUALIZER_MID1_CENTER 0x0004 -//#define AL_EQUALIZER_MID1_WIDTH 0x0005 -//#define AL_EQUALIZER_MID2_GAIN 0x0006 -//#define AL_EQUALIZER_MID2_CENTER 0x0007 -//#define AL_EQUALIZER_MID2_WIDTH 0x0008 -//#define AL_EQUALIZER_HIGH_GAIN 0x0009 -//#define AL_EQUALIZER_HIGH_CUTOFF 0x000A -// -///* Effect type */ -//#define AL_EFFECT_FIRST_PARAMETER 0x0000 -//#define AL_EFFECT_LAST_PARAMETER 0x8000 - static final int AL_EFFECT_TYPE = 0x8001; -// -///* Effect types, used with the AL_EFFECT_TYPE property */ -//#define AL_EFFECT_NULL 0x0000 - static final int AL_EFFECT_REVERB = 0x0001; -//#define AL_EFFECT_CHORUS 0x0002 -//#define AL_EFFECT_DISTORTION 0x0003 -//#define AL_EFFECT_ECHO 0x0004 -//#define AL_EFFECT_FLANGER 0x0005 -//#define AL_EFFECT_FREQUENCY_SHIFTER 0x0006 -//#define AL_EFFECT_VOCAL_MORPHER 0x0007 -//#define AL_EFFECT_PITCH_SHIFTER 0x0008 -//#define AL_EFFECT_RING_MODULATOR 0x0009 -//#define AL_EFFECT_AUTOWAH 0x000A -//#define AL_EFFECT_COMPRESSOR 0x000B -//#define AL_EFFECT_EQUALIZER 0x000C -//#define AL_EFFECT_EAXREVERB 0x8000 -// -///* Auxiliary Effect Slot properties. */ - static final int AL_EFFECTSLOT_EFFECT = 0x0001; -//#define AL_EFFECTSLOT_GAIN 0x0002 -//#define AL_EFFECTSLOT_AUXILIARY_SEND_AUTO 0x0003 -// -///* NULL Auxiliary Slot ID to disable a source send. */ -//#define AL_EFFECTSLOT_NULL 0x0000 -// -// -///* Filter properties. */ -// -///* Lowpass filter parameters */ - static final int AL_LOWPASS_GAIN = 0x0001; - static final int AL_LOWPASS_GAINHF = 0x0002; -// -///* Highpass filter parameters */ -//#define AL_HIGHPASS_GAIN 0x0001 -//#define AL_HIGHPASS_GAINLF 0x0002 -// -///* Bandpass filter parameters */ -//#define AL_BANDPASS_GAIN 0x0001 -//#define AL_BANDPASS_GAINLF 0x0002 -//#define AL_BANDPASS_GAINHF 0x0003 -// -///* Filter type */ -//#define AL_FILTER_FIRST_PARAMETER 0x0000 -//#define AL_FILTER_LAST_PARAMETER 0x8000 - static final int AL_FILTER_TYPE = 0x8001; -// -///* Filter types, used with the AL_FILTER_TYPE property */ - static final int AL_FILTER_NULL = 0x0000; - static final int AL_FILTER_LOWPASS = 0x0001; - static final int AL_FILTER_HIGHPASS = 0x0002; -//#define AL_FILTER_BANDPASS 0x0003 -// -///* Filter ranges and defaults. */ -// -///* Lowpass filter */ -//#define AL_LOWPASS_MIN_GAIN (0.0f) -//#define AL_LOWPASS_MAX_GAIN (1.0f) -//#define AL_LOWPASS_DEFAULT_GAIN (1.0f) -// -//#define AL_LOWPASS_MIN_GAINHF (0.0f) -//#define AL_LOWPASS_MAX_GAINHF (1.0f) -//#define AL_LOWPASS_DEFAULT_GAINHF (1.0f) -// -///* Highpass filter */ -//#define AL_HIGHPASS_MIN_GAIN (0.0f) -//#define AL_HIGHPASS_MAX_GAIN (1.0f) -//#define AL_HIGHPASS_DEFAULT_GAIN (1.0f) -// -//#define AL_HIGHPASS_MIN_GAINLF (0.0f) -//#define AL_HIGHPASS_MAX_GAINLF (1.0f) -//#define AL_HIGHPASS_DEFAULT_GAINLF (1.0f) -// -///* Bandpass filter */ -//#define AL_BANDPASS_MIN_GAIN (0.0f) -//#define AL_BANDPASS_MAX_GAIN (1.0f) -//#define AL_BANDPASS_DEFAULT_GAIN (1.0f) -// -//#define AL_BANDPASS_MIN_GAINHF (0.0f) -//#define AL_BANDPASS_MAX_GAINHF (1.0f) -//#define AL_BANDPASS_DEFAULT_GAINHF (1.0f) -// -//#define AL_BANDPASS_MIN_GAINLF (0.0f) -//#define AL_BANDPASS_MAX_GAINLF (1.0f) -//#define AL_BANDPASS_DEFAULT_GAINLF (1.0f) -// -// -///* Effect parameter ranges and defaults. */ -// -///* Standard reverb effect */ -//#define AL_REVERB_MIN_DENSITY (0.0f) -//#define AL_REVERB_MAX_DENSITY (1.0f) -//#define AL_REVERB_DEFAULT_DENSITY (1.0f) -// -//#define AL_REVERB_MIN_DIFFUSION (0.0f) -//#define AL_REVERB_MAX_DIFFUSION (1.0f) -//#define AL_REVERB_DEFAULT_DIFFUSION (1.0f) -// -//#define AL_REVERB_MIN_GAIN (0.0f) -//#define AL_REVERB_MAX_GAIN (1.0f) -//#define AL_REVERB_DEFAULT_GAIN (0.32f) -// -//#define AL_REVERB_MIN_GAINHF (0.0f) -//#define AL_REVERB_MAX_GAINHF (1.0f) -//#define AL_REVERB_DEFAULT_GAINHF (0.89f) -// -//#define AL_REVERB_MIN_DECAY_TIME (0.1f) -//#define AL_REVERB_MAX_DECAY_TIME (20.0f) -//#define AL_REVERB_DEFAULT_DECAY_TIME (1.49f) -// -//#define AL_REVERB_MIN_DECAY_HFRATIO (0.1f) -//#define AL_REVERB_MAX_DECAY_HFRATIO (2.0f) -//#define AL_REVERB_DEFAULT_DECAY_HFRATIO (0.83f) -// -//#define AL_REVERB_MIN_REFLECTIONS_GAIN (0.0f) -//#define AL_REVERB_MAX_REFLECTIONS_GAIN (3.16f) -//#define AL_REVERB_DEFAULT_REFLECTIONS_GAIN (0.05f) -// -//#define AL_REVERB_MIN_REFLECTIONS_DELAY (0.0f) -//#define AL_REVERB_MAX_REFLECTIONS_DELAY (0.3f) -//#define AL_REVERB_DEFAULT_REFLECTIONS_DELAY (0.007f) -// -//#define AL_REVERB_MIN_LATE_REVERB_GAIN (0.0f) -//#define AL_REVERB_MAX_LATE_REVERB_GAIN (10.0f) -//#define AL_REVERB_DEFAULT_LATE_REVERB_GAIN (1.26f) -// -//#define AL_REVERB_MIN_LATE_REVERB_DELAY (0.0f) -//#define AL_REVERB_MAX_LATE_REVERB_DELAY (0.1f) -//#define AL_REVERB_DEFAULT_LATE_REVERB_DELAY (0.011f) -// -//#define AL_REVERB_MIN_AIR_ABSORPTION_GAINHF (0.892f) -//#define AL_REVERB_MAX_AIR_ABSORPTION_GAINHF (1.0f) -//#define AL_REVERB_DEFAULT_AIR_ABSORPTION_GAINHF (0.994f) -// -//#define AL_REVERB_MIN_ROOM_ROLLOFF_FACTOR (0.0f) -//#define AL_REVERB_MAX_ROOM_ROLLOFF_FACTOR (10.0f) -//#define AL_REVERB_DEFAULT_ROOM_ROLLOFF_FACTOR (0.0f) -// -//#define AL_REVERB_MIN_DECAY_HFLIMIT AL_FALSE -//#define AL_REVERB_MAX_DECAY_HFLIMIT AL_TRUE -//#define AL_REVERB_DEFAULT_DECAY_HFLIMIT AL_TRUE -// -///* EAX reverb effect */ -//#define AL_EAXREVERB_MIN_DENSITY (0.0f) -//#define AL_EAXREVERB_MAX_DENSITY (1.0f) -//#define AL_EAXREVERB_DEFAULT_DENSITY (1.0f) -// -//#define AL_EAXREVERB_MIN_DIFFUSION (0.0f) -//#define AL_EAXREVERB_MAX_DIFFUSION (1.0f) -//#define AL_EAXREVERB_DEFAULT_DIFFUSION (1.0f) -// -//#define AL_EAXREVERB_MIN_GAIN (0.0f) -//#define AL_EAXREVERB_MAX_GAIN (1.0f) -//#define AL_EAXREVERB_DEFAULT_GAIN (0.32f) -// -//#define AL_EAXREVERB_MIN_GAINHF (0.0f) -//#define AL_EAXREVERB_MAX_GAINHF (1.0f) -//#define AL_EAXREVERB_DEFAULT_GAINHF (0.89f) -// -//#define AL_EAXREVERB_MIN_GAINLF (0.0f) -//#define AL_EAXREVERB_MAX_GAINLF (1.0f) -//#define AL_EAXREVERB_DEFAULT_GAINLF (1.0f) -// -//#define AL_EAXREVERB_MIN_DECAY_TIME (0.1f) -//#define AL_EAXREVERB_MAX_DECAY_TIME (20.0f) -//#define AL_EAXREVERB_DEFAULT_DECAY_TIME (1.49f) -// -//#define AL_EAXREVERB_MIN_DECAY_HFRATIO (0.1f) -//#define AL_EAXREVERB_MAX_DECAY_HFRATIO (2.0f) -//#define AL_EAXREVERB_DEFAULT_DECAY_HFRATIO (0.83f) -// -//#define AL_EAXREVERB_MIN_DECAY_LFRATIO (0.1f) -//#define AL_EAXREVERB_MAX_DECAY_LFRATIO (2.0f) -//#define AL_EAXREVERB_DEFAULT_DECAY_LFRATIO (1.0f) -// -//#define AL_EAXREVERB_MIN_REFLECTIONS_GAIN (0.0f) -//#define AL_EAXREVERB_MAX_REFLECTIONS_GAIN (3.16f) -//#define AL_EAXREVERB_DEFAULT_REFLECTIONS_GAIN (0.05f) -// -//#define AL_EAXREVERB_MIN_REFLECTIONS_DELAY (0.0f) -//#define AL_EAXREVERB_MAX_REFLECTIONS_DELAY (0.3f) -//#define AL_EAXREVERB_DEFAULT_REFLECTIONS_DELAY (0.007f) -// -//#define AL_EAXREVERB_DEFAULT_REFLECTIONS_PAN_XYZ (0.0f) -// -//#define AL_EAXREVERB_MIN_LATE_REVERB_GAIN (0.0f) -//#define AL_EAXREVERB_MAX_LATE_REVERB_GAIN (10.0f) -//#define AL_EAXREVERB_DEFAULT_LATE_REVERB_GAIN (1.26f) -// -//#define AL_EAXREVERB_MIN_LATE_REVERB_DELAY (0.0f) -//#define AL_EAXREVERB_MAX_LATE_REVERB_DELAY (0.1f) -//#define AL_EAXREVERB_DEFAULT_LATE_REVERB_DELAY (0.011f) -// -//#define AL_EAXREVERB_DEFAULT_LATE_REVERB_PAN_XYZ (0.0f) -// -//#define AL_EAXREVERB_MIN_ECHO_TIME (0.075f) -//#define AL_EAXREVERB_MAX_ECHO_TIME (0.25f) -//#define AL_EAXREVERB_DEFAULT_ECHO_TIME (0.25f) -// -//#define AL_EAXREVERB_MIN_ECHO_DEPTH (0.0f) -//#define AL_EAXREVERB_MAX_ECHO_DEPTH (1.0f) -//#define AL_EAXREVERB_DEFAULT_ECHO_DEPTH (0.0f) -// -//#define AL_EAXREVERB_MIN_MODULATION_TIME (0.04f) -//#define AL_EAXREVERB_MAX_MODULATION_TIME (4.0f) -//#define AL_EAXREVERB_DEFAULT_MODULATION_TIME (0.25f) -// -//#define AL_EAXREVERB_MIN_MODULATION_DEPTH (0.0f) -//#define AL_EAXREVERB_MAX_MODULATION_DEPTH (1.0f) -//#define AL_EAXREVERB_DEFAULT_MODULATION_DEPTH (0.0f) -// -//#define AL_EAXREVERB_MIN_AIR_ABSORPTION_GAINHF (0.892f) -//#define AL_EAXREVERB_MAX_AIR_ABSORPTION_GAINHF (1.0f) -//#define AL_EAXREVERB_DEFAULT_AIR_ABSORPTION_GAINHF (0.994f) -// -//#define AL_EAXREVERB_MIN_HFREFERENCE (1000.0f) -//#define AL_EAXREVERB_MAX_HFREFERENCE (20000.0f) -//#define AL_EAXREVERB_DEFAULT_HFREFERENCE (5000.0f) -// -//#define AL_EAXREVERB_MIN_LFREFERENCE (20.0f) -//#define AL_EAXREVERB_MAX_LFREFERENCE (1000.0f) -//#define AL_EAXREVERB_DEFAULT_LFREFERENCE (250.0f) -// -//#define AL_EAXREVERB_MIN_ROOM_ROLLOFF_FACTOR (0.0f) -//#define AL_EAXREVERB_MAX_ROOM_ROLLOFF_FACTOR (10.0f) -//#define AL_EAXREVERB_DEFAULT_ROOM_ROLLOFF_FACTOR (0.0f) -// -//#define AL_EAXREVERB_MIN_DECAY_HFLIMIT AL_FALSE -//#define AL_EAXREVERB_MAX_DECAY_HFLIMIT AL_TRUE -//#define AL_EAXREVERB_DEFAULT_DECAY_HFLIMIT AL_TRUE -// -///* Chorus effect */ -//#define AL_CHORUS_WAVEFORM_SINUSOID (0) -//#define AL_CHORUS_WAVEFORM_TRIANGLE (1) -// -//#define AL_CHORUS_MIN_WAVEFORM (0) -//#define AL_CHORUS_MAX_WAVEFORM (1) -//#define AL_CHORUS_DEFAULT_WAVEFORM (1) -// -//#define AL_CHORUS_MIN_PHASE (-180) -//#define AL_CHORUS_MAX_PHASE (180) -//#define AL_CHORUS_DEFAULT_PHASE (90) -// -//#define AL_CHORUS_MIN_RATE (0.0f) -//#define AL_CHORUS_MAX_RATE (10.0f) -//#define AL_CHORUS_DEFAULT_RATE (1.1f) -// -//#define AL_CHORUS_MIN_DEPTH (0.0f) -//#define AL_CHORUS_MAX_DEPTH (1.0f) -//#define AL_CHORUS_DEFAULT_DEPTH (0.1f) -// -//#define AL_CHORUS_MIN_FEEDBACK (-1.0f) -//#define AL_CHORUS_MAX_FEEDBACK (1.0f) -//#define AL_CHORUS_DEFAULT_FEEDBACK (0.25f) -// -//#define AL_CHORUS_MIN_DELAY (0.0f) -//#define AL_CHORUS_MAX_DELAY (0.016f) -//#define AL_CHORUS_DEFAULT_DELAY (0.016f) -// -///* Distortion effect */ -//#define AL_DISTORTION_MIN_EDGE (0.0f) -//#define AL_DISTORTION_MAX_EDGE (1.0f) -//#define AL_DISTORTION_DEFAULT_EDGE (0.2f) -// -//#define AL_DISTORTION_MIN_GAIN (0.01f) -//#define AL_DISTORTION_MAX_GAIN (1.0f) -//#define AL_DISTORTION_DEFAULT_GAIN (0.05f) -// -//#define AL_DISTORTION_MIN_LOWPASS_CUTOFF (80.0f) -//#define AL_DISTORTION_MAX_LOWPASS_CUTOFF (24000.0f) -//#define AL_DISTORTION_DEFAULT_LOWPASS_CUTOFF (8000.0f) -// -//#define AL_DISTORTION_MIN_EQCENTER (80.0f) -//#define AL_DISTORTION_MAX_EQCENTER (24000.0f) -//#define AL_DISTORTION_DEFAULT_EQCENTER (3600.0f) -// -//#define AL_DISTORTION_MIN_EQBANDWIDTH (80.0f) -//#define AL_DISTORTION_MAX_EQBANDWIDTH (24000.0f) -//#define AL_DISTORTION_DEFAULT_EQBANDWIDTH (3600.0f) -// -///* Echo effect */ -//#define AL_ECHO_MIN_DELAY (0.0f) -//#define AL_ECHO_MAX_DELAY (0.207f) -//#define AL_ECHO_DEFAULT_DELAY (0.1f) -// -//#define AL_ECHO_MIN_LRDELAY (0.0f) -//#define AL_ECHO_MAX_LRDELAY (0.404f) -//#define AL_ECHO_DEFAULT_LRDELAY (0.1f) -// -//#define AL_ECHO_MIN_DAMPING (0.0f) -//#define AL_ECHO_MAX_DAMPING (0.99f) -//#define AL_ECHO_DEFAULT_DAMPING (0.5f) -// -//#define AL_ECHO_MIN_FEEDBACK (0.0f) -//#define AL_ECHO_MAX_FEEDBACK (1.0f) -//#define AL_ECHO_DEFAULT_FEEDBACK (0.5f) -// -//#define AL_ECHO_MIN_SPREAD (-1.0f) -//#define AL_ECHO_MAX_SPREAD (1.0f) -//#define AL_ECHO_DEFAULT_SPREAD (-1.0f) -// -///* Flanger effect */ -//#define AL_FLANGER_WAVEFORM_SINUSOID (0) -//#define AL_FLANGER_WAVEFORM_TRIANGLE (1) -// -//#define AL_FLANGER_MIN_WAVEFORM (0) -//#define AL_FLANGER_MAX_WAVEFORM (1) -//#define AL_FLANGER_DEFAULT_WAVEFORM (1) -// -//#define AL_FLANGER_MIN_PHASE (-180) -//#define AL_FLANGER_MAX_PHASE (180) -//#define AL_FLANGER_DEFAULT_PHASE (0) -// -//#define AL_FLANGER_MIN_RATE (0.0f) -//#define AL_FLANGER_MAX_RATE (10.0f) -//#define AL_FLANGER_DEFAULT_RATE (0.27f) -// -//#define AL_FLANGER_MIN_DEPTH (0.0f) -//#define AL_FLANGER_MAX_DEPTH (1.0f) -//#define AL_FLANGER_DEFAULT_DEPTH (1.0f) -// -//#define AL_FLANGER_MIN_FEEDBACK (-1.0f) -//#define AL_FLANGER_MAX_FEEDBACK (1.0f) -//#define AL_FLANGER_DEFAULT_FEEDBACK (-0.5f) -// -//#define AL_FLANGER_MIN_DELAY (0.0f) -//#define AL_FLANGER_MAX_DELAY (0.004f) -//#define AL_FLANGER_DEFAULT_DELAY (0.002f) -// -///* Frequency shifter effect */ -//#define AL_FREQUENCY_SHIFTER_MIN_FREQUENCY (0.0f) -//#define AL_FREQUENCY_SHIFTER_MAX_FREQUENCY (24000.0f) -//#define AL_FREQUENCY_SHIFTER_DEFAULT_FREQUENCY (0.0f) -// -//#define AL_FREQUENCY_SHIFTER_MIN_LEFT_DIRECTION (0) -//#define AL_FREQUENCY_SHIFTER_MAX_LEFT_DIRECTION (2) -//#define AL_FREQUENCY_SHIFTER_DEFAULT_LEFT_DIRECTION (0) -// -//#define AL_FREQUENCY_SHIFTER_DIRECTION_DOWN (0) -//#define AL_FREQUENCY_SHIFTER_DIRECTION_UP (1) -//#define AL_FREQUENCY_SHIFTER_DIRECTION_OFF (2) -// -//#define AL_FREQUENCY_SHIFTER_MIN_RIGHT_DIRECTION (0) -//#define AL_FREQUENCY_SHIFTER_MAX_RIGHT_DIRECTION (2) -//#define AL_FREQUENCY_SHIFTER_DEFAULT_RIGHT_DIRECTION (0) -// -///* Vocal morpher effect */ -//#define AL_VOCAL_MORPHER_MIN_PHONEMEA (0) -//#define AL_VOCAL_MORPHER_MAX_PHONEMEA (29) -//#define AL_VOCAL_MORPHER_DEFAULT_PHONEMEA (0) -// -//#define AL_VOCAL_MORPHER_MIN_PHONEMEA_COARSE_TUNING (-24) -//#define AL_VOCAL_MORPHER_MAX_PHONEMEA_COARSE_TUNING (24) -//#define AL_VOCAL_MORPHER_DEFAULT_PHONEMEA_COARSE_TUNING (0) -// -//#define AL_VOCAL_MORPHER_MIN_PHONEMEB (0) -//#define AL_VOCAL_MORPHER_MAX_PHONEMEB (29) -//#define AL_VOCAL_MORPHER_DEFAULT_PHONEMEB (10) -// -//#define AL_VOCAL_MORPHER_MIN_PHONEMEB_COARSE_TUNING (-24) -//#define AL_VOCAL_MORPHER_MAX_PHONEMEB_COARSE_TUNING (24) -//#define AL_VOCAL_MORPHER_DEFAULT_PHONEMEB_COARSE_TUNING (0) -// -//#define AL_VOCAL_MORPHER_PHONEME_A (0) -//#define AL_VOCAL_MORPHER_PHONEME_E (1) -//#define AL_VOCAL_MORPHER_PHONEME_I (2) -//#define AL_VOCAL_MORPHER_PHONEME_O (3) -//#define AL_VOCAL_MORPHER_PHONEME_U (4) -//#define AL_VOCAL_MORPHER_PHONEME_AA (5) -//#define AL_VOCAL_MORPHER_PHONEME_AE (6) -//#define AL_VOCAL_MORPHER_PHONEME_AH (7) -//#define AL_VOCAL_MORPHER_PHONEME_AO (8) -//#define AL_VOCAL_MORPHER_PHONEME_EH (9) -//#define AL_VOCAL_MORPHER_PHONEME_ER (10) -//#define AL_VOCAL_MORPHER_PHONEME_IH (11) -//#define AL_VOCAL_MORPHER_PHONEME_IY (12) -//#define AL_VOCAL_MORPHER_PHONEME_UH (13) -//#define AL_VOCAL_MORPHER_PHONEME_UW (14) -//#define AL_VOCAL_MORPHER_PHONEME_B (15) -//#define AL_VOCAL_MORPHER_PHONEME_D (16) -//#define AL_VOCAL_MORPHER_PHONEME_F (17) -//#define AL_VOCAL_MORPHER_PHONEME_G (18) -//#define AL_VOCAL_MORPHER_PHONEME_J (19) -//#define AL_VOCAL_MORPHER_PHONEME_K (20) -//#define AL_VOCAL_MORPHER_PHONEME_L (21) -//#define AL_VOCAL_MORPHER_PHONEME_M (22) -//#define AL_VOCAL_MORPHER_PHONEME_N (23) -//#define AL_VOCAL_MORPHER_PHONEME_P (24) -//#define AL_VOCAL_MORPHER_PHONEME_R (25) -//#define AL_VOCAL_MORPHER_PHONEME_S (26) -//#define AL_VOCAL_MORPHER_PHONEME_T (27) -//#define AL_VOCAL_MORPHER_PHONEME_V (28) -//#define AL_VOCAL_MORPHER_PHONEME_Z (29) -// -//#define AL_VOCAL_MORPHER_WAVEFORM_SINUSOID (0) -//#define AL_VOCAL_MORPHER_WAVEFORM_TRIANGLE (1) -//#define AL_VOCAL_MORPHER_WAVEFORM_SAWTOOTH (2) -// -//#define AL_VOCAL_MORPHER_MIN_WAVEFORM (0) -//#define AL_VOCAL_MORPHER_MAX_WAVEFORM (2) -//#define AL_VOCAL_MORPHER_DEFAULT_WAVEFORM (0) -// -//#define AL_VOCAL_MORPHER_MIN_RATE (0.0f) -//#define AL_VOCAL_MORPHER_MAX_RATE (10.0f) -//#define AL_VOCAL_MORPHER_DEFAULT_RATE (1.41f) -// -///* Pitch shifter effect */ -//#define AL_PITCH_SHIFTER_MIN_COARSE_TUNE (-12) -//#define AL_PITCH_SHIFTER_MAX_COARSE_TUNE (12) -//#define AL_PITCH_SHIFTER_DEFAULT_COARSE_TUNE (12) -// -//#define AL_PITCH_SHIFTER_MIN_FINE_TUNE (-50) -//#define AL_PITCH_SHIFTER_MAX_FINE_TUNE (50) -//#define AL_PITCH_SHIFTER_DEFAULT_FINE_TUNE (0) -// -///* Ring modulator effect */ -//#define AL_RING_MODULATOR_MIN_FREQUENCY (0.0f) -//#define AL_RING_MODULATOR_MAX_FREQUENCY (8000.0f) -//#define AL_RING_MODULATOR_DEFAULT_FREQUENCY (440.0f) -// -//#define AL_RING_MODULATOR_MIN_HIGHPASS_CUTOFF (0.0f) -//#define AL_RING_MODULATOR_MAX_HIGHPASS_CUTOFF (24000.0f) -//#define AL_RING_MODULATOR_DEFAULT_HIGHPASS_CUTOFF (800.0f) -// -//#define AL_RING_MODULATOR_SINUSOID (0) -//#define AL_RING_MODULATOR_SAWTOOTH (1) -//#define AL_RING_MODULATOR_SQUARE (2) -// -//#define AL_RING_MODULATOR_MIN_WAVEFORM (0) -//#define AL_RING_MODULATOR_MAX_WAVEFORM (2) -//#define AL_RING_MODULATOR_DEFAULT_WAVEFORM (0) -// -///* Autowah effect */ -//#define AL_AUTOWAH_MIN_ATTACK_TIME (0.0001f) -//#define AL_AUTOWAH_MAX_ATTACK_TIME (1.0f) -//#define AL_AUTOWAH_DEFAULT_ATTACK_TIME (0.06f) -// -//#define AL_AUTOWAH_MIN_RELEASE_TIME (0.0001f) -//#define AL_AUTOWAH_MAX_RELEASE_TIME (1.0f) -//#define AL_AUTOWAH_DEFAULT_RELEASE_TIME (0.06f) -// -//#define AL_AUTOWAH_MIN_RESONANCE (2.0f) -//#define AL_AUTOWAH_MAX_RESONANCE (1000.0f) -//#define AL_AUTOWAH_DEFAULT_RESONANCE (1000.0f) -// -//#define AL_AUTOWAH_MIN_PEAK_GAIN (0.00003f) -//#define AL_AUTOWAH_MAX_PEAK_GAIN (31621.0f) -//#define AL_AUTOWAH_DEFAULT_PEAK_GAIN (11.22f) -// -///* Compressor effect */ -//#define AL_COMPRESSOR_MIN_ONOFF (0) -//#define AL_COMPRESSOR_MAX_ONOFF (1) -//#define AL_COMPRESSOR_DEFAULT_ONOFF (1) -// -///* Equalizer effect */ -//#define AL_EQUALIZER_MIN_LOW_GAIN (0.126f) -//#define AL_EQUALIZER_MAX_LOW_GAIN (7.943f) -//#define AL_EQUALIZER_DEFAULT_LOW_GAIN (1.0f) -// -//#define AL_EQUALIZER_MIN_LOW_CUTOFF (50.0f) -//#define AL_EQUALIZER_MAX_LOW_CUTOFF (800.0f) -//#define AL_EQUALIZER_DEFAULT_LOW_CUTOFF (200.0f) -// -//#define AL_EQUALIZER_MIN_MID1_GAIN (0.126f) -//#define AL_EQUALIZER_MAX_MID1_GAIN (7.943f) -//#define AL_EQUALIZER_DEFAULT_MID1_GAIN (1.0f) -// -//#define AL_EQUALIZER_MIN_MID1_CENTER (200.0f) -//#define AL_EQUALIZER_MAX_MID1_CENTER (3000.0f) -//#define AL_EQUALIZER_DEFAULT_MID1_CENTER (500.0f) -// -//#define AL_EQUALIZER_MIN_MID1_WIDTH (0.01f) -//#define AL_EQUALIZER_MAX_MID1_WIDTH (1.0f) -//#define AL_EQUALIZER_DEFAULT_MID1_WIDTH (1.0f) -// -//#define AL_EQUALIZER_MIN_MID2_GAIN (0.126f) -//#define AL_EQUALIZER_MAX_MID2_GAIN (7.943f) -//#define AL_EQUALIZER_DEFAULT_MID2_GAIN (1.0f) -// -//#define AL_EQUALIZER_MIN_MID2_CENTER (1000.0f) -//#define AL_EQUALIZER_MAX_MID2_CENTER (8000.0f) -//#define AL_EQUALIZER_DEFAULT_MID2_CENTER (3000.0f) -// -//#define AL_EQUALIZER_MIN_MID2_WIDTH (0.01f) -//#define AL_EQUALIZER_MAX_MID2_WIDTH (1.0f) -//#define AL_EQUALIZER_DEFAULT_MID2_WIDTH (1.0f) -// -//#define AL_EQUALIZER_MIN_HIGH_GAIN (0.126f) -//#define AL_EQUALIZER_MAX_HIGH_GAIN (7.943f) -//#define AL_EQUALIZER_DEFAULT_HIGH_GAIN (1.0f) -// -//#define AL_EQUALIZER_MIN_HIGH_CUTOFF (4000.0f) -//#define AL_EQUALIZER_MAX_HIGH_CUTOFF (16000.0f) -//#define AL_EQUALIZER_DEFAULT_HIGH_CUTOFF (6000.0f) -// -// -///* Source parameter value ranges and defaults. */ -//#define AL_MIN_AIR_ABSORPTION_FACTOR (0.0f) -//#define AL_MAX_AIR_ABSORPTION_FACTOR (10.0f) -//#define AL_DEFAULT_AIR_ABSORPTION_FACTOR (0.0f) -// -//#define AL_MIN_ROOM_ROLLOFF_FACTOR (0.0f) -//#define AL_MAX_ROOM_ROLLOFF_FACTOR (10.0f) -//#define AL_DEFAULT_ROOM_ROLLOFF_FACTOR (0.0f) -// -//#define AL_MIN_CONE_OUTER_GAINHF (0.0f) -//#define AL_MAX_CONE_OUTER_GAINHF (1.0f) -//#define AL_DEFAULT_CONE_OUTER_GAINHF (1.0f) -// -//#define AL_MIN_DIRECT_FILTER_GAINHF_AUTO AL_FALSE -//#define AL_MAX_DIRECT_FILTER_GAINHF_AUTO AL_TRUE -//#define AL_DEFAULT_DIRECT_FILTER_GAINHF_AUTO AL_TRUE -// -//#define AL_MIN_AUXILIARY_SEND_FILTER_GAIN_AUTO AL_FALSE -//#define AL_MAX_AUXILIARY_SEND_FILTER_GAIN_AUTO AL_TRUE -//#define AL_DEFAULT_AUXILIARY_SEND_FILTER_GAIN_AUTO AL_TRUE -// -//#define AL_MIN_AUXILIARY_SEND_FILTER_GAINHF_AUTO AL_FALSE -//#define AL_MAX_AUXILIARY_SEND_FILTER_GAINHF_AUTO AL_TRUE -//#define AL_DEFAULT_AUXILIARY_SEND_FILTER_GAINHF_AUTO AL_TRUE -// -// -///* Listener parameter value ranges and defaults. */ -//#define AL_MIN_METERS_PER_UNIT FLT_MIN -//#define AL_MAX_METERS_PER_UNIT FLT_MAX -//#define AL_DEFAULT_METERS_PER_UNIT (1.0f) - - - public static String GetALErrorMsg(int errorCode) { - String errorText; - switch (errorCode) { - case AL_NO_ERROR: - errorText = "No Error"; - break; - case AL_INVALID_NAME: - errorText = "Invalid Name"; - break; - case AL_INVALID_ENUM: - errorText = "Invalid Enum"; - break; - case AL_INVALID_VALUE: - errorText = "Invalid Value"; - break; - case AL_INVALID_OPERATION: - errorText = "Invalid Operation"; - break; - case AL_OUT_OF_MEMORY: - errorText = "Out of Memory"; - break; - default: - errorText = "Unknown Error Code: " + String.valueOf(errorCode); - } - return errorText; - } -} - diff --git a/jme3-ios/src/main/java/com/jme3/audio/android/AndroidAudioData.java b/jme3-ios/src/main/java/com/jme3/audio/android/AndroidAudioData.java deleted file mode 100644 index e7f4a0f98..000000000 --- a/jme3-ios/src/main/java/com/jme3/audio/android/AndroidAudioData.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.jme3.audio.android; - -import com.jme3.asset.AssetKey; -import com.jme3.audio.AudioData; -import com.jme3.audio.AudioRenderer; -import com.jme3.util.NativeObject; - -public class AndroidAudioData extends AudioData { - - protected AssetKey assetKey; - protected float currentVolume = 0f; - - public AndroidAudioData(){ - super(); - } - - protected AndroidAudioData(int id){ - super(id); - } - - public AssetKey getAssetKey() { - return assetKey; - } - - public void setAssetKey(AssetKey assetKey) { - this.assetKey = assetKey; - } - - @Override - public DataType getDataType() { - return DataType.Buffer; - } - - @Override - public float getDuration() { - return 0; // TODO: ??? - } - - @Override - public void resetObject() { - this.id = -1; - setUpdateNeeded(); - } - - @Override - public void deleteObject(Object rendererObject) { - ((AudioRenderer)rendererObject).deleteAudioData(this); - } - - public float getCurrentVolume() { - return currentVolume; - } - - public void setCurrentVolume(float currentVolume) { - this.currentVolume = currentVolume; - } - - @Override - public NativeObject createDestructableClone() { - return new AndroidAudioData(id); - } - - @Override - public long getUniqueId() { - return ((long)OBJTYPE_AUDIOBUFFER << 32) | ((long)id); - } -} diff --git a/jme3-ios/src/main/java/com/jme3/audio/ios/IosAL.java b/jme3-ios/src/main/java/com/jme3/audio/ios/IosAL.java new file mode 100644 index 000000000..7812dc748 --- /dev/null +++ b/jme3-ios/src/main/java/com/jme3/audio/ios/IosAL.java @@ -0,0 +1,53 @@ +package com.jme3.audio.ios; + +import com.jme3.audio.openal.AL; +import java.nio.ByteBuffer; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; + +public final class IosAL implements AL { + + public IosAL() { + } + + public native String alGetString(int parameter); + + public native int alGenSources(); + + public native int alGetError(); + + public native void alDeleteSources(int numSources, IntBuffer sources); + + public native void alGenBuffers(int numBuffers, IntBuffer buffers); + + public native void alDeleteBuffers(int numBuffers, IntBuffer buffers); + + public native void alSourceStop(int source); + + public native void alSourcei(int source, int param, int value); + + public native void alBufferData(int buffer, int format, ByteBuffer data, int size, int frequency); + + public native void alSourcePlay(int source); + + public native void alSourcePause(int source); + + public native void alSourcef(int source, int param, float value); + + public native void alSource3f(int source, int param, float value1, float value2, float value3); + + public native int alGetSourcei(int source, int param); + + public native void alSourceUnqueueBuffers(int source, int numBuffers, IntBuffer buffers); + + public native void alSourceQueueBuffers(int source, int numBuffers, IntBuffer buffers); + + public native void alListener(int param, FloatBuffer data); + + public native void alListenerf(int param, float value); + + public native void alListener3f(int param, float value1, float value2, float value3); + + public native void alSource3i(int source, int param, int value1, int value2, int value3); + +} diff --git a/jme3-ios/src/main/java/com/jme3/audio/ios/IosALC.java b/jme3-ios/src/main/java/com/jme3/audio/ios/IosALC.java new file mode 100644 index 000000000..f1579c9e5 --- /dev/null +++ b/jme3-ios/src/main/java/com/jme3/audio/ios/IosALC.java @@ -0,0 +1,26 @@ +package com.jme3.audio.ios; + +import com.jme3.audio.openal.ALC; +import java.nio.IntBuffer; + +public final class IosALC implements ALC { + + public IosALC() { + } + + public native void createALC(); + + public native void destroyALC(); + + public native boolean isCreated(); + + public native String alcGetString(int parameter); + + public native boolean alcIsExtensionPresent(String extension); + + public native void alcGetInteger(int param, IntBuffer buffer, int size); + + public native void alcDevicePauseSOFT(); + + public native void alcDeviceResumeSOFT(); +} diff --git a/jme3-ios/src/main/java/com/jme3/audio/ios/IosEFX.java b/jme3-ios/src/main/java/com/jme3/audio/ios/IosEFX.java new file mode 100644 index 000000000..d7a569c1f --- /dev/null +++ b/jme3-ios/src/main/java/com/jme3/audio/ios/IosEFX.java @@ -0,0 +1,32 @@ +package com.jme3.audio.ios; + +import com.jme3.audio.openal.EFX; +import java.nio.IntBuffer; + +public class IosEFX implements EFX { + + public IosEFX() { + } + + public native void alGenAuxiliaryEffectSlots(int numSlots, IntBuffer buffers); + + public native void alGenEffects(int numEffects, IntBuffer buffers); + + public native void alEffecti(int effect, int param, int value); + + public native void alAuxiliaryEffectSloti(int effectSlot, int param, int value); + + public native void alDeleteEffects(int numEffects, IntBuffer buffers); + + public native void alDeleteAuxiliaryEffectSlots(int numEffectSlots, IntBuffer buffers); + + public native void alGenFilters(int numFilters, IntBuffer buffers); + + public native void alFilteri(int filter, int param, int value); + + public native void alFilterf(int filter, int param, float value); + + public native void alDeleteFilters(int numFilters, IntBuffer buffers); + + public native void alEffectf(int effect, int param, float value); +} diff --git a/jme3-ios/src/main/java/com/jme3/audio/plugins/AndroidAudioLoader.java b/jme3-ios/src/main/java/com/jme3/audio/plugins/AndroidAudioLoader.java deleted file mode 100644 index a11425b23..000000000 --- a/jme3-ios/src/main/java/com/jme3/audio/plugins/AndroidAudioLoader.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jme3.audio.plugins; - -import com.jme3.asset.AssetInfo; -import com.jme3.asset.AssetLoader; -import com.jme3.audio.android.AndroidAudioData; -import java.io.IOException; - -/** - * AndroidAudioLoader will create an - * {@link AndroidAudioData} object with the specified asset key. - */ -public class AndroidAudioLoader implements AssetLoader { - - @Override - public Object load(AssetInfo assetInfo) throws IOException { - AndroidAudioData result = new AndroidAudioData(); - result.setAssetKey(assetInfo.getKey()); - return result; - } -} diff --git a/jme3-ios/src/main/java/com/jme3/renderer/ios/IGLESShaderRenderer.java b/jme3-ios/src/main/java/com/jme3/renderer/ios/IGLESShaderRenderer.java deleted file mode 100644 index d6b7010f4..000000000 --- a/jme3-ios/src/main/java/com/jme3/renderer/ios/IGLESShaderRenderer.java +++ /dev/null @@ -1,2600 +0,0 @@ -package com.jme3.renderer.ios; - -import com.jme3.light.LightList; -import com.jme3.material.RenderState; -import com.jme3.math.*; -import com.jme3.renderer.*; -import com.jme3.scene.Mesh; -import com.jme3.scene.Mesh.Mode; -import com.jme3.scene.VertexBuffer; -import com.jme3.scene.VertexBuffer.Format; -import com.jme3.scene.VertexBuffer.Type; -import com.jme3.scene.VertexBuffer.Usage; -import com.jme3.shader.Attribute; -import com.jme3.shader.Shader; -import com.jme3.shader.Shader.ShaderSource; -import com.jme3.shader.Shader.ShaderType; -import com.jme3.shader.Uniform; -import com.jme3.texture.FrameBuffer; -import com.jme3.texture.FrameBuffer.RenderBuffer; -import com.jme3.texture.Image; -import com.jme3.texture.Texture; -import com.jme3.texture.Texture.WrapAxis; -import com.jme3.util.BufferUtils; -import com.jme3.util.ListMap; -import com.jme3.util.NativeObjectManager; - -import java.nio.*; -import java.util.EnumSet; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import jme3tools.shader.ShaderDebug; - -/** - * The Renderer is responsible for taking rendering commands and - * executing them on the underlying video hardware. - * - * @author Kirill Vainer - */ -public class IGLESShaderRenderer implements Renderer { - - private static final Logger logger = Logger.getLogger(IGLESShaderRenderer.class.getName()); - private static final boolean VALIDATE_SHADER = false; - - private final NativeObjectManager objManager = new NativeObjectManager(); - private final EnumSet caps = EnumSet.noneOf(Caps.class); - private final Statistics statistics = new Statistics(); - private final StringBuilder stringBuf = new StringBuilder(250); - private final RenderContext context = new RenderContext(); - private final ByteBuffer nameBuf = BufferUtils.createByteBuffer(250); - - private final int maxFBOAttachs = 1; // Only 1 color attachment on ES - private final int maxMRTFBOAttachs = 1; // FIXME for now, not sure if > 1 is needed for ES - - private final int[] intBuf1 = new int[1]; - private final int[] intBuf16 = new int[16]; - - private int glslVer; - private int vertexTextureUnits; - private int fragTextureUnits; - private int vertexUniforms; - private int fragUniforms; - private int vertexAttribs; - private int maxRBSize; - private int maxTexSize; - private int maxCubeTexSize; - - private FrameBuffer lastFb = null; - private FrameBuffer mainFbOverride = null; - private boolean useVBO = true; - private boolean powerVr = false; - private boolean uintIndexSupport = false; - - private Shader boundShader; - - private int vpX, vpY, vpW, vpH; - private int clipX, clipY, clipW, clipH; - - public IGLESShaderRenderer() { - logger.log(Level.FINE, "IGLESShaderRenderer Constructor"); - } - - /** - * Get the capabilities of the renderer. - * @return The capabilities of the renderer. - */ - public EnumSet getCaps() { - logger.log(Level.FINE, "IGLESShaderRenderer getCaps"); - return caps; - } - - /** - * The statistics allow tracking of how data - * per frame, such as number of objects rendered, number of triangles, etc. - * These are updated when the Renderer's methods are used, make sure - * to call {@link Statistics#clearFrame() } at the appropriate time - * to get accurate info per frame. - */ - public Statistics getStatistics() { - logger.log(Level.FINE, "IGLESShaderRenderer getStatistics"); - return statistics; - } - - /** - * Invalidates the current rendering state. Should be called after - * the GL state was changed manually or through an external library. - */ - public void invalidateState() { - logger.log(Level.FINE, "IGLESShaderRenderer invalidateState"); - } - - /** - * Clears certain channels of the currently bound framebuffer. - * - * @param color True if to clear colors (RGBA) - * @param depth True if to clear depth/z - * @param stencil True if to clear stencil buffer (if available, otherwise - * ignored) - */ - public void clearBuffers(boolean color, boolean depth, boolean stencil) { - logger.log(Level.FINE, "IGLESShaderRenderer clearBuffers"); - int bits = 0; - if (color) { - //See explanations of the depth below, we must enable color write to be able to clear the color buffer - if (context.colorWriteEnabled == false) { - JmeIosGLES.glColorMask(true, true, true, true); - context.colorWriteEnabled = true; - } - bits = JmeIosGLES.GL_COLOR_BUFFER_BIT; - } - if (depth) { - //glClear(GL_DEPTH_BUFFER_BIT) seems to not work when glDepthMask is false - //here s some link on openl board - //http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=257223 - //if depth clear is requested, we enable the depthMask - if (context.depthWriteEnabled == false) { - JmeIosGLES.glDepthMask(true); - context.depthWriteEnabled = true; - } - bits |= JmeIosGLES.GL_DEPTH_BUFFER_BIT; - } - if (stencil) { - bits |= JmeIosGLES.GL_STENCIL_BUFFER_BIT; - } - if (bits != 0) { - JmeIosGLES.glClear(bits); - JmeIosGLES.checkGLError(); - } - } - - /** - * Sets the background (aka clear) color. - * - * @param color The background color to set - */ - public void setBackgroundColor(ColorRGBA color) { - logger.log(Level.FINE, "IGLESShaderRenderer setBackgroundColor"); - JmeIosGLES.glClearColor(color.r, color.g, color.b, color.a); - JmeIosGLES.checkGLError(); - } - - /** - * Applies the given {@link RenderState}, making the necessary - * GL calls so that the state is applied. - */ - public void applyRenderState(RenderState state) { - logger.log(Level.FINE, "IGLESShaderRenderer applyRenderState"); - /* - if (state.isWireframe() && !context.wireframe){ - GLES20.glPolygonMode(GLES20.GL_FRONT_AND_BACK, GLES20.GL_LINE); - context.wireframe = true; - }else if (!state.isWireframe() && context.wireframe){ - GLES20.glPolygonMode(GLES20.GL_FRONT_AND_BACK, GLES20.GL_FILL); - context.wireframe = false; - } - */ - if (state.isDepthTest() && !context.depthTestEnabled) { - JmeIosGLES.glEnable(JmeIosGLES.GL_DEPTH_TEST); - JmeIosGLES.glDepthFunc(convertTestFunction(context.depthFunc)); - JmeIosGLES.checkGLError(); - context.depthTestEnabled = true; - } else if (!state.isDepthTest() && context.depthTestEnabled) { - JmeIosGLES.glDisable(JmeIosGLES.GL_DEPTH_TEST); - JmeIosGLES.checkGLError(); - context.depthTestEnabled = false; - } - if (state.getDepthFunc() != context.depthFunc) { - JmeIosGLES.glDepthFunc(convertTestFunction(state.getDepthFunc())); - context.depthFunc = state.getDepthFunc(); - } - - if (state.isDepthWrite() && !context.depthWriteEnabled) { - JmeIosGLES.glDepthMask(true); - JmeIosGLES.checkGLError(); - context.depthWriteEnabled = true; - } else if (!state.isDepthWrite() && context.depthWriteEnabled) { - JmeIosGLES.glDepthMask(false); - JmeIosGLES.checkGLError(); - context.depthWriteEnabled = false; - } - if (state.isColorWrite() && !context.colorWriteEnabled) { - JmeIosGLES.glColorMask(true, true, true, true); - JmeIosGLES.checkGLError(); - context.colorWriteEnabled = true; - } else if (!state.isColorWrite() && context.colorWriteEnabled) { - JmeIosGLES.glColorMask(false, false, false, false); - JmeIosGLES.checkGLError(); - context.colorWriteEnabled = false; - } -// if (state.isPointSprite() && !context.pointSprite) { -//// GLES20.glEnable(GLES20.GL_POINT_SPRITE); -//// GLES20.glTexEnvi(GLES20.GL_POINT_SPRITE, GLES20.GL_COORD_REPLACE, GLES20.GL_TRUE); -//// GLES20.glEnable(GLES20.GL_VERTEX_PROGRAM_POINT_SIZE); -//// GLES20.glPointParameterf(GLES20.GL_POINT_SIZE_MIN, 1.0f); -// } else if (!state.isPointSprite() && context.pointSprite) { -//// GLES20.glDisable(GLES20.GL_POINT_SPRITE); -// } - - if (state.isPolyOffset()) { - if (!context.polyOffsetEnabled) { - JmeIosGLES.glEnable(JmeIosGLES.GL_POLYGON_OFFSET_FILL); - JmeIosGLES.glPolygonOffset(state.getPolyOffsetFactor(), - state.getPolyOffsetUnits()); - JmeIosGLES.checkGLError(); - - context.polyOffsetEnabled = true; - context.polyOffsetFactor = state.getPolyOffsetFactor(); - context.polyOffsetUnits = state.getPolyOffsetUnits(); - } else { - if (state.getPolyOffsetFactor() != context.polyOffsetFactor - || state.getPolyOffsetUnits() != context.polyOffsetUnits) { - JmeIosGLES.glPolygonOffset(state.getPolyOffsetFactor(), - state.getPolyOffsetUnits()); - JmeIosGLES.checkGLError(); - - context.polyOffsetFactor = state.getPolyOffsetFactor(); - context.polyOffsetUnits = state.getPolyOffsetUnits(); - } - } - } else { - if (context.polyOffsetEnabled) { - JmeIosGLES.glDisable(JmeIosGLES.GL_POLYGON_OFFSET_FILL); - JmeIosGLES.checkGLError(); - - context.polyOffsetEnabled = false; - context.polyOffsetFactor = 0; - context.polyOffsetUnits = 0; - } - } - if (state.getFaceCullMode() != context.cullMode) { - if (state.getFaceCullMode() == RenderState.FaceCullMode.Off) { - JmeIosGLES.glDisable(JmeIosGLES.GL_CULL_FACE); - JmeIosGLES.checkGLError(); - } else { - JmeIosGLES.glEnable(JmeIosGLES.GL_CULL_FACE); - JmeIosGLES.checkGLError(); - } - - switch (state.getFaceCullMode()) { - case Off: - break; - case Back: - JmeIosGLES.glCullFace(JmeIosGLES.GL_BACK); - JmeIosGLES.checkGLError(); - break; - case Front: - JmeIosGLES.glCullFace(JmeIosGLES.GL_FRONT); - JmeIosGLES.checkGLError(); - break; - case FrontAndBack: - JmeIosGLES.glCullFace(JmeIosGLES.GL_FRONT_AND_BACK); - JmeIosGLES.checkGLError(); - break; - default: - throw new UnsupportedOperationException("Unrecognized face cull mode: " - + state.getFaceCullMode()); - } - - context.cullMode = state.getFaceCullMode(); - } - - if (state.getBlendMode() != context.blendMode) { - if (state.getBlendMode() == RenderState.BlendMode.Off) { - JmeIosGLES.glDisable(JmeIosGLES.GL_BLEND); - JmeIosGLES.checkGLError(); - } else { - JmeIosGLES.glEnable(JmeIosGLES.GL_BLEND); - switch (state.getBlendMode()) { - case Off: - break; - case Additive: - JmeIosGLES.glBlendFunc(JmeIosGLES.GL_ONE, JmeIosGLES.GL_ONE); - break; - case AlphaAdditive: - JmeIosGLES.glBlendFunc(JmeIosGLES.GL_SRC_ALPHA, JmeIosGLES.GL_ONE); - break; - case Color: - JmeIosGLES.glBlendFunc(JmeIosGLES.GL_ONE, JmeIosGLES.GL_ONE_MINUS_SRC_COLOR); - break; - case Alpha: - JmeIosGLES.glBlendFunc(JmeIosGLES.GL_SRC_ALPHA, JmeIosGLES.GL_ONE_MINUS_SRC_ALPHA); - break; - case PremultAlpha: - JmeIosGLES.glBlendFunc(JmeIosGLES.GL_ONE, JmeIosGLES.GL_ONE_MINUS_SRC_ALPHA); - break; - case Modulate: - JmeIosGLES.glBlendFunc(JmeIosGLES.GL_DST_COLOR, JmeIosGLES.GL_ZERO); - break; - case ModulateX2: - JmeIosGLES.glBlendFunc(JmeIosGLES.GL_DST_COLOR, JmeIosGLES.GL_SRC_COLOR); - break; - default: - throw new UnsupportedOperationException("Unrecognized blend mode: " - + state.getBlendMode()); - } - JmeIosGLES.checkGLError(); - } - context.blendMode = state.getBlendMode(); - } - } - - /** - * Set the range of the depth values for objects. All rendered - * objects will have their depth clamped to this range. - * - * @param start The range start - * @param end The range end - */ - public void setDepthRange(float start, float end) { - logger.log(Level.FINE, "IGLESShaderRenderer setDepthRange"); - JmeIosGLES.glDepthRangef(start, end); - JmeIosGLES.checkGLError(); - } - - /** - * Called when a new frame has been rendered. - */ - public void postFrame() { - logger.log(Level.FINE, "IGLESShaderRenderer onFrame"); - //JmeIosGLES.checkGLErrorForced(); - JmeIosGLES.checkGLError(); - - objManager.deleteUnused(this); - } - - /** - * Set the world matrix to use. Does nothing if the Renderer is - * shader based. - * - * @param worldMatrix World matrix to use. - */ - public void setWorldMatrix(Matrix4f worldMatrix) { - logger.log(Level.FINE, "IGLESShaderRenderer setWorldMatrix"); - } - - /** - * Sets the view and projection matrices to use. Does nothing if the Renderer - * is shader based. - * - * @param viewMatrix The view matrix to use. - * @param projMatrix The projection matrix to use. - */ - public void setViewProjectionMatrices(Matrix4f viewMatrix, Matrix4f projMatrix) { - logger.log(Level.FINE, "IGLESShaderRenderer setViewProjectionMatrices"); - } - - /** - * Set the viewport location and resolution on the screen. - * - * @param x The x coordinate of the viewport - * @param y The y coordinate of the viewport - * @param width Width of the viewport - * @param height Height of the viewport - */ - public void setViewPort(int x, int y, int width, int height) { - logger.log(Level.FINE, "IGLESShaderRenderer setViewPort"); - if (x != vpX || vpY != y || vpW != width || vpH != height) { - JmeIosGLES.glViewport(x, y, width, height); - JmeIosGLES.checkGLError(); - - vpX = x; - vpY = y; - vpW = width; - vpH = height; - } - } - - /** - * Specifies a clipping rectangle. - * For all future rendering commands, no pixels will be allowed - * to be rendered outside of the clip rectangle. - * - * @param x The x coordinate of the clip rect - * @param y The y coordinate of the clip rect - * @param width Width of the clip rect - * @param height Height of the clip rect - */ - public void setClipRect(int x, int y, int width, int height) { - logger.log(Level.FINE, "IGLESShaderRenderer setClipRect"); - if (!context.clipRectEnabled) { - JmeIosGLES.glEnable(JmeIosGLES.GL_SCISSOR_TEST); - JmeIosGLES.checkGLError(); - context.clipRectEnabled = true; - } - if (clipX != x || clipY != y || clipW != width || clipH != height) { - JmeIosGLES.glScissor(x, y, width, height); - JmeIosGLES.checkGLError(); - clipX = x; - clipY = y; - clipW = width; - clipH = height; - } - } - - /** - * Clears the clipping rectangle set with - * {@link #setClipRect(int, int, int, int) }. - */ - public void clearClipRect() { - logger.log(Level.FINE, "IGLESShaderRenderer clearClipRect"); - if (context.clipRectEnabled) { - JmeIosGLES.glDisable(JmeIosGLES.GL_SCISSOR_TEST); - JmeIosGLES.checkGLError(); - context.clipRectEnabled = false; - - clipX = 0; - clipY = 0; - clipW = 0; - clipH = 0; - } - } - - /** - * Set lighting state. - * Does nothing if the renderer is shader based. - * The lights should be provided in world space. - * Specify null to disable lighting. - * - * @param lights The light list to set. - */ - public void setLighting(LightList lights) { - logger.log(Level.FINE, "IGLESShaderRenderer setLighting"); - } - - /** - * Sets the shader to use for rendering. - * If the shader has not been uploaded yet, it is compiled - * and linked. If it has been uploaded, then the - * uniform data is updated and the shader is set. - * - * @param shader The shader to use for rendering. - */ - public void setShader(Shader shader) { - logger.log(Level.FINE, "IGLESShaderRenderer setShader"); - if (shader == null) { - throw new IllegalArgumentException("Shader cannot be null"); - } else { - if (shader.isUpdateNeeded()) { - updateShaderData(shader); - } - - // NOTE: might want to check if any of the - // sources need an update? - - assert shader.getId() > 0; - - updateShaderUniforms(shader); - bindProgram(shader); - } - } - - /** - * Deletes a shader. This method also deletes - * the attached shader sources. - * - * @param shader Shader to delete. - */ - public void deleteShader(Shader shader) { - logger.log(Level.FINE, "IGLESShaderRenderer deleteShader"); - if (shader.getId() == -1) { - logger.warning("Shader is not uploaded to GPU, cannot delete."); - return; - } - - for (ShaderSource source : shader.getSources()) { - if (source.getId() != -1) { - JmeIosGLES.glDetachShader(shader.getId(), source.getId()); - JmeIosGLES.checkGLError(); - - deleteShaderSource(source); - } - } - - JmeIosGLES.glDeleteProgram(shader.getId()); - JmeIosGLES.checkGLError(); - - statistics.onDeleteShader(); - shader.resetObject(); - } - - /** - * Deletes the provided shader source. - * - * @param source The ShaderSource to delete. - */ - public void deleteShaderSource(ShaderSource source) { - logger.log(Level.FINE, "IGLESShaderRenderer deleteShaderSource"); - if (source.getId() < 0) { - logger.warning("Shader source is not uploaded to GPU, cannot delete."); - return; - } - - source.clearUpdateNeeded(); - - JmeIosGLES.glDeleteShader(source.getId()); - JmeIosGLES.checkGLError(); - - source.resetObject(); - } - - /** - * Copies contents from src to dst, scaling if necessary. - */ - public void copyFrameBuffer(FrameBuffer src, FrameBuffer dst) { - logger.log(Level.FINE, "IGLESShaderRenderer copyFrameBuffer"); - copyFrameBuffer(src, dst, true); - } - - /** - * Copies contents from src to dst, scaling if necessary. - * set copyDepth to false to only copy the color buffers. - */ - public void copyFrameBuffer(FrameBuffer src, FrameBuffer dst, boolean copyDepth) { - logger.warning("IGLESShaderRenderer copyFrameBuffer with depth TODO"); - throw new RendererException("Copy framebuffer not implemented yet."); - } - - /** - * Sets the framebuffer that will be drawn to. - */ - public void setFrameBuffer(FrameBuffer fb) { - logger.log(Level.FINE, "IGLESShaderRenderer setFrameBuffer"); - if (fb == null && mainFbOverride != null) { - fb = mainFbOverride; - } - - if (lastFb == fb) { - if (fb == null || !fb.isUpdateNeeded()) { - return; - } - } - - // generate mipmaps for last FB if needed - if (lastFb != null) { - for (int i = 0; i < lastFb.getNumColorBuffers(); i++) { - RenderBuffer rb = lastFb.getColorBuffer(i); - Texture tex = rb.getTexture(); - if (tex != null - && tex.getMinFilter().usesMipMapLevels()) { - setTexture(0, rb.getTexture()); - -// int textureType = convertTextureType(tex.getType(), tex.getImage().getMultiSamples(), rb.getFace()); - int textureType = convertTextureType(tex.getType()); - JmeIosGLES.glGenerateMipmap(textureType); - JmeIosGLES.checkGLError(); - } - } - } - - if (fb == null) { - // unbind any fbos - if (context.boundFBO != 0) { - JmeIosGLES.glBindFramebuffer(JmeIosGLES.GL_FRAMEBUFFER, 0); - JmeIosGLES.checkGLError(); - - statistics.onFrameBufferUse(null, true); - - context.boundFBO = 0; - } - - /* - // select back buffer - if (context.boundDrawBuf != -1) { - glDrawBuffer(initialDrawBuf); - context.boundDrawBuf = -1; - } - if (context.boundReadBuf != -1) { - glReadBuffer(initialReadBuf); - context.boundReadBuf = -1; - } - */ - - lastFb = null; - } else { - if (fb.getNumColorBuffers() == 0 && fb.getDepthBuffer() == null) { - throw new IllegalArgumentException("The framebuffer: " + fb - + "\nDoesn't have any color/depth buffers"); - } - - if (fb.isUpdateNeeded()) { - updateFrameBuffer(fb); - } - - if (context.boundFBO != fb.getId()) { - JmeIosGLES.glBindFramebuffer(JmeIosGLES.GL_FRAMEBUFFER, fb.getId()); - JmeIosGLES.checkGLError(); - - statistics.onFrameBufferUse(fb, true); - - // update viewport to reflect framebuffer's resolution - setViewPort(0, 0, fb.getWidth(), fb.getHeight()); - - context.boundFBO = fb.getId(); - } else { - statistics.onFrameBufferUse(fb, false); - } - if (fb.getNumColorBuffers() == 0) { -// // make sure to select NONE as draw buf -// // no color buffer attached. select NONE - if (context.boundDrawBuf != -2) { -// glDrawBuffer(GL_NONE); - context.boundDrawBuf = -2; - } - if (context.boundReadBuf != -2) { -// glReadBuffer(GL_NONE); - context.boundReadBuf = -2; - } - } else { - if (fb.getNumColorBuffers() > maxFBOAttachs) { - throw new RendererException("Framebuffer has more color " - + "attachments than are supported" - + " by the video hardware!"); - } - if (fb.isMultiTarget()) { - if (fb.getNumColorBuffers() > maxMRTFBOAttachs) { - throw new RendererException("Framebuffer has more" - + " multi targets than are supported" - + " by the video hardware!"); - } - - if (context.boundDrawBuf != 100 + fb.getNumColorBuffers()) { - //intBuf16.clear(); - for (int i = 0; i < 16; i++) { - intBuf16[i] = i < fb.getNumColorBuffers() ? JmeIosGLES.GL_COLOR_ATTACHMENT0 + i : 0; - } - - //intBuf16.flip();// TODO: flip -// glDrawBuffers(intBuf16); - context.boundDrawBuf = 100 + fb.getNumColorBuffers(); - } - } else { - RenderBuffer rb = fb.getColorBuffer(fb.getTargetIndex()); - // select this draw buffer - if (context.boundDrawBuf != rb.getSlot()) { - JmeIosGLES.glActiveTexture(convertAttachmentSlot(rb.getSlot())); - JmeIosGLES.checkGLError(); - - context.boundDrawBuf = rb.getSlot(); - } - } - } - - assert fb.getId() >= 0; - assert context.boundFBO == fb.getId(); - - lastFb = fb; - - checkFrameBufferStatus(fb); - } - } - - /** - * Set the framebuffer that will be set instead of the main framebuffer - * when a call to setFrameBuffer(null) is made. - * - * @param fb - */ - public void setMainFrameBufferOverride(FrameBuffer fb) { - logger.log(Level.FINE, "IGLESShaderRenderer setMainFrameBufferOverride"); - mainFbOverride = fb; - } - - /** - * Reads the pixels currently stored in the specified framebuffer - * into the given ByteBuffer object. - * Only color pixels are transferred, the format is BGRA with 8 bits - * per component. The given byte buffer should have at least - * fb.getWidth() * fb.getHeight() * 4 bytes remaining. - * - * @param fb The framebuffer to read from - * @param byteBuf The bytebuffer to transfer color data to - */ - public void readFrameBuffer(FrameBuffer fb, ByteBuffer byteBuf) { - logger.log(Level.FINE, "IGLESShaderRenderer readFrameBuffer"); - if (fb != null) { - RenderBuffer rb = fb.getColorBuffer(); - if (rb == null) { - throw new IllegalArgumentException("Specified framebuffer" - + " does not have a colorbuffer"); - } - - setFrameBuffer(fb); - } else { - setFrameBuffer(null); - } - - //JmeIosGLES.glReadPixels2(vpX, vpY, vpW, vpH, JmeIosGLES.GL_RGBA, JmeIosGLES.GL_UNSIGNED_BYTE, byteBuf.array(), 0, vpW * vpH * 4); - JmeIosGLES.glReadPixels(vpX, vpY, vpW, vpH, JmeIosGLES.GL_RGBA, JmeIosGLES.GL_UNSIGNED_BYTE, byteBuf); - JmeIosGLES.checkGLError(); - } - - /** - * Deletes a framebuffer and all attached renderbuffers - */ - public void deleteFrameBuffer(FrameBuffer fb) { - logger.log(Level.FINE, "IGLESShaderRenderer deleteFrameBuffer"); - if (fb.getId() != -1) { - if (context.boundFBO == fb.getId()) { - JmeIosGLES.glBindFramebuffer(JmeIosGLES.GL_FRAMEBUFFER, 0); - JmeIosGLES.checkGLError(); - - context.boundFBO = 0; - } - - if (fb.getDepthBuffer() != null) { - deleteRenderBuffer(fb, fb.getDepthBuffer()); - } - if (fb.getColorBuffer() != null) { - deleteRenderBuffer(fb, fb.getColorBuffer()); - } - - intBuf1[0] = fb.getId(); - JmeIosGLES.glDeleteFramebuffers(1, intBuf1, 0); - JmeIosGLES.checkGLError(); - - fb.resetObject(); - - statistics.onDeleteFrameBuffer(); - } - } - - /** - * Sets the texture to use for the given texture unit. - */ - public void setTexture(int unit, Texture tex) { - logger.log(Level.FINE, "IGLESShaderRenderer setTexture"); - Image image = tex.getImage(); - if (image.isUpdateNeeded() || (image.isGeneratedMipmapsRequired() && !image.isMipmapsGenerated()) ) { - updateTexImageData(image, tex.getType()); - } - - int texId = image.getId(); - assert texId != -1; - - if (texId == -1) { - logger.warning("error: texture image has -1 id"); - } - - Image[] textures = context.boundTextures; - - int type = convertTextureType(tex.getType()); - if (!context.textureIndexList.moveToNew(unit)) { -// if (context.boundTextureUnit != unit){ -// glActiveTexture(GL_TEXTURE0 + unit); -// context.boundTextureUnit = unit; -// } -// glEnable(type); - } - - if (textures[unit] != image) { - if (context.boundTextureUnit != unit) { - JmeIosGLES.glActiveTexture(JmeIosGLES.GL_TEXTURE0 + unit); - context.boundTextureUnit = unit; - } - - JmeIosGLES.glBindTexture(type, texId); - JmeIosGLES.checkGLError(); - - textures[unit] = image; - - statistics.onTextureUse(tex.getImage(), true); - } else { - statistics.onTextureUse(tex.getImage(), false); - } - - setupTextureParams(tex); - } - - /** - * Modify the given Texture tex with the given Image. The image will be put at x and y into the texture. - * - * @param tex the Texture that will be modified - * @param pixels the source Image data to copy data from - * @param x the x position to put the image into the texture - * @param y the y position to put the image into the texture - */ - public void modifyTexture(Texture tex, Image pixels, int x, int y) { - logger.log(Level.FINE, "IGLESShaderRenderer modifyTexture"); - setTexture(0, tex); - TextureUtil.uploadSubTexture(pixels, convertTextureType(tex.getType()), 0, x, y); - } - - /** - * Deletes a texture from the GPU. - */ - public void deleteImage(Image image) { - logger.log(Level.FINE, "IGLESShaderRenderer deleteImage"); - int texId = image.getId(); - if (texId != -1) { - intBuf1[0] = texId; - - JmeIosGLES.glDeleteTextures(1, intBuf1, 0); - JmeIosGLES.checkGLError(); - - image.resetObject(); - - statistics.onDeleteTexture(); - } - } - - /** - * Uploads a vertex buffer to the GPU. - * - * @param vb The vertex buffer to upload - */ - public void updateBufferData(VertexBuffer vb) { - logger.log(Level.FINE, "IGLESShaderRenderer updateBufferData"); - int bufId = vb.getId(); - boolean created = false; - if (bufId == -1) { - // create buffer - JmeIosGLES.glGenBuffers(1, intBuf1, 0); - JmeIosGLES.checkGLError(); - - bufId = intBuf1[0]; - vb.setId(bufId); - objManager.registerObject(vb); - - created = true; - } - - // bind buffer - int target; - if (vb.getBufferType() == VertexBuffer.Type.Index) { - target = JmeIosGLES.GL_ELEMENT_ARRAY_BUFFER; - if (context.boundElementArrayVBO != bufId) { - JmeIosGLES.glBindBuffer(target, bufId); - JmeIosGLES.checkGLError(); - - context.boundElementArrayVBO = bufId; - } - } else { - target = JmeIosGLES.GL_ARRAY_BUFFER; - if (context.boundArrayVBO != bufId) { - JmeIosGLES.glBindBuffer(target, bufId); - JmeIosGLES.checkGLError(); - - context.boundArrayVBO = bufId; - } - } - - int usage = convertUsage(vb.getUsage()); - vb.getData().rewind(); - - if (created || vb.hasDataSizeChanged()) { - // upload data based on format - int size = vb.getData().limit() * vb.getFormat().getComponentSize(); - - switch (vb.getFormat()) { - case Byte: - case UnsignedByte: - JmeIosGLES.glBufferData(target, size, (ByteBuffer) vb.getData(), usage); - JmeIosGLES.checkGLError(); - break; - case Short: - case UnsignedShort: - JmeIosGLES.glBufferData(target, size, (ShortBuffer) vb.getData(), usage); - JmeIosGLES.checkGLError(); - break; - case Int: - case UnsignedInt: - JmeIosGLES.glBufferData(target, size, (IntBuffer) vb.getData(), usage); - JmeIosGLES.checkGLError(); - break; - case Float: - JmeIosGLES.glBufferData(target, size, (FloatBuffer) vb.getData(), usage); - JmeIosGLES.checkGLError(); - break; - default: - throw new RuntimeException("Unknown buffer format."); - } - } else { - int size = vb.getData().limit() * vb.getFormat().getComponentSize(); - - switch (vb.getFormat()) { - case Byte: - case UnsignedByte: - JmeIosGLES.glBufferSubData(target, 0, size, (ByteBuffer) vb.getData()); - JmeIosGLES.checkGLError(); - break; - case Short: - case UnsignedShort: - JmeIosGLES.glBufferSubData(target, 0, size, (ShortBuffer) vb.getData()); - JmeIosGLES.checkGLError(); - break; - case Int: - case UnsignedInt: - JmeIosGLES.glBufferSubData(target, 0, size, (IntBuffer) vb.getData()); - JmeIosGLES.checkGLError(); - break; - case Float: - JmeIosGLES.glBufferSubData(target, 0, size, (FloatBuffer) vb.getData()); - JmeIosGLES.checkGLError(); - break; - default: - throw new RuntimeException("Unknown buffer format."); - } - } - vb.clearUpdateNeeded(); - } - - /** - * Deletes a vertex buffer from the GPU. - * @param vb The vertex buffer to delete - */ - public void deleteBuffer(VertexBuffer vb) { - logger.log(Level.FINE, "IGLESShaderRenderer deleteBuffer"); - int bufId = vb.getId(); - if (bufId != -1) { - // delete buffer - intBuf1[0] = bufId; - - JmeIosGLES.glDeleteBuffers(1, intBuf1, 0); - JmeIosGLES.checkGLError(); - - vb.resetObject(); - } - } - - /** - * Renders count meshes, with the geometry data supplied. - * The shader which is currently set with setShader is - * responsible for transforming the input verticies into clip space - * and shading it based on the given vertex attributes. - * The int variable gl_InstanceID can be used to access the current - * instance of the mesh being rendered inside the vertex shader. - * - * @param mesh The mesh to render - * @param lod The LOD level to use, see {@link Mesh#setLodLevels(com.jme3.scene.VertexBuffer[]) }. - * @param count Number of mesh instances to render - */ - public void renderMesh(Mesh mesh, int lod, int count, VertexBuffer[] instanceData) { - logger.log(Level.FINE, "IGLESShaderRenderer renderMesh"); - if (mesh.getVertexCount() == 0) { - return; - } - /* - * NOTE: not supported in OpenGL ES 2.0. - if (context.pointSize != mesh.getPointSize()) { - GLES10.glPointSize(mesh.getPointSize()); - context.pointSize = mesh.getPointSize(); - } - */ - if (context.lineWidth != mesh.getLineWidth()) { - JmeIosGLES.glLineWidth(mesh.getLineWidth()); - JmeIosGLES.checkGLError(); - context.lineWidth = mesh.getLineWidth(); - } - - statistics.onMeshDrawn(mesh, lod); -// if (GLContext.getCapabilities().GL_ARB_vertex_array_object){ -// renderMeshVertexArray(mesh, lod, count); -// }else{ - - if (useVBO) { - renderMeshDefault(mesh, lod, count); - } else { - renderMeshVertexArray(mesh, lod, count); - } - } - - /** - * Resets all previously used {@link NativeObject Native Objects} on this Renderer. - * The state of the native objects is reset in such way, that using - * them again will cause the renderer to reupload them. - * Call this method when you know the GL context is going to shutdown. - * - * @see NativeObject#resetObject() - */ - public void resetGLObjects() { - logger.log(Level.FINE, "IGLESShaderRenderer resetGLObjects"); - objManager.resetObjects(); - statistics.clearMemory(); - boundShader = null; - lastFb = null; - context.reset(); - } - - /** - * Deletes all previously used {@link NativeObject Native Objects} on this Renderer, and - * then resets the native objects. - * - * @see #resetGLObjects() - * @see NativeObject#deleteObject(java.lang.Object) - */ - public void cleanup() { - logger.log(Level.FINE, "IGLESShaderRenderer cleanup"); - objManager.deleteAllObjects(this); - statistics.clearMemory(); - } - - /** - * Sets the alpha to coverage state. - *

    - * When alpha coverage and multi-sampling is enabled, - * each pixel will contain alpha coverage in all - * of its subsamples, which is then combined when - * other future alpha-blended objects are rendered. - *

    - *

    - * Alpha-to-coverage is useful for rendering transparent objects - * without having to worry about sorting them. - *

    - */ - public void setAlphaToCoverage(boolean value) { - logger.log(Level.FINE, "IGLESShaderRenderer setAlphaToCoverage"); - if (value) { - JmeIosGLES.glEnable(JmeIosGLES.GL_SAMPLE_ALPHA_TO_COVERAGE); - JmeIosGLES.checkGLError(); - } else { - JmeIosGLES.glDisable(JmeIosGLES.GL_SAMPLE_ALPHA_TO_COVERAGE); - JmeIosGLES.checkGLError(); - } - } - - - /* ------------------------------------------------------------------------------ */ - - - public void initialize() { - Level store = logger.getLevel(); - logger.setLevel(Level.FINE); - - logger.log(Level.FINE, "Vendor: {0}", JmeIosGLES.glGetString(JmeIosGLES.GL_VENDOR)); - logger.log(Level.FINE, "Renderer: {0}", JmeIosGLES.glGetString(JmeIosGLES.GL_RENDERER)); - logger.log(Level.FINE, "Version: {0}", JmeIosGLES.glGetString(JmeIosGLES.GL_VERSION)); - logger.log(Level.FINE, "Shading Language Version: {0}", JmeIosGLES.glGetString(JmeIosGLES.GL_SHADING_LANGUAGE_VERSION)); - - /* - // Fix issue in TestRenderToMemory when GL_FRONT is the main - // buffer being used. - initialDrawBuf = glGetInteger(GL_DRAW_BUFFER); - initialReadBuf = glGetInteger(GL_READ_BUFFER); - - // XXX: This has to be GL_BACK for canvas on Mac - // Since initialDrawBuf is GL_FRONT for pbuffer, gotta - // change this value later on ... -// initialDrawBuf = GL_BACK; -// initialReadBuf = GL_BACK; - */ - - // Check OpenGL version - int openGlVer = extractVersion("OpenGL ES ", JmeIosGLES.glGetString(JmeIosGLES.GL_VERSION)); - if (openGlVer == -1) { - glslVer = -1; - throw new UnsupportedOperationException("OpenGL ES 2.0+ is required for IGLESShaderRenderer!"); - } - - // Check shader language version - glslVer = extractVersion("OpenGL ES GLSL ES ", JmeIosGLES.glGetString(JmeIosGLES.GL_SHADING_LANGUAGE_VERSION)); - switch (glslVer) { - // TODO: When new versions of OpenGL ES shader language come out, - // update this. - default: - caps.add(Caps.GLSL100); - break; - } - - JmeIosGLES.glGetIntegerv(JmeIosGLES.GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, intBuf16, 0); - vertexTextureUnits = intBuf16[0]; - logger.log(Level.FINE, "VTF Units: {0}", vertexTextureUnits); - if (vertexTextureUnits > 0) { - caps.add(Caps.VertexTextureFetch); - } - - JmeIosGLES.glGetIntegerv(JmeIosGLES.GL_MAX_TEXTURE_IMAGE_UNITS, intBuf16, 0); - fragTextureUnits = intBuf16[0]; - logger.log(Level.FINE, "Texture Units: {0}", fragTextureUnits); - - // Multiply vector count by 4 to get float count. - JmeIosGLES.glGetIntegerv(JmeIosGLES.GL_MAX_VERTEX_UNIFORM_VECTORS, intBuf16, 0); - vertexUniforms = intBuf16[0] * 4; - logger.log(Level.FINER, "Vertex Uniforms: {0}", vertexUniforms); - - JmeIosGLES.glGetIntegerv(JmeIosGLES.GL_MAX_FRAGMENT_UNIFORM_VECTORS, intBuf16, 0); - fragUniforms = intBuf16[0] * 4; - logger.log(Level.FINER, "Fragment Uniforms: {0}", fragUniforms); - - JmeIosGLES.glGetIntegerv(JmeIosGLES.GL_MAX_VARYING_VECTORS, intBuf16, 0); - int varyingFloats = intBuf16[0] * 4; - logger.log(Level.FINER, "Varying Floats: {0}", varyingFloats); - - JmeIosGLES.glGetIntegerv(JmeIosGLES.GL_MAX_VERTEX_ATTRIBS, intBuf16, 0); - vertexAttribs = intBuf16[0]; - logger.log(Level.FINE, "Vertex Attributes: {0}", vertexAttribs); - - JmeIosGLES.glGetIntegerv(JmeIosGLES.GL_SUBPIXEL_BITS, intBuf16, 0); - int subpixelBits = intBuf16[0]; - logger.log(Level.FINE, "Subpixel Bits: {0}", subpixelBits); - -// GLES10.glGetIntegerv(GLES10.GL_MAX_ELEMENTS_VERTICES, intBuf16); -// maxVertCount = intBuf16.get(0); -// logger.log(Level.FINER, "Preferred Batch Vertex Count: {0}", maxVertCount); -// -// GLES10.glGetIntegerv(GLES10.GL_MAX_ELEMENTS_INDICES, intBuf16); -// maxTriCount = intBuf16.get(0); -// logger.log(Level.FINER, "Preferred Batch Index Count: {0}", maxTriCount); - - JmeIosGLES.glGetIntegerv(JmeIosGLES.GL_MAX_TEXTURE_SIZE, intBuf16, 0); - maxTexSize = intBuf16[0]; - logger.log(Level.FINE, "Maximum Texture Resolution: {0}", maxTexSize); - - JmeIosGLES.glGetIntegerv(JmeIosGLES.GL_MAX_CUBE_MAP_TEXTURE_SIZE, intBuf16, 0); - maxCubeTexSize = intBuf16[0]; - logger.log(Level.FINE, "Maximum CubeMap Resolution: {0}", maxCubeTexSize); - - JmeIosGLES.glGetIntegerv(JmeIosGLES.GL_MAX_RENDERBUFFER_SIZE, intBuf16, 0); - maxRBSize = intBuf16[0]; - logger.log(Level.FINER, "FBO RB Max Size: {0}", maxRBSize); - - /* - if (ctxCaps.GL_ARB_color_buffer_float){ - // XXX: Require both 16 and 32 bit float support for FloatColorBuffer. - if (ctxCaps.GL_ARB_half_float_pixel){ - caps.add(Caps.FloatColorBuffer); - } - } - - if (ctxCaps.GL_ARB_depth_buffer_float){ - caps.add(Caps.FloatDepthBuffer); - } - - if (ctxCaps.GL_ARB_draw_instanced) - caps.add(Caps.MeshInstancing); - - if (ctxCaps.GL_ARB_texture_buffer_object) - caps.add(Caps.TextureBuffer); - - if (ctxCaps.GL_ARB_texture_float){ - if (ctxCaps.GL_ARB_half_float_pixel){ - caps.add(Caps.FloatTexture); - } - } - - if (ctxCaps.GL_EXT_packed_float){ - caps.add(Caps.PackedFloatColorBuffer); - if (ctxCaps.GL_ARB_half_float_pixel){ - // because textures are usually uploaded as RGB16F - // need half-float pixel - caps.add(Caps.PackedFloatTexture); - } - } - - if (ctxCaps.GL_EXT_texture_array) - caps.add(Caps.TextureArray); - - if (ctxCaps.GL_EXT_texture_shared_exponent) - caps.add(Caps.SharedExponentTexture); - - if (ctxCaps.GL_EXT_framebuffer_object){ - caps.add(Caps.FrameBuffer); - - glGetInteger(GL_MAX_RENDERBUFFER_SIZE_EXT, intBuf16); - maxRBSize = intBuf16.get(0); - logger.log(Level.FINER, "FBO RB Max Size: {0}", maxRBSize); - - glGetInteger(GL_MAX_COLOR_ATTACHMENTS_EXT, intBuf16); - maxFBOAttachs = intBuf16.get(0); - logger.log(Level.FINER, "FBO Max renderbuffers: {0}", maxFBOAttachs); - - if (ctxCaps.GL_EXT_framebuffer_multisample){ - caps.add(Caps.FrameBufferMultisample); - - glGetInteger(GL_MAX_SAMPLES_EXT, intBuf16); - maxFBOSamples = intBuf16.get(0); - logger.log(Level.FINER, "FBO Max Samples: {0}", maxFBOSamples); - } - - if (ctxCaps.GL_ARB_draw_buffers){ - caps.add(Caps.FrameBufferMRT); - glGetInteger(ARBDrawBuffers.GL_MAX_DRAW_BUFFERS_ARB, intBuf16); - maxMRTFBOAttachs = intBuf16.get(0); - logger.log(Level.FINER, "FBO Max MRT renderbuffers: {0}", maxMRTFBOAttachs); - } - } - - if (ctxCaps.GL_ARB_multisample){ - glGetInteger(ARBMultisample.GL_SAMPLE_BUFFERS_ARB, intBuf16); - boolean available = intBuf16.get(0) != 0; - glGetInteger(ARBMultisample.GL_SAMPLES_ARB, intBuf16); - int samples = intBuf16.get(0); - logger.log(Level.FINER, "Samples: {0}", samples); - boolean enabled = glIsEnabled(ARBMultisample.GL_MULTISAMPLE_ARB); - if (samples > 0 && available && !enabled){ - glEnable(ARBMultisample.GL_MULTISAMPLE_ARB); - } - } - */ - - String extensions = JmeIosGLES.glGetString(JmeIosGLES.GL_EXTENSIONS); - logger.log(Level.FINE, "GL_EXTENSIONS: {0}", extensions); - - // Get number of compressed formats available. - JmeIosGLES.glGetIntegerv(JmeIosGLES.GL_NUM_COMPRESSED_TEXTURE_FORMATS, intBuf16, 0); - int numCompressedFormats = intBuf16[0]; - - // Allocate buffer for compressed formats. - int[] compressedFormats = new int[numCompressedFormats]; - JmeIosGLES.glGetIntegerv(JmeIosGLES.GL_COMPRESSED_TEXTURE_FORMATS, compressedFormats, 0); - - // Check for errors after all glGet calls. - JmeIosGLES.checkGLError(); - - // Print compressed formats. - for (int i = 0; i < numCompressedFormats; i++) { - logger.log(Level.FINE, "Compressed Texture Formats: {0}", compressedFormats[i]); - } - - TextureUtil.loadTextureFeatures(extensions); - - applyRenderState(RenderState.DEFAULT); - JmeIosGLES.glDisable(JmeIosGLES.GL_DITHER); - JmeIosGLES.checkGLError(); - - logger.log(Level.FINE, "Caps: {0}", caps); - logger.setLevel(store); - - uintIndexSupport = extensions.contains("GL_OES_element_index_uint"); - logger.log(Level.FINE, "Support for UInt index: {0}", uintIndexSupport); - } - - - /* ------------------------------------------------------------------------------ */ - - - private int extractVersion(String prefixStr, String versionStr) { - if (versionStr != null) { - int spaceIdx = versionStr.indexOf(" ", prefixStr.length()); - if (spaceIdx >= 1) { - versionStr = versionStr.substring(prefixStr.length(), spaceIdx).trim(); - } else { - versionStr = versionStr.substring(prefixStr.length()).trim(); - } - float version = Float.parseFloat(versionStr); - return (int) (version * 100); - } else { - return -1; - } - } - - private void deleteRenderBuffer(FrameBuffer fb, RenderBuffer rb) { - intBuf1[0] = rb.getId(); - JmeIosGLES.glDeleteRenderbuffers(1, intBuf1, 0); - JmeIosGLES.checkGLError(); - } - - private int convertUsage(Usage usage) { - switch (usage) { - case Static: - return JmeIosGLES.GL_STATIC_DRAW; - case Dynamic: - return JmeIosGLES.GL_DYNAMIC_DRAW; - case Stream: - return JmeIosGLES.GL_STREAM_DRAW; - default: - throw new RuntimeException("Unknown usage type."); - } - } - - - protected void bindProgram(Shader shader) { - int shaderId = shader.getId(); - if (context.boundShaderProgram != shaderId) { - JmeIosGLES.glUseProgram(shaderId); - JmeIosGLES.checkGLError(); - - statistics.onShaderUse(shader, true); - boundShader = shader; - context.boundShaderProgram = shaderId; - } else { - statistics.onShaderUse(shader, false); - } - } - - protected void updateShaderUniforms(Shader shader) { - ListMap uniforms = shader.getUniformMap(); - for (int i = 0; i < uniforms.size(); i++) { - Uniform uniform = uniforms.getValue(i); - if (uniform.isUpdateNeeded()) { - updateUniform(shader, uniform); - } - } - } - - - protected void updateUniform(Shader shader, Uniform uniform) { - logger.log(Level.FINE, "IGLESShaderRenderer private updateUniform: " + uniform.getVarType()); - int shaderId = shader.getId(); - - assert uniform.getName() != null; - assert shader.getId() > 0; - - if (context.boundShaderProgram != shaderId) { - JmeIosGLES.glUseProgram(shaderId); - JmeIosGLES.checkGLError(); - - statistics.onShaderUse(shader, true); - boundShader = shader; - context.boundShaderProgram = shaderId; - } else { - statistics.onShaderUse(shader, false); - } - - int loc = uniform.getLocation(); - if (loc == -1) { - return; - } - - if (loc == -2) { - // get uniform location - updateUniformLocation(shader, uniform); - if (uniform.getLocation() == -1) { - // not declared, ignore - uniform.clearUpdateNeeded(); - return; - } - loc = uniform.getLocation(); - } - - if (uniform.getVarType() == null) { - // removed logging the warning to avoid flooding the log - // (LWJGL also doesn't post a warning) - //logger.log(Level.FINEST, "Uniform value is not set yet. Shader: {0}, Uniform: {1}", - // new Object[]{shader.toString(), uniform.toString()}); - return; // value not set yet.. - } - - statistics.onUniformSet(); - - uniform.clearUpdateNeeded(); - ByteBuffer bb;//GetPrimitiveArrayCritical - FloatBuffer fb; - IntBuffer ib; - switch (uniform.getVarType()) { - case Float: - Float f = (Float) uniform.getValue(); - JmeIosGLES.glUniform1f(loc, f.floatValue()); - break; - case Vector2: - Vector2f v2 = (Vector2f) uniform.getValue(); - JmeIosGLES.glUniform2f(loc, v2.getX(), v2.getY()); - break; - case Vector3: - Vector3f v3 = (Vector3f) uniform.getValue(); - JmeIosGLES.glUniform3f(loc, v3.getX(), v3.getY(), v3.getZ()); - break; - case Vector4: - Object val = uniform.getValue(); - if (val instanceof ColorRGBA) { - ColorRGBA c = (ColorRGBA) val; - JmeIosGLES.glUniform4f(loc, c.r, c.g, c.b, c.a); - } else if (val instanceof Vector4f) { - Vector4f c = (Vector4f) val; - JmeIosGLES.glUniform4f(loc, c.x, c.y, c.z, c.w); - } else { - Quaternion c = (Quaternion) uniform.getValue(); - JmeIosGLES.glUniform4f(loc, c.getX(), c.getY(), c.getZ(), c.getW()); - } - break; - case Boolean: - Boolean b = (Boolean) uniform.getValue(); - JmeIosGLES.glUniform1i(loc, b.booleanValue() ? JmeIosGLES.GL_TRUE : JmeIosGLES.GL_FALSE); - break; - case Matrix3: - fb = (FloatBuffer) uniform.getValue(); - assert fb.remaining() == 9; - JmeIosGLES.glUniformMatrix3fv(loc, 1, false, fb); - break; - case Matrix4: - fb = (FloatBuffer) uniform.getValue(); - assert fb.remaining() == 16; - JmeIosGLES.glUniformMatrix4fv(loc, 1, false, fb); - break; - case IntArray: - ib = (IntBuffer) uniform.getValue(); - JmeIosGLES.glUniform1iv(loc, ib.limit(), ib); - break; - case FloatArray: - fb = (FloatBuffer) uniform.getValue(); - JmeIosGLES.glUniform1fv(loc, fb.limit(), fb); - break; - case Vector2Array: - fb = (FloatBuffer) uniform.getValue(); - JmeIosGLES.glUniform2fv(loc, fb.limit() / 2, fb); - break; - case Vector3Array: - fb = (FloatBuffer) uniform.getValue(); - JmeIosGLES.glUniform3fv(loc, fb.limit() / 3, fb); - break; - case Vector4Array: - fb = (FloatBuffer) uniform.getValue(); - JmeIosGLES.glUniform4fv(loc, fb.limit() / 4, fb); - break; - case Matrix4Array: - fb = (FloatBuffer) uniform.getValue(); - JmeIosGLES.glUniformMatrix4fv(loc, fb.limit() / 16, false, fb); - break; - case Int: - Integer i = (Integer) uniform.getValue(); - JmeIosGLES.glUniform1i(loc, i.intValue()); - break; - default: - throw new UnsupportedOperationException("Unsupported uniform type: " + uniform.getVarType()); - } - JmeIosGLES.checkGLError(); - } - - protected void updateUniformLocation(Shader shader, Uniform uniform) { - stringBuf.setLength(0); - stringBuf.append(uniform.getName()).append('\0'); - updateNameBuffer(); - int loc = JmeIosGLES.glGetUniformLocation(shader.getId(), uniform.getName()); - JmeIosGLES.checkGLError(); - - if (loc < 0) { - uniform.setLocation(-1); - // uniform is not declared in shader - } else { - uniform.setLocation(loc); - } - } - - protected void updateNameBuffer() { - int len = stringBuf.length(); - - nameBuf.position(0); - nameBuf.limit(len); - for (int i = 0; i < len; i++) { - nameBuf.put((byte) stringBuf.charAt(i)); - } - - nameBuf.rewind(); - } - - - public void updateShaderData(Shader shader) { - int id = shader.getId(); - boolean needRegister = false; - if (id == -1) { - // create program - id = JmeIosGLES.glCreateProgram(); - JmeIosGLES.checkGLError(); - - if (id <= 0) { - throw new RendererException("Invalid ID received when trying to create shader program."); - } - - shader.setId(id); - needRegister = true; - } - - for (ShaderSource source : shader.getSources()) { - if (source.isUpdateNeeded()) { - updateShaderSourceData(source); - } - - JmeIosGLES.glAttachShader(id, source.getId()); - JmeIosGLES.checkGLError(); - } - - // link shaders to program - JmeIosGLES.glLinkProgram(id); - JmeIosGLES.checkGLError(); - - JmeIosGLES.glGetProgramiv(id, JmeIosGLES.GL_LINK_STATUS, intBuf1, 0); - JmeIosGLES.checkGLError(); - - boolean linkOK = intBuf1[0] == JmeIosGLES.GL_TRUE; - String infoLog = null; - - if (VALIDATE_SHADER || !linkOK) { - JmeIosGLES.glGetProgramiv(id, JmeIosGLES.GL_INFO_LOG_LENGTH, intBuf1, 0); - JmeIosGLES.checkGLError(); - - int length = intBuf1[0]; - if (length > 3) { - // get infos - infoLog = JmeIosGLES.glGetProgramInfoLog(id); - JmeIosGLES.checkGLError(); - } - } - - if (linkOK) { - if (infoLog != null) { - logger.log(Level.FINE, "shader link success. \n{0}", infoLog); - } else { - logger.fine("shader link success"); - } - shader.clearUpdateNeeded(); - if (needRegister) { - // Register shader for clean up if it was created in this method. - objManager.registerObject(shader); - statistics.onNewShader(); - } else { - // OpenGL spec: uniform locations may change after re-link - resetUniformLocations(shader); - } - } else { - if (infoLog != null) { - throw new RendererException("Shader link failure, shader:" + shader + "\n" + infoLog); - } else { - throw new RendererException("Shader link failure, shader:" + shader + "\ninfo: "); - } - } - } - - protected void resetUniformLocations(Shader shader) { - ListMap uniforms = shader.getUniformMap(); - for (int i = 0; i < uniforms.size(); i++) { - Uniform uniform = uniforms.getValue(i); - uniform.reset(); // e.g check location again - } - } - - public void updateTexImageData(Image img, Texture.Type type) { - int texId = img.getId(); - if (texId == -1) { - // create texture - JmeIosGLES.glGenTextures(1, intBuf1, 0); - JmeIosGLES.checkGLError(); - - texId = intBuf1[0]; - img.setId(texId); - objManager.registerObject(img); - - statistics.onNewTexture(); - } - - // bind texture - int target = convertTextureType(type); - if (context.boundTextures[0] != img) { - if (context.boundTextureUnit != 0) { - JmeIosGLES.glActiveTexture(JmeIosGLES.GL_TEXTURE0); - JmeIosGLES.checkGLError(); - - context.boundTextureUnit = 0; - } - - JmeIosGLES.glBindTexture(target, texId); - JmeIosGLES.checkGLError(); - - context.boundTextures[0] = img; - } - - boolean needMips = false; - if (img.isGeneratedMipmapsRequired()) { - needMips = true; - img.setMipmapsGenerated(true); - } - - if (target == JmeIosGLES.GL_TEXTURE_CUBE_MAP) { - // Check max texture size before upload - if (img.getWidth() > maxCubeTexSize || img.getHeight() > maxCubeTexSize) { - throw new RendererException("Cannot upload cubemap " + img + ". The maximum supported cubemap resolution is " + maxCubeTexSize); - } - } else { - if (img.getWidth() > maxTexSize || img.getHeight() > maxTexSize) { - throw new RendererException("Cannot upload texture " + img + ". The maximum supported texture resolution is " + maxTexSize); - } - } - - if (target == JmeIosGLES.GL_TEXTURE_CUBE_MAP) { - // Upload a cube map / sky box - /* - @SuppressWarnings("unchecked") - List bmps = (List) img.getEfficentData(); - if (bmps != null) { - // Native android bitmap - if (bmps.size() != 6) { - throw new UnsupportedOperationException("Invalid texture: " + img - + "Cubemap textures must contain 6 data units."); - } - for (int i = 0; i < 6; i++) { - TextureUtil.uploadTextureBitmap(JmeIosGLES.GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, bmps.get(i).getBitmap(), needMips); - bmps.get(i).notifyBitmapUploaded(); - } - } else { - */ - // Standard jme3 image data - List data = img.getData(); - if (data.size() != 6) { - throw new UnsupportedOperationException("Invalid texture: " + img - + "Cubemap textures must contain 6 data units."); - } - for (int i = 0; i < 6; i++) { - TextureUtil.uploadTextureAny(img, JmeIosGLES.GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, i, needMips); - } - //} - } else { - TextureUtil.uploadTextureAny(img, target, 0, needMips); - /* - if (img.getEfficentData() instanceof AndroidImageInfo) { - AndroidImageInfo info = (AndroidImageInfo) img.getEfficentData(); - info.notifyBitmapUploaded(); - } - */ - } - - img.clearUpdateNeeded(); - } - - private void setupTextureParams(Texture tex) { - int target = convertTextureType(tex.getType()); - - // filter things - int minFilter = convertMinFilter(tex.getMinFilter()); - int magFilter = convertMagFilter(tex.getMagFilter()); - - JmeIosGLES.glTexParameteri(target, JmeIosGLES.GL_TEXTURE_MIN_FILTER, minFilter); - JmeIosGLES.checkGLError(); - JmeIosGLES.glTexParameteri(target, JmeIosGLES.GL_TEXTURE_MAG_FILTER, magFilter); - JmeIosGLES.checkGLError(); - - /* - if (tex.getAnisotropicFilter() > 1){ - - if (GLContext.getCapabilities().GL_EXT_texture_filter_anisotropic){ - glTexParameterf(target, - EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT, - tex.getAnisotropicFilter()); - } - - } - */ - // repeat modes - - switch (tex.getType()) { - case ThreeDimensional: - case CubeMap: // cubemaps use 3D coords - // GL_TEXTURE_WRAP_R is not available in api 8 - //GLES20.glTexParameteri(target, GLES20.GL_TEXTURE_WRAP_R, convertWrapMode(tex.getWrap(WrapAxis.R))); - case TwoDimensional: - case TwoDimensionalArray: - JmeIosGLES.glTexParameteri(target, JmeIosGLES.GL_TEXTURE_WRAP_T, convertWrapMode(tex.getWrap(WrapAxis.T))); - - // fall down here is intentional.. -// case OneDimensional: - JmeIosGLES.glTexParameteri(target, JmeIosGLES.GL_TEXTURE_WRAP_S, convertWrapMode(tex.getWrap(WrapAxis.S))); - - JmeIosGLES.checkGLError(); - break; - default: - throw new UnsupportedOperationException("Unknown texture type: " + tex.getType()); - } - - // R to Texture compare mode -/* - if (tex.getShadowCompareMode() != Texture.ShadowCompareMode.Off){ - GLES20.glTexParameteri(target, GLES20.GL_TEXTURE_COMPARE_MODE, GLES20.GL_COMPARE_R_TO_TEXTURE); - GLES20.glTexParameteri(target, GLES20.GL_DEPTH_TEXTURE_MODE, GLES20.GL_INTENSITY); - if (tex.getShadowCompareMode() == Texture.ShadowCompareMode.GreaterOrEqual){ - GLES20.glTexParameteri(target, GLES20.GL_TEXTURE_COMPARE_FUNC, GLES20.GL_GEQUAL); - }else{ - GLES20.glTexParameteri(target, GLES20.GL_TEXTURE_COMPARE_FUNC, GLES20.GL_LEQUAL); - } - } - */ - } - - private int convertTextureType(Texture.Type type) { - switch (type) { - case TwoDimensional: - return JmeIosGLES.GL_TEXTURE_2D; - // case TwoDimensionalArray: - // return EXTTextureArray.GL_TEXTURE_2D_ARRAY_EXT; -// case ThreeDimensional: - // return GLES20.GL_TEXTURE_3D; - case CubeMap: - return JmeIosGLES.GL_TEXTURE_CUBE_MAP; - default: - throw new UnsupportedOperationException("Unknown texture type: " + type); - } - } - - private int convertMagFilter(Texture.MagFilter filter) { - switch (filter) { - case Bilinear: - return JmeIosGLES.GL_LINEAR; - case Nearest: - return JmeIosGLES.GL_NEAREST; - default: - throw new UnsupportedOperationException("Unknown mag filter: " + filter); - } - } - - private int convertMinFilter(Texture.MinFilter filter) { - switch (filter) { - case Trilinear: - return JmeIosGLES.GL_LINEAR_MIPMAP_LINEAR; - case BilinearNearestMipMap: - return JmeIosGLES.GL_LINEAR_MIPMAP_NEAREST; - case NearestLinearMipMap: - return JmeIosGLES.GL_NEAREST_MIPMAP_LINEAR; - case NearestNearestMipMap: - return JmeIosGLES.GL_NEAREST_MIPMAP_NEAREST; - case BilinearNoMipMaps: - return JmeIosGLES.GL_LINEAR; - case NearestNoMipMaps: - return JmeIosGLES.GL_NEAREST; - default: - throw new UnsupportedOperationException("Unknown min filter: " + filter); - } - } - - private int convertWrapMode(Texture.WrapMode mode) { - switch (mode) { - case BorderClamp: - case Clamp: - case EdgeClamp: - return JmeIosGLES.GL_CLAMP_TO_EDGE; - case Repeat: - return JmeIosGLES.GL_REPEAT; - case MirroredRepeat: - return JmeIosGLES.GL_MIRRORED_REPEAT; - default: - throw new UnsupportedOperationException("Unknown wrap mode: " + mode); - } - } - - private void renderMeshVertexArray(Mesh mesh, int lod, int count) { - for (VertexBuffer vb : mesh.getBufferList().getArray()) { - if (vb.getBufferType() == Type.InterleavedData - || vb.getUsage() == Usage.CpuOnly // ignore cpu-only buffers - || vb.getBufferType() == Type.Index) { - continue; - } - - if (vb.getStride() == 0) { - // not interleaved - setVertexAttrib_Array(vb); - } else { - // interleaved - VertexBuffer interleavedData = mesh.getBuffer(Type.InterleavedData); - setVertexAttrib_Array(vb, interleavedData); - } - } - - VertexBuffer indices = null; - if (mesh.getNumLodLevels() > 0) { - indices = mesh.getLodLevel(lod); - } else { - indices = mesh.getBuffer(Type.Index);//buffers.get(Type.Index.ordinal()); - } - if (indices != null) { - drawTriangleList_Array(indices, mesh, count); - } else { - JmeIosGLES.glDrawArrays(convertElementMode(mesh.getMode()), 0, mesh.getVertexCount()); - JmeIosGLES.checkGLError(); - } - clearVertexAttribs(); - clearTextureUnits(); - } - - private void renderMeshDefault(Mesh mesh, int lod, int count) { - VertexBuffer indices = null; - VertexBuffer interleavedData = mesh.getBuffer(Type.InterleavedData); - if (interleavedData != null && interleavedData.isUpdateNeeded()) { - updateBufferData(interleavedData); - } - - //IntMap buffers = mesh.getBuffers(); ; - if (mesh.getNumLodLevels() > 0) { - indices = mesh.getLodLevel(lod); - } else { - indices = mesh.getBuffer(Type.Index);// buffers.get(Type.Index.ordinal()); - } - for (VertexBuffer vb : mesh.getBufferList().getArray()){ - if (vb.getBufferType() == Type.InterleavedData - || vb.getUsage() == Usage.CpuOnly // ignore cpu-only buffers - || vb.getBufferType() == Type.Index) { - continue; - } - - if (vb.getStride() == 0) { - // not interleaved - setVertexAttrib(vb); - } else { - // interleaved - setVertexAttrib(vb, interleavedData); - } - } - if (indices != null) { - drawTriangleList(indices, mesh, count); - } else { -// throw new UnsupportedOperationException("Cannot render without index buffer"); - JmeIosGLES.glDrawArrays(convertElementMode(mesh.getMode()), 0, mesh.getVertexCount()); - JmeIosGLES.checkGLError(); - } - clearVertexAttribs(); - clearTextureUnits(); - } - - - public void setVertexAttrib(VertexBuffer vb, VertexBuffer idb) { - if (vb.getBufferType() == VertexBuffer.Type.Index) { - throw new IllegalArgumentException("Index buffers not allowed to be set to vertex attrib"); - } - - if (vb.isUpdateNeeded() && idb == null) { - updateBufferData(vb); - } - - int programId = context.boundShaderProgram; - if (programId > 0) { - Attribute attrib = boundShader.getAttribute(vb.getBufferType()); - int loc = attrib.getLocation(); - if (loc == -1) { - return; // not defined - } - - if (loc == -2) { -// stringBuf.setLength(0); -// stringBuf.append("in").append(vb.getBufferType().name()).append('\0'); -// updateNameBuffer(); - - String attributeName = "in" + vb.getBufferType().name(); - loc = JmeIosGLES.glGetAttribLocation(programId, attributeName); - JmeIosGLES.checkGLError(); - - // not really the name of it in the shader (inPosition\0) but - // the internal name of the enum (Position). - if (loc < 0) { - attrib.setLocation(-1); - return; // not available in shader. - } else { - attrib.setLocation(loc); - } - } - - VertexBuffer[] attribs = context.boundAttribs; - if (!context.attribIndexList.moveToNew(loc)) { - JmeIosGLES.glEnableVertexAttribArray(loc); - JmeIosGLES.checkGLError(); - //System.out.println("Enabled ATTRIB IDX: "+loc); - } - if (attribs[loc] != vb) { - // NOTE: Use id from interleaved buffer if specified - int bufId = idb != null ? idb.getId() : vb.getId(); - assert bufId != -1; - - if (bufId == -1) { - logger.warning("invalid buffer id"); - } - - if (context.boundArrayVBO != bufId) { - JmeIosGLES.glBindBuffer(JmeIosGLES.GL_ARRAY_BUFFER, bufId); - JmeIosGLES.checkGLError(); - - context.boundArrayVBO = bufId; - } - - vb.getData().rewind(); - /* - Android22Workaround.glVertexAttribPointer(loc, - vb.getNumComponents(), - convertVertexBufferFormat(vb.getFormat()), - vb.isNormalized(), - vb.getStride(), - 0); - */ - logger.warning("iTODO Android22Workaround"); - - JmeIosGLES.glVertexAttribPointer(loc, - vb.getNumComponents(), - convertVertexBufferFormat(vb.getFormat()), - vb.isNormalized(), - vb.getStride(), - null); - - JmeIosGLES.checkGLError(); - - attribs[loc] = vb; - } - } else { - throw new IllegalStateException("Cannot render mesh without shader bound"); - } - } - - public void setVertexAttrib(VertexBuffer vb) { - setVertexAttrib(vb, null); - } - - public void drawTriangleArray(Mesh.Mode mode, int count, int vertCount) { - /* if (count > 1){ - ARBDrawInstanced.glDrawArraysInstancedARB(convertElementMode(mode), 0, - vertCount, count); - }else{*/ - JmeIosGLES.glDrawArrays(convertElementMode(mode), 0, vertCount); - JmeIosGLES.checkGLError(); - /* - }*/ - } - - public void drawTriangleList(VertexBuffer indexBuf, Mesh mesh, int count) { - if (indexBuf.getBufferType() != VertexBuffer.Type.Index) { - throw new IllegalArgumentException("Only index buffers are allowed as triangle lists."); - } - - if (indexBuf.isUpdateNeeded()) { - updateBufferData(indexBuf); - } - - int bufId = indexBuf.getId(); - assert bufId != -1; - - if (bufId == -1) { - throw new RendererException("Invalid buffer ID"); - } - - if (context.boundElementArrayVBO != bufId) { - JmeIosGLES.glBindBuffer(JmeIosGLES.GL_ELEMENT_ARRAY_BUFFER, bufId); - JmeIosGLES.checkGLError(); - - context.boundElementArrayVBO = bufId; - } - - int vertCount = mesh.getVertexCount(); - boolean useInstancing = count > 1 && caps.contains(Caps.MeshInstancing); - - Buffer indexData = indexBuf.getData(); - - if (!uintIndexSupport && (indexBuf.getFormat() == Format.UnsignedInt)) { - throw new RendererException("OpenGL ES does not support 32-bit index buffers." + - "Split your models to avoid going over 65536 vertices."); - } - - if (mesh.getMode() == Mode.Hybrid) { - int[] modeStart = mesh.getModeStart(); - int[] elementLengths = mesh.getElementLengths(); - - int elMode = convertElementMode(Mode.Triangles); - int fmt = convertVertexBufferFormat(indexBuf.getFormat()); - int elSize = indexBuf.getFormat().getComponentSize(); - int listStart = modeStart[0]; - int stripStart = modeStart[1]; - int fanStart = modeStart[2]; - int curOffset = 0; - for (int i = 0; i < elementLengths.length; i++) { - if (i == stripStart) { - elMode = convertElementMode(Mode.TriangleStrip); - } else if (i == fanStart) { - elMode = convertElementMode(Mode.TriangleStrip); - } - int elementLength = elementLengths[i]; - - if (useInstancing) { - //ARBDrawInstanced. - throw new IllegalArgumentException("instancing is not supported."); - /* - GLES20.glDrawElementsInstancedARB(elMode, - elementLength, - fmt, - curOffset, - count); - */ - } else { - indexBuf.getData().position(curOffset); - JmeIosGLES.glDrawElements(elMode, elementLength, fmt, indexBuf.getData()); - JmeIosGLES.checkGLError(); - /* - glDrawRangeElements(elMode, - 0, - vertCount, - elementLength, - fmt, - curOffset); - */ - } - - curOffset += elementLength * elSize; - } - } else { - if (useInstancing) { - throw new IllegalArgumentException("instancing is not supported."); - //ARBDrawInstanced. -/* - GLES20.glDrawElementsInstancedARB(convertElementMode(mesh.getMode()), - indexBuf.getData().limit(), - convertVertexBufferFormat(indexBuf.getFormat()), - 0, - count); - */ - } else { - logger.log(Level.FINE, "IGLESShaderRenderer drawTriangleList TODO check"); - indexData.rewind(); - JmeIosGLES.glDrawElementsIndex( - convertElementMode(mesh.getMode()), - indexBuf.getData().limit(), - convertVertexBufferFormat(indexBuf.getFormat()), - 0); - /*TODO: - indexData.rewind(); - JmeIosGLES.glDrawElements( - convertElementMode(mesh.getMode()), - indexBuf.getData().limit(), - convertVertexBufferFormat(indexBuf.getFormat()), - 0); - */ - JmeIosGLES.checkGLError(); - } - } - } - - public int convertElementMode(Mesh.Mode mode) { - switch (mode) { - case Points: - return JmeIosGLES.GL_POINTS; - case Lines: - return JmeIosGLES.GL_LINES; - case LineLoop: - return JmeIosGLES.GL_LINE_LOOP; - case LineStrip: - return JmeIosGLES.GL_LINE_STRIP; - case Triangles: - return JmeIosGLES.GL_TRIANGLES; - case TriangleFan: - return JmeIosGLES.GL_TRIANGLE_FAN; - case TriangleStrip: - return JmeIosGLES.GL_TRIANGLE_STRIP; - default: - throw new UnsupportedOperationException("Unrecognized mesh mode: " + mode); - } - } - - - private int convertVertexBufferFormat(Format format) { - switch (format) { - case Byte: - return JmeIosGLES.GL_BYTE; - case UnsignedByte: - return JmeIosGLES.GL_UNSIGNED_BYTE; - case Short: - return JmeIosGLES.GL_SHORT; - case UnsignedShort: - return JmeIosGLES.GL_UNSIGNED_SHORT; - case Int: - return JmeIosGLES.GL_INT; - case UnsignedInt: - return JmeIosGLES.GL_UNSIGNED_INT; - /* - case Half: - return NVHalfFloat.GL_HALF_FLOAT_NV; - // return ARBHalfFloatVertex.GL_HALF_FLOAT; - */ - case Float: - return JmeIosGLES.GL_FLOAT; -// case Double: -// return JmeIosGLES.GL_DOUBLE; - default: - throw new RuntimeException("Unknown buffer format."); - - } - } - - public void clearVertexAttribs() { - IDList attribList = context.attribIndexList; - for (int i = 0; i < attribList.oldLen; i++) { - int idx = attribList.oldList[i]; - - JmeIosGLES.glDisableVertexAttribArray(idx); - JmeIosGLES.checkGLError(); - - context.boundAttribs[idx] = null; - } - context.attribIndexList.copyNewToOld(); - } - - - public void clearTextureUnits() { - IDList textureList = context.textureIndexList; - Image[] textures = context.boundTextures; - for (int i = 0; i < textureList.oldLen; i++) { - int idx = textureList.oldList[i]; -// if (context.boundTextureUnit != idx){ -// glActiveTexture(GL_TEXTURE0 + idx); -// context.boundTextureUnit = idx; -// } -// glDisable(convertTextureType(textures[idx].getType())); - textures[idx] = null; - } - context.textureIndexList.copyNewToOld(); - } - - - public void updateFrameBuffer(FrameBuffer fb) { - int id = fb.getId(); - if (id == -1) { - // create FBO - JmeIosGLES.glGenFramebuffers(1, intBuf1, 0); - JmeIosGLES.checkGLError(); - - id = intBuf1[0]; - fb.setId(id); - objManager.registerObject(fb); - - statistics.onNewFrameBuffer(); - } - - if (context.boundFBO != id) { - JmeIosGLES.glBindFramebuffer(JmeIosGLES.GL_FRAMEBUFFER, id); - JmeIosGLES.checkGLError(); - - // binding an FBO automatically sets draw buf to GL_COLOR_ATTACHMENT0 - context.boundDrawBuf = 0; - context.boundFBO = id; - } - - FrameBuffer.RenderBuffer depthBuf = fb.getDepthBuffer(); - if (depthBuf != null) { - updateFrameBufferAttachment(fb, depthBuf); - } - - for (int i = 0; i < fb.getNumColorBuffers(); i++) { - FrameBuffer.RenderBuffer colorBuf = fb.getColorBuffer(i); - updateFrameBufferAttachment(fb, colorBuf); - } - - fb.clearUpdateNeeded(); - } - - - public void updateFrameBufferAttachment(FrameBuffer fb, RenderBuffer rb) { - boolean needAttach; - if (rb.getTexture() == null) { - // if it hasn't been created yet, then attach is required. - needAttach = rb.getId() == -1; - updateRenderBuffer(fb, rb); - } else { - needAttach = false; - updateRenderTexture(fb, rb); - } - if (needAttach) { - JmeIosGLES.glFramebufferRenderbuffer(JmeIosGLES.GL_FRAMEBUFFER, - convertAttachmentSlot(rb.getSlot()), - JmeIosGLES.GL_RENDERBUFFER, - rb.getId()); - - JmeIosGLES.checkGLError(); - } - } - - - public void updateRenderTexture(FrameBuffer fb, RenderBuffer rb) { - Texture tex = rb.getTexture(); - Image image = tex.getImage(); - if (image.isUpdateNeeded()) { - updateTexImageData(image, tex.getType()); - - // NOTE: For depth textures, sets nearest/no-mips mode - // Required to fix "framebuffer unsupported" - // for old NVIDIA drivers! - setupTextureParams(tex); - } - - JmeIosGLES.glFramebufferTexture2D(JmeIosGLES.GL_FRAMEBUFFER, - convertAttachmentSlot(rb.getSlot()), - convertTextureType(tex.getType()), - image.getId(), - 0); - - JmeIosGLES.checkGLError(); - } - - - private void updateRenderBuffer(FrameBuffer fb, RenderBuffer rb) { - int id = rb.getId(); - if (id == -1) { - JmeIosGLES.glGenRenderbuffers(1, intBuf1, 0); - JmeIosGLES.checkGLError(); - - id = intBuf1[0]; - rb.setId(id); - } - - if (context.boundRB != id) { - JmeIosGLES.glBindRenderbuffer(JmeIosGLES.GL_RENDERBUFFER, id); - JmeIosGLES.checkGLError(); - - context.boundRB = id; - } - - if (fb.getWidth() > maxRBSize || fb.getHeight() > maxRBSize) { - throw new RendererException("Resolution " + fb.getWidth() - + ":" + fb.getHeight() + " is not supported."); - } - - TextureUtil.IosGLImageFormat imageFormat = TextureUtil.getImageFormat(rb.getFormat()); - if (imageFormat.renderBufferStorageFormat == 0) { - throw new RendererException("The format '" + rb.getFormat() + "' cannot be used for renderbuffers."); - } - -// if (fb.getSamples() > 1 && GLContext.getCapabilities().GL_EXT_framebuffer_multisample) { - if (fb.getSamples() > 1) { -// // FIXME - throw new RendererException("Multisample FrameBuffer is not supported yet."); -// int samples = fb.getSamples(); -// if (maxFBOSamples < samples) { -// samples = maxFBOSamples; -// } -// glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, -// samples, -// glFmt.internalFormat, -// fb.getWidth(), -// fb.getHeight()); - } else { - JmeIosGLES.glRenderbufferStorage(JmeIosGLES.GL_RENDERBUFFER, - imageFormat.renderBufferStorageFormat, - fb.getWidth(), - fb.getHeight()); - - JmeIosGLES.checkGLError(); - } - } - - - private int convertAttachmentSlot(int attachmentSlot) { - // can also add support for stencil here - if (attachmentSlot == FrameBuffer.SLOT_DEPTH) { - return JmeIosGLES.GL_DEPTH_ATTACHMENT; - } else if (attachmentSlot == 0) { - return JmeIosGLES.GL_COLOR_ATTACHMENT0; - } else { - throw new UnsupportedOperationException("Android does not support multiple color attachments to an FBO"); - } - } - - - private void checkFrameBufferStatus(FrameBuffer fb) { - try { - checkFrameBufferError(); - } catch (IllegalStateException ex) { - logger.log(Level.SEVERE, "=== jMonkeyEngine FBO State ===\n{0}", fb); - printRealFrameBufferInfo(fb); - throw ex; - } - } - - private void checkFrameBufferError() { - int status = JmeIosGLES.glCheckFramebufferStatus(JmeIosGLES.GL_FRAMEBUFFER); - switch (status) { - case JmeIosGLES.GL_FRAMEBUFFER_COMPLETE: - break; - case JmeIosGLES.GL_FRAMEBUFFER_UNSUPPORTED: - //Choose different formats - throw new IllegalStateException("Framebuffer object format is " - + "unsupported by the video hardware."); - case JmeIosGLES.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: - throw new IllegalStateException("Framebuffer has erronous attachment."); - case JmeIosGLES.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: - throw new IllegalStateException("Framebuffer doesn't have any renderbuffers attached."); - case JmeIosGLES.GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: - throw new IllegalStateException("Framebuffer attachments must have same dimensions."); -// case GLES20.GL_FRAMEBUFFER_INCOMPLETE_FORMATS: -// throw new IllegalStateException("Framebuffer attachments must have same formats."); -// case GLES20.GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: -// throw new IllegalStateException("Incomplete draw buffer."); -// case GLES20.GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT: -// throw new IllegalStateException("Incomplete read buffer."); -// case GLES20.GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT: -// throw new IllegalStateException("Incomplete multisample buffer."); - default: - //Programming error; will fail on all hardware - throw new IllegalStateException("Some video driver error " - + "or programming error occured. " - + "Framebuffer object status is invalid: " + status); - } - } - - private void printRealRenderBufferInfo(FrameBuffer fb, RenderBuffer rb, String name) { - System.out.println("== Renderbuffer " + name + " =="); - System.out.println("RB ID: " + rb.getId()); - System.out.println("Is proper? " + JmeIosGLES.glIsRenderbuffer(rb.getId())); - - int attachment = convertAttachmentSlot(rb.getSlot()); - - //intBuf16.clear(); - JmeIosGLES.glGetFramebufferAttachmentParameteriv(JmeIosGLES.GL_FRAMEBUFFER, - attachment, JmeIosGLES.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, intBuf16, 0); - int type = intBuf16[0]; - - //intBuf16.clear(); - JmeIosGLES.glGetFramebufferAttachmentParameteriv(JmeIosGLES.GL_FRAMEBUFFER, - attachment, JmeIosGLES.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, intBuf16, 0); - int rbName = intBuf16[0]; - - switch (type) { - case JmeIosGLES.GL_NONE: - System.out.println("Type: None"); - break; - case JmeIosGLES.GL_TEXTURE: - System.out.println("Type: Texture"); - break; - case JmeIosGLES.GL_RENDERBUFFER: - System.out.println("Type: Buffer"); - System.out.println("RB ID: " + rbName); - break; - } - } - - private void printRealFrameBufferInfo(FrameBuffer fb) { -// boolean doubleBuffer = GLES20.glGetBooleanv(GLES20.GL_DOUBLEBUFFER); - boolean doubleBuffer = false; // FIXME -// String drawBuf = getTargetBufferName(glGetInteger(GL_DRAW_BUFFER)); -// String readBuf = getTargetBufferName(glGetInteger(GL_READ_BUFFER)); - - int fbId = fb.getId(); - //intBuf16.clear(); -// int curDrawBinding = GLES20.glGetIntegerv(GLES20.GL_DRAW_FRAMEBUFFER_BINDING); -// int curReadBinding = glGetInteger(ARBFramebufferObject.GL_READ_FRAMEBUFFER_BINDING); - - System.out.println("=== OpenGL FBO State ==="); - System.out.println("Context doublebuffered? " + doubleBuffer); - System.out.println("FBO ID: " + fbId); - System.out.println("Is proper? " + JmeIosGLES.glIsFramebuffer(fbId)); -// System.out.println("Is bound to draw? " + (fbId == curDrawBinding)); -// System.out.println("Is bound to read? " + (fbId == curReadBinding)); -// System.out.println("Draw buffer: " + drawBuf); -// System.out.println("Read buffer: " + readBuf); - - if (context.boundFBO != fbId) { - JmeIosGLES.glBindFramebuffer(JmeIosGLES.GL_FRAMEBUFFER, fbId); - context.boundFBO = fbId; - } - - if (fb.getDepthBuffer() != null) { - printRealRenderBufferInfo(fb, fb.getDepthBuffer(), "Depth"); - } - for (int i = 0; i < fb.getNumColorBuffers(); i++) { - printRealRenderBufferInfo(fb, fb.getColorBuffer(i), "Color" + i); - } - - - } - - public void drawTriangleList_Array(VertexBuffer indexBuf, Mesh mesh, int count) { - if (indexBuf.getBufferType() != VertexBuffer.Type.Index) { - throw new IllegalArgumentException("Only index buffers are allowed as triangle lists."); - } - - boolean useInstancing = count > 1 && caps.contains(Caps.MeshInstancing); - if (useInstancing) { - throw new IllegalArgumentException("Caps.MeshInstancing is not supported."); - } - - int vertCount = mesh.getVertexCount(); - Buffer indexData = indexBuf.getData(); - indexData.rewind(); - - if (mesh.getMode() == Mode.Hybrid) { - int[] modeStart = mesh.getModeStart(); - int[] elementLengths = mesh.getElementLengths(); - - int elMode = convertElementMode(Mode.Triangles); - int fmt = convertVertexBufferFormat(indexBuf.getFormat()); - int elSize = indexBuf.getFormat().getComponentSize(); - int listStart = modeStart[0]; - int stripStart = modeStart[1]; - int fanStart = modeStart[2]; - int curOffset = 0; - for (int i = 0; i < elementLengths.length; i++) { - if (i == stripStart) { - elMode = convertElementMode(Mode.TriangleStrip); - } else if (i == fanStart) { - elMode = convertElementMode(Mode.TriangleFan); - } - int elementLength = elementLengths[i]; - - indexBuf.getData().position(curOffset); - JmeIosGLES.glDrawElements(elMode, elementLength, fmt, indexBuf.getData()); - JmeIosGLES.checkGLError(); - - curOffset += elementLength * elSize; - } - } else { - JmeIosGLES.glDrawElements( - convertElementMode(mesh.getMode()), - indexBuf.getData().limit(), - convertVertexBufferFormat(indexBuf.getFormat()), - indexBuf.getData()); - JmeIosGLES.checkGLError(); - } - } - - public void setVertexAttrib_Array(VertexBuffer vb, VertexBuffer idb) { - if (vb.getBufferType() == VertexBuffer.Type.Index) { - throw new IllegalArgumentException("Index buffers not allowed to be set to vertex attrib"); - } - - // Get shader - int programId = context.boundShaderProgram; - if (programId > 0) { - VertexBuffer[] attribs = context.boundAttribs; - - Attribute attrib = boundShader.getAttribute(vb.getBufferType()); - int loc = attrib.getLocation(); - if (loc == -1) { - //throw new IllegalArgumentException("Location is invalid for attrib: [" + vb.getBufferType().name() + "]"); - return; - } else if (loc == -2) { - String attributeName = "in" + vb.getBufferType().name(); - - loc = JmeIosGLES.glGetAttribLocation(programId, attributeName); - JmeIosGLES.checkGLError(); - - if (loc < 0) { - attrib.setLocation(-1); - return; // not available in shader. - } else { - attrib.setLocation(loc); - } - - } // if (loc == -2) - - if ((attribs[loc] != vb) || vb.isUpdateNeeded()) { - // NOTE: Use data from interleaved buffer if specified - VertexBuffer avb = idb != null ? idb : vb; - avb.getData().rewind(); - avb.getData().position(vb.getOffset()); - - // Upload attribute data - JmeIosGLES.glVertexAttribPointer(loc, - vb.getNumComponents(), - convertVertexBufferFormat(vb.getFormat()), - vb.isNormalized(), - vb.getStride(), - avb.getData()); - - JmeIosGLES.checkGLError(); - - JmeIosGLES.glEnableVertexAttribArray(loc); - JmeIosGLES.checkGLError(); - - attribs[loc] = vb; - } // if (attribs[loc] != vb) - } else { - throw new IllegalStateException("Cannot render mesh without shader bound"); - } - } - - public void setVertexAttrib_Array(VertexBuffer vb) { - setVertexAttrib_Array(vb, null); - } - - - public void updateShaderSourceData(ShaderSource source) { - int id = source.getId(); - if (id == -1) { - // Create id - id = JmeIosGLES.glCreateShader(convertShaderType(source.getType())); - JmeIosGLES.checkGLError(); - - if (id <= 0) { - throw new RendererException("Invalid ID received when trying to create shader."); - } - source.setId(id); - } - - if (!source.getLanguage().equals("GLSL100")) { - throw new RendererException("This shader cannot run in OpenGL ES. " - + "Only GLSL 1.0 shaders are supported."); - } - - // upload shader source - // merge the defines and source code - byte[] definesCodeData = source.getDefines().getBytes(); - byte[] sourceCodeData = source.getSource().getBytes(); - ByteBuffer codeBuf = BufferUtils.createByteBuffer(definesCodeData.length - + sourceCodeData.length); - codeBuf.put(definesCodeData); - codeBuf.put(sourceCodeData); - codeBuf.flip(); - - if (powerVr && source.getType() == ShaderType.Vertex) { - // XXX: This is to fix a bug in old PowerVR, remove - // when no longer applicable. - JmeIosGLES.glShaderSource( - id, source.getDefines() - + source.getSource()); - } else { - String precision =""; - if (source.getType() == ShaderType.Fragment) { - precision = "precision mediump float;\n"; - } - JmeIosGLES.glShaderSource( - id, - precision - +source.getDefines() - + source.getSource()); - } -// int range[] = new int[2]; -// int precision[] = new int[1]; -// GLES20.glGetShaderPrecisionFormat(GLES20.GL_VERTEX_SHADER, GLES20.GL_HIGH_FLOAT, range, 0, precision, 0); -// System.out.println("PRECISION HIGH FLOAT VERTEX"); -// System.out.println("range "+range[0]+"," +range[1]); -// System.out.println("precision "+precision[0]); - - JmeIosGLES.glCompileShader(id); - JmeIosGLES.checkGLError(); - - JmeIosGLES.glGetShaderiv(id, JmeIosGLES.GL_COMPILE_STATUS, intBuf1, 0); - JmeIosGLES.checkGLError(); - - boolean compiledOK = intBuf1[0] == JmeIosGLES.GL_TRUE; - String infoLog = null; - - if (VALIDATE_SHADER || !compiledOK) { - // even if compile succeeded, check - // log for warnings - JmeIosGLES.glGetShaderiv(id, JmeIosGLES.GL_INFO_LOG_LENGTH, intBuf1, 0); - JmeIosGLES.checkGLError(); - infoLog = JmeIosGLES.glGetShaderInfoLog(id); - } - - if (compiledOK) { - if (infoLog != null) { - logger.log(Level.FINE, "compile success: {0}, {1}", new Object[]{source.getName(), infoLog}); - } else { - logger.log(Level.FINE, "compile success: {0}", source.getName()); - } - source.clearUpdateNeeded(); - } else { - logger.log(Level.WARNING, "Bad compile of:\n{0}", - new Object[]{ShaderDebug.formatShaderSource(stringBuf.toString() + source.getDefines() + source.getSource())}); - if (infoLog != null) { - throw new RendererException("compile error in: " + source + "\n" + infoLog); - } else { - throw new RendererException("compile error in: " + source + "\nerror: "); - } - } - } - - - public int convertShaderType(ShaderType type) { - switch (type) { - case Fragment: - return JmeIosGLES.GL_FRAGMENT_SHADER; - case Vertex: - return JmeIosGLES.GL_VERTEX_SHADER; -// case Geometry: -// return ARBGeometryShader4.GL_GEOMETRY_SHADER_ARB; - default: - throw new RuntimeException("Unrecognized shader type."); - } - } - - private int convertTestFunction(RenderState.TestFunction testFunc) { - switch (testFunc) { - case Never: - return JmeIosGLES.GL_NEVER; - case Less: - return JmeIosGLES.GL_LESS; - case LessOrEqual: - return JmeIosGLES.GL_LEQUAL; - case Greater: - return JmeIosGLES.GL_GREATER; - case GreaterOrEqual: - return JmeIosGLES.GL_GEQUAL; - case Equal: - return JmeIosGLES.GL_EQUAL; - case NotEqual: - return JmeIosGLES.GL_NOTEQUAL; - case Always: - return JmeIosGLES.GL_ALWAYS; - default: - throw new UnsupportedOperationException("Unrecognized test function: " + testFunc); - } - } - - public void setMainFrameBufferSrgb(boolean srgb) { - - } - - public void setLinearizeSrgbImages(boolean linearize) { - - } - - public void readFrameBufferWithFormat(FrameBuffer fb, ByteBuffer byteBuf, Image.Format format) { - throw new UnsupportedOperationException("Not supported yet. URA will make that work seamlessly"); - } -} \ No newline at end of file diff --git a/jme3-ios/src/main/java/com/jme3/renderer/ios/IosGL.java b/jme3-ios/src/main/java/com/jme3/renderer/ios/IosGL.java index d3276972d..a9398f159 100644 --- a/jme3-ios/src/main/java/com/jme3/renderer/ios/IosGL.java +++ b/jme3-ios/src/main/java/com/jme3/renderer/ios/IosGL.java @@ -34,6 +34,7 @@ package com.jme3.renderer.ios; import com.jme3.renderer.RendererException; import com.jme3.renderer.opengl.GL; import com.jme3.renderer.opengl.GLExt; +import com.jme3.renderer.opengl.GLFbo; import java.nio.Buffer; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; @@ -46,10 +47,13 @@ import java.nio.ShortBuffer; * * @author Kirill Vainer */ -public class IosGL implements GL, GLExt { +public class IosGL implements GL, GLExt, GLFbo { private final int[] temp_array = new int[16]; + public void resetStats() { + } + private static int getLimitBytes(ByteBuffer buffer) { checkLimit(buffer); return buffer.limit(); @@ -90,7 +94,9 @@ public class IosGL implements GL, GLExt { if (buffer.remaining() < n) { throw new BufferOverflowException(); } + int pos = buffer.position(); buffer.put(array, 0, n); + buffer.position(pos); } private static void checkLimit(Buffer buffer) { diff --git a/jme3-ios/src/main/java/com/jme3/renderer/ios/TextureUtil.java b/jme3-ios/src/main/java/com/jme3/renderer/ios/TextureUtil.java deleted file mode 100644 index d11308c2a..000000000 --- a/jme3-ios/src/main/java/com/jme3/renderer/ios/TextureUtil.java +++ /dev/null @@ -1,576 +0,0 @@ -package com.jme3.renderer.ios; - -//import android.graphics.Bitmap; -//import android.opengl.ETC1; -//import android.opengl.ETC1Util.ETC1Texture; -//import android.opengl.JmeIosGLES; -//import android.opengl.GLUtils; -//import com.jme3.asset.AndroidImageInfo; -import com.jme3.renderer.ios.JmeIosGLES; -import com.jme3.math.FastMath; -import com.jme3.renderer.RendererException; -import com.jme3.texture.Image; -import com.jme3.texture.Image.Format; -import com.jme3.util.BufferUtils; -import java.nio.ByteBuffer; -import java.util.logging.Level; -import java.util.logging.Logger; - -public class TextureUtil { - - private static final Logger logger = Logger.getLogger(TextureUtil.class.getName()); - //TODO Make this configurable through appSettings - public static boolean ENABLE_COMPRESSION = true; - private static boolean NPOT = false; - private static boolean ETC1support = false; - private static boolean DXT1 = false; - private static boolean PVRTC = false; - private static boolean DEPTH24_STENCIL8 = false; - private static boolean DEPTH_TEXTURE = false; - private static boolean RGBA8 = false; - - // Same constant used by both GL_ARM_rgba8 and GL_OES_rgb8_rgba8. - private static final int GL_RGBA8 = 0x8058; - - private static final int GL_DXT1 = 0x83F0; - private static final int GL_DXT1A = 0x83F1; - - private static final int GL_DEPTH_STENCIL_OES = 0x84F9; - private static final int GL_UNSIGNED_INT_24_8_OES = 0x84FA; - private static final int GL_DEPTH24_STENCIL8_OES = 0x88F0; - - public static void loadTextureFeatures(String extensionString) { - ETC1support = extensionString.contains("GL_OES_compressed_ETC1_RGB8_texture"); - DEPTH24_STENCIL8 = extensionString.contains("GL_OES_packed_depth_stencil"); - NPOT = extensionString.contains("GL_IMG_texture_npot") - || extensionString.contains("GL_OES_texture_npot") - || extensionString.contains("GL_NV_texture_npot_2D_mipmap"); - - PVRTC = extensionString.contains("GL_IMG_texture_compression_pvrtc"); - - DXT1 = extensionString.contains("GL_EXT_texture_compression_dxt1"); - DEPTH_TEXTURE = extensionString.contains("GL_OES_depth_texture"); - - RGBA8 = extensionString.contains("GL_ARM_rgba8") || - extensionString.contains("GL_OES_rgb8_rgba8"); - - logger.log(Level.FINE, "Supports ETC1? {0}", ETC1support); - logger.log(Level.FINE, "Supports DEPTH24_STENCIL8? {0}", DEPTH24_STENCIL8); - logger.log(Level.FINE, "Supports NPOT? {0}", NPOT); - logger.log(Level.FINE, "Supports PVRTC? {0}", PVRTC); - logger.log(Level.FINE, "Supports DXT1? {0}", DXT1); - logger.log(Level.FINE, "Supports DEPTH_TEXTURE? {0}", DEPTH_TEXTURE); - logger.log(Level.FINE, "Supports RGBA8? {0}", RGBA8); - } - - /* - private static void buildMipmap(Bitmap bitmap, boolean compress) { - int level = 0; - int height = bitmap.getHeight(); - int width = bitmap.getWidth(); - - logger.log(Level.FINEST, " - Generating mipmaps for bitmap using SOFTWARE"); - - JmeIosGLES.glPixelStorei(JmeIosGLES.GL_UNPACK_ALIGNMENT, 1); - - while (height >= 1 || width >= 1) { - //First of all, generate the texture from our bitmap and set it to the according level - if (compress) { - logger.log(Level.FINEST, " - Uploading LOD level {0} ({1}x{2}) with compression.", new Object[]{level, width, height}); - uploadBitmapAsCompressed(JmeIosGLES.GL_TEXTURE_2D, level, bitmap, false, 0, 0); - } else { - logger.log(Level.FINEST, " - Uploading LOD level {0} ({1}x{2}) directly.", new Object[]{level, width, height}); - GLUtils.texImage2D(JmeIosGLES.GL_TEXTURE_2D, level, bitmap, 0); - } - - if (height == 1 || width == 1) { - break; - } - - //Increase the mipmap level - height /= 2; - width /= 2; - Bitmap bitmap2 = Bitmap.createScaledBitmap(bitmap, width, height, true); - - // Recycle any bitmaps created as a result of scaling the bitmap. - // Do not recycle the original image (mipmap level 0) - if (level != 0) { - bitmap.recycle(); - } - - bitmap = bitmap2; - - level++; - } - } - - private static void uploadBitmapAsCompressed(int target, int level, Bitmap bitmap, boolean subTexture, int x, int y) { - if (bitmap.hasAlpha()) { - logger.log(Level.FINEST, " - Uploading bitmap directly. Cannot compress as alpha present."); - if (subTexture) { - GLUtils.texSubImage2D(target, level, x, y, bitmap); - JmeIosGLES.checkGLError(); - } else { - GLUtils.texImage2D(target, level, bitmap, 0); - JmeIosGLES.checkGLError(); - } - } else { - // Convert to RGB565 - int bytesPerPixel = 2; - Bitmap rgb565 = bitmap.copy(Bitmap.Config.RGB_565, true); - - // Put texture data into ByteBuffer - ByteBuffer inputImage = BufferUtils.createByteBuffer(bitmap.getRowBytes() * bitmap.getHeight()); - rgb565.copyPixelsToBuffer(inputImage); - inputImage.position(0); - - // Delete the copied RGB565 image - rgb565.recycle(); - - // Encode the image into the output bytebuffer - int encodedImageSize = ETC1.getEncodedDataSize(bitmap.getWidth(), bitmap.getHeight()); - ByteBuffer compressedImage = BufferUtils.createByteBuffer(encodedImageSize); - ETC1.encodeImage(inputImage, bitmap.getWidth(), - bitmap.getHeight(), - bytesPerPixel, - bytesPerPixel * bitmap.getWidth(), - compressedImage); - - // Delete the input image buffer - BufferUtils.destroyDirectBuffer(inputImage); - - // Create an ETC1Texture from the compressed image data - ETC1Texture etc1tex = new ETC1Texture(bitmap.getWidth(), bitmap.getHeight(), compressedImage); - - // Upload the ETC1Texture - if (bytesPerPixel == 2) { - int oldSize = (bitmap.getRowBytes() * bitmap.getHeight()); - int newSize = compressedImage.capacity(); - logger.log(Level.FINEST, " - Uploading compressed image to GL, oldSize = {0}, newSize = {1}, ratio = {2}", new Object[]{oldSize, newSize, (float) oldSize / newSize}); - if (subTexture) { - JmeIosGLES.glCompressedTexSubImage2D(target, - level, - x, y, - bitmap.getWidth(), - bitmap.getHeight(), - ETC1.ETC1_RGB8_OES, - etc1tex.getData().capacity(), - etc1tex.getData()); - - JmeIosGLES.checkGLError(); - } else { - JmeIosGLES.glCompressedTexImage2D(target, - level, - ETC1.ETC1_RGB8_OES, - bitmap.getWidth(), - bitmap.getHeight(), - 0, - etc1tex.getData().capacity(), - etc1tex.getData()); - - JmeIosGLES.checkGLError(); - } - -// ETC1Util.loadTexture(target, level, 0, JmeIosGLES.GL_RGB, -// JmeIosGLES.GL_UNSIGNED_SHORT_5_6_5, etc1Texture); -// } else if (bytesPerPixel == 3) { -// ETC1Util.loadTexture(target, level, 0, JmeIosGLES.GL_RGB, -// JmeIosGLES.GL_UNSIGNED_BYTE, etc1Texture); - } - - BufferUtils.destroyDirectBuffer(compressedImage); - } - } - - /** - * uploadTextureBitmap uploads a native android bitmap - */ - /* - public static void uploadTextureBitmap(final int target, Bitmap bitmap, boolean needMips) { - uploadTextureBitmap(target, bitmap, needMips, false, 0, 0); - } - - /** - * uploadTextureBitmap uploads a native android bitmap - */ - /* - public static void uploadTextureBitmap(final int target, Bitmap bitmap, boolean needMips, boolean subTexture, int x, int y) { - boolean recycleBitmap = false; - //TODO, maybe this should raise an exception when NPOT is not supported - - boolean willCompress = ENABLE_COMPRESSION && ETC1support && !bitmap.hasAlpha(); - if (needMips && willCompress) { - // Image is compressed and mipmaps are desired, generate them - // using software. - buildMipmap(bitmap, willCompress); - } else { - if (willCompress) { - // Image is compressed but mipmaps are not desired, upload directly. - logger.log(Level.FINEST, " - Uploading compressed bitmap. Mipmaps are not generated."); - uploadBitmapAsCompressed(target, 0, bitmap, subTexture, x, y); - - } else { - // Image is not compressed, mipmaps may or may not be desired. - logger.log(Level.FINEST, " - Uploading bitmap directly.{0}", - (needMips - ? " Mipmaps will be generated in HARDWARE" - : " Mipmaps are not generated.")); - if (subTexture) { - System.err.println("x : " + x + " y :" + y + " , " + bitmap.getWidth() + "/" + bitmap.getHeight()); - GLUtils.texSubImage2D(target, 0, x, y, bitmap); - JmeIosGLES.checkGLError(); - } else { - GLUtils.texImage2D(target, 0, bitmap, 0); - JmeIosGLES.checkGLError(); - } - - if (needMips) { - // No pregenerated mips available, - // generate from base level if required - JmeIosGLES.glGenerateMipmap(target); - JmeIosGLES.checkGLError(); - } - } - } - - if (recycleBitmap) { - bitmap.recycle(); - } - } - */ - - public static void uploadTextureAny(Image img, int target, int index, boolean needMips) { - /* - if (img.getEfficentData() instanceof AndroidImageInfo) { - logger.log(Level.FINEST, " === Uploading image {0}. Using BITMAP PATH === ", img); - // If image was loaded from asset manager, use fast path - AndroidImageInfo imageInfo = (AndroidImageInfo) img.getEfficentData(); - uploadTextureBitmap(target, imageInfo.getBitmap(), needMips); - } else { - */ - logger.log(Level.FINEST, " === Uploading image {0}. Using BUFFER PATH === ", img); - boolean wantGeneratedMips = needMips && !img.hasMipmaps(); - if (wantGeneratedMips && img.getFormat().isCompressed()) { - logger.log(Level.WARNING, "Generating mipmaps is only" - + " supported for Bitmap based or non-compressed images!"); - } - - // Upload using slower path - logger.log(Level.FINEST, " - Uploading bitmap directly.{0}", - (wantGeneratedMips - ? " Mipmaps will be generated in HARDWARE" - : " Mipmaps are not generated.")); - - uploadTexture(img, target, index); - - // Image was uploaded using slower path, since it is not compressed, - // then compress it - if (wantGeneratedMips) { - // No pregenerated mips available, - // generate from base level if required - JmeIosGLES.glGenerateMipmap(target); - JmeIosGLES.checkGLError(); - } - //} - } - - private static void unsupportedFormat(Format fmt) { - throw new UnsupportedOperationException("The image format '" + fmt + "' is unsupported by the video hardware."); - } - - public static IosGLImageFormat getImageFormat(Format fmt) throws UnsupportedOperationException { - IosGLImageFormat imageFormat = new IosGLImageFormat(); - switch (fmt) { - case Depth32: - case Depth32F: - throw new UnsupportedOperationException("The image format '" - + fmt + "' is not supported by OpenGL ES 2.0 specification."); - case Alpha8: - imageFormat.format = JmeIosGLES.GL_ALPHA; - imageFormat.dataType = JmeIosGLES.GL_UNSIGNED_BYTE; - if (RGBA8) { - imageFormat.renderBufferStorageFormat = GL_RGBA8; - } else { - // Highest precision alpha supported by vanilla OGLES2 - imageFormat.renderBufferStorageFormat = JmeIosGLES.GL_RGBA4; - } - break; - case Luminance8: - imageFormat.format = JmeIosGLES.GL_LUMINANCE; - imageFormat.dataType = JmeIosGLES.GL_UNSIGNED_BYTE; - if (RGBA8) { - imageFormat.renderBufferStorageFormat = GL_RGBA8; - } else { - // Highest precision luminance supported by vanilla OGLES2 - imageFormat.renderBufferStorageFormat = JmeIosGLES.GL_RGB565; - } - break; - case Luminance8Alpha8: - imageFormat.format = JmeIosGLES.GL_LUMINANCE_ALPHA; - imageFormat.dataType = JmeIosGLES.GL_UNSIGNED_BYTE; - if (RGBA8) { - imageFormat.renderBufferStorageFormat = GL_RGBA8; - } else { - imageFormat.renderBufferStorageFormat = JmeIosGLES.GL_RGBA4; - } - break; - case RGB565: - imageFormat.format = JmeIosGLES.GL_RGB; - imageFormat.dataType = JmeIosGLES.GL_UNSIGNED_SHORT_5_6_5; - imageFormat.renderBufferStorageFormat = JmeIosGLES.GL_RGB565; - break; - case RGB5A1: - imageFormat.format = JmeIosGLES.GL_RGBA; - imageFormat.dataType = JmeIosGLES.GL_UNSIGNED_SHORT_5_5_5_1; - imageFormat.renderBufferStorageFormat = JmeIosGLES.GL_RGB5_A1; - break; - case RGB8: - imageFormat.format = JmeIosGLES.GL_RGB; - imageFormat.dataType = JmeIosGLES.GL_UNSIGNED_BYTE; - if (RGBA8) { - imageFormat.renderBufferStorageFormat = GL_RGBA8; - } else { - // Fallback: Use RGB565 if RGBA8 is not available. - imageFormat.renderBufferStorageFormat = JmeIosGLES.GL_RGB565; - } - break; - case BGR8: - imageFormat.format = JmeIosGLES.GL_RGB; - imageFormat.dataType = JmeIosGLES.GL_UNSIGNED_BYTE; - if (RGBA8) { - imageFormat.renderBufferStorageFormat = GL_RGBA8; - } else { - imageFormat.renderBufferStorageFormat = JmeIosGLES.GL_RGB565; - } - break; - case RGBA8: - imageFormat.format = JmeIosGLES.GL_RGBA; - imageFormat.dataType = JmeIosGLES.GL_UNSIGNED_BYTE; - if (RGBA8) { - imageFormat.renderBufferStorageFormat = GL_RGBA8; - } else { - imageFormat.renderBufferStorageFormat = JmeIosGLES.GL_RGBA4; - } - break; - case Depth: - case Depth16: - if (!DEPTH_TEXTURE) { - unsupportedFormat(fmt); - } - imageFormat.format = JmeIosGLES.GL_DEPTH_COMPONENT; - imageFormat.dataType = JmeIosGLES.GL_UNSIGNED_SHORT; - imageFormat.renderBufferStorageFormat = JmeIosGLES.GL_DEPTH_COMPONENT16; - break; - case Depth24: - case Depth24Stencil8: - if (!DEPTH_TEXTURE) { - unsupportedFormat(fmt); - } - if (DEPTH24_STENCIL8) { - // NEW: True Depth24 + Stencil8 format. - imageFormat.format = GL_DEPTH_STENCIL_OES; - imageFormat.dataType = GL_UNSIGNED_INT_24_8_OES; - imageFormat.renderBufferStorageFormat = GL_DEPTH24_STENCIL8_OES; - } else { - // Vanilla OGLES2, only Depth16 available. - imageFormat.format = JmeIosGLES.GL_DEPTH_COMPONENT; - imageFormat.dataType = JmeIosGLES.GL_UNSIGNED_SHORT; - imageFormat.renderBufferStorageFormat = JmeIosGLES.GL_DEPTH_COMPONENT16; - } - break; - case DXT1: - if (!DXT1) { - unsupportedFormat(fmt); - } - imageFormat.format = GL_DXT1; - imageFormat.dataType = JmeIosGLES.GL_UNSIGNED_BYTE; - imageFormat.compress = true; - break; - case DXT1A: - if (!DXT1) { - unsupportedFormat(fmt); - } - imageFormat.format = GL_DXT1A; - imageFormat.dataType = JmeIosGLES.GL_UNSIGNED_BYTE; - imageFormat.compress = true; - break; - default: - throw new UnsupportedOperationException("Unrecognized format: " + fmt); - } - return imageFormat; - } - - public static class IosGLImageFormat { - - boolean compress = false; - int format = -1; - int renderBufferStorageFormat = -1; - int dataType = -1; - } - - private static void uploadTexture(Image img, - int target, - int index) { - - /* - if (img.getEfficentData() instanceof AndroidImageInfo) { - throw new RendererException("This image uses efficient data. " - + "Use uploadTextureBitmap instead."); - } - */ - - // Otherwise upload image directly. - // Prefer to only use power of 2 textures here to avoid errors. - Image.Format fmt = img.getFormat(); - ByteBuffer data; - if (index >= 0 || img.getData() != null && img.getData().size() > 0) { - data = img.getData(index); - } else { - data = null; - } - - int width = img.getWidth(); - int height = img.getHeight(); - - if (!NPOT && img.isNPOT()) { - // Check if texture is POT - throw new RendererException("Non-power-of-2 textures " - + "are not supported by the video hardware " - + "and no scaling path available for image: " + img); - } - IosGLImageFormat imageFormat = getImageFormat(fmt); - - if (data != null) { - JmeIosGLES.glPixelStorei(JmeIosGLES.GL_UNPACK_ALIGNMENT, 1); - JmeIosGLES.checkGLError(); - } - - int[] mipSizes = img.getMipMapSizes(); - int pos = 0; - if (mipSizes == null) { - if (data != null) { - mipSizes = new int[]{data.capacity()}; - } else { - mipSizes = new int[]{width * height * fmt.getBitsPerPixel() / 8}; - } - } - - for (int i = 0; i < mipSizes.length; i++) { - int mipWidth = Math.max(1, width >> i); - int mipHeight = Math.max(1, height >> i); - - if (data != null) { - data.position(pos); - data.limit(pos + mipSizes[i]); - } - - if (imageFormat.compress && data != null) { - JmeIosGLES.glCompressedTexImage2D(target, - i, - imageFormat.format, - mipWidth, - mipHeight, - 0, - data.remaining(), - data); - } else { - JmeIosGLES.glTexImage2D(target, - i, - imageFormat.format, - mipWidth, - mipHeight, - 0, - imageFormat.format, - imageFormat.dataType, - data); - } - JmeIosGLES.checkGLError(); - - pos += mipSizes[i]; - } - } - - /** - * Update the texture currently bound to target at with data from the given - * Image at position x and y. The parameter index is used as the zoffset in - * case a 3d texture or texture 2d array is being updated. - * - * @param image Image with the source data (this data will be put into the - * texture) - * @param target the target texture - * @param index the mipmap level to update - * @param x the x position where to put the image in the texture - * @param y the y position where to put the image in the texture - */ - public static void uploadSubTexture( - Image img, - int target, - int index, - int x, - int y) { - //TODO: - /* - if (img.getEfficentData() instanceof AndroidImageInfo) { - AndroidImageInfo imageInfo = (AndroidImageInfo) img.getEfficentData(); - uploadTextureBitmap(target, imageInfo.getBitmap(), true, true, x, y); - return; - } - */ - - // Otherwise upload image directly. - // Prefer to only use power of 2 textures here to avoid errors. - Image.Format fmt = img.getFormat(); - ByteBuffer data; - if (index >= 0 || img.getData() != null && img.getData().size() > 0) { - data = img.getData(index); - } else { - data = null; - } - - int width = img.getWidth(); - int height = img.getHeight(); - - if (!NPOT && img.isNPOT()) { - // Check if texture is POT - throw new RendererException("Non-power-of-2 textures " - + "are not supported by the video hardware " - + "and no scaling path available for image: " + img); - } - IosGLImageFormat imageFormat = getImageFormat(fmt); - - if (data != null) { - JmeIosGLES.glPixelStorei(JmeIosGLES.GL_UNPACK_ALIGNMENT, 1); - JmeIosGLES.checkGLError(); - } - - int[] mipSizes = img.getMipMapSizes(); - int pos = 0; - if (mipSizes == null) { - if (data != null) { - mipSizes = new int[]{data.capacity()}; - } else { - mipSizes = new int[]{width * height * fmt.getBitsPerPixel() / 8}; - } - } - - for (int i = 0; i < mipSizes.length; i++) { - int mipWidth = Math.max(1, width >> i); - int mipHeight = Math.max(1, height >> i); - - if (data != null) { - data.position(pos); - data.limit(pos + mipSizes[i]); - } - - if (imageFormat.compress && data != null) { - JmeIosGLES.glCompressedTexSubImage2D(target, i, x, y, mipWidth, mipHeight, imageFormat.format, data.remaining(), data); - JmeIosGLES.checkGLError(); - } else { - JmeIosGLES.glTexSubImage2D(target, i, x, y, mipWidth, mipHeight, imageFormat.format, imageFormat.dataType, data); - JmeIosGLES.checkGLError(); - } - - pos += mipSizes[i]; - } - } -} diff --git a/jme3-ios/src/main/java/com/jme3/system/ios/IGLESContext.java b/jme3-ios/src/main/java/com/jme3/system/ios/IGLESContext.java index 7feaeae5b..2d046550e 100644 --- a/jme3-ios/src/main/java/com/jme3/system/ios/IGLESContext.java +++ b/jme3-ios/src/main/java/com/jme3/system/ios/IGLESContext.java @@ -40,6 +40,7 @@ import com.jme3.renderer.ios.IosGL; import com.jme3.renderer.opengl.GL; import com.jme3.renderer.opengl.GLDebugES; import com.jme3.renderer.opengl.GLExt; +import com.jme3.renderer.opengl.GLFbo; import com.jme3.renderer.opengl.GLRenderer; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; @@ -158,11 +159,11 @@ public class IGLESContext implements JmeContext { GLExt glext = (GLExt) gl; // if (settings.getBoolean("GraphicsDebug")) { - gl = new GLDebugES(gl, glext); + gl = new GLDebugES(gl, glext, (GLFbo) glext); glext = (GLExt) gl; // } - renderer = new GLRenderer(gl, glext); + renderer = new GLRenderer(gl, glext, (GLFbo) glext); renderer.initialize(); input = new IosInputHandler(); diff --git a/jme3-ios/src/main/java/com/jme3/system/ios/IosImageLoader.java b/jme3-ios/src/main/java/com/jme3/system/ios/IosImageLoader.java index 4ec649086..e47de3a50 100644 --- a/jme3-ios/src/main/java/com/jme3/system/ios/IosImageLoader.java +++ b/jme3-ios/src/main/java/com/jme3/system/ios/IosImageLoader.java @@ -33,6 +33,7 @@ package com.jme3.system.ios; import com.jme3.asset.AssetInfo; import com.jme3.asset.AssetLoader; +import com.jme3.asset.TextureKey; import com.jme3.texture.Image; import com.jme3.texture.Image.Format; import java.io.IOException; @@ -45,14 +46,16 @@ import java.io.InputStream; public class IosImageLoader implements AssetLoader { public Object load(AssetInfo info) throws IOException { - InputStream in = info.openStream(); + boolean flip = ((TextureKey) info.getKey()).isFlipY(); Image img = null; + InputStream in = null; try { - img = loadImageData(Image.Format.RGBA8, in); - } catch (Exception e) { - e.printStackTrace(); + in = info.openStream(); + img = loadImageData(Format.RGBA8, flip, in); } finally { - in.close(); + if (in != null) { + in.close(); + } } return img; } @@ -64,5 +67,5 @@ public class IosImageLoader implements AssetLoader { * @param inputStream the InputStream to load the image data from * @return the loaded Image */ - private static native Image loadImageData(Format format, InputStream inputStream); + private static native Image loadImageData(Format format, boolean flipY, InputStream inputStream); } diff --git a/jme3-ios/src/main/java/com/jme3/system/ios/JmeIosSystem.java b/jme3-ios/src/main/java/com/jme3/system/ios/JmeIosSystem.java index 904db71cf..d29f76f62 100644 --- a/jme3-ios/src/main/java/com/jme3/system/ios/JmeIosSystem.java +++ b/jme3-ios/src/main/java/com/jme3/system/ios/JmeIosSystem.java @@ -36,6 +36,14 @@ import com.jme3.system.AppSettings; import com.jme3.system.JmeContext; import com.jme3.system.JmeSystemDelegate; import com.jme3.system.NullContext; +import com.jme3.audio.AudioRenderer; +import com.jme3.audio.ios.IosAL; +import com.jme3.audio.ios.IosALC; +//import com.jme3.audio.ios.IosEFX; +import com.jme3.audio.openal.AL; +import com.jme3.audio.openal.ALAudioRenderer; +import com.jme3.audio.openal.ALC; +import com.jme3.audio.openal.EFX; import java.io.IOException; import java.io.OutputStream; import java.net.URL; @@ -89,8 +97,11 @@ public class JmeIosSystem extends JmeSystemDelegate { @Override public AudioRenderer newAudioRenderer(AppSettings settings) { - return null; - } + ALC alc = new IosALC(); + AL al = new IosAL(); + //EFX efx = new IosEFX(); + return new ALAudioRenderer(al, alc, null); + } @Override public void initialize(AppSettings settings) { diff --git a/jme3-ios/src/main/resources/com/jme3/asset/IOS.cfg b/jme3-ios/src/main/resources/com/jme3/asset/IOS.cfg new file mode 100644 index 000000000..e9d79a459 --- /dev/null +++ b/jme3-ios/src/main/resources/com/jme3/asset/IOS.cfg @@ -0,0 +1,10 @@ +INCLUDE com/jme3/asset/General.cfg + +# IOS specific loaders +LOADER com.jme3.system.ios.IosImageLoader : jpg, bmp, gif, png, jpeg +LOADER com.jme3.audio.plugins.OGGLoader : ogg +LOADER com.jme3.material.plugins.J3MLoader : j3m +LOADER com.jme3.material.plugins.J3MLoader : j3md +LOADER com.jme3.shader.plugins.GLSLLoader : vert, frag, glsl, glsllib +LOADER com.jme3.export.binary.BinaryImporter : j3o +LOADER com.jme3.font.plugins.BitmapFontLoader : fnt diff --git a/jme3-jbullet/src/main/java/com/jme3/bullet/PhysicsSpace.java b/jme3-jbullet/src/main/java/com/jme3/bullet/PhysicsSpace.java index dc61e6c6c..016440bf0 100644 --- a/jme3-jbullet/src/main/java/com/jme3/bullet/PhysicsSpace.java +++ b/jme3-jbullet/src/main/java/com/jme3/bullet/PhysicsSpace.java @@ -142,7 +142,6 @@ public class PhysicsSpace { private javax.vecmath.Vector3f rayVec2 = new javax.vecmath.Vector3f(); private com.bulletphysics.linearmath.Transform sweepTrans1 = new com.bulletphysics.linearmath.Transform(new javax.vecmath.Matrix3f()); private com.bulletphysics.linearmath.Transform sweepTrans2 = new com.bulletphysics.linearmath.Transform(new javax.vecmath.Matrix3f()); - private AssetManager debugManager; /** * Get the current PhysicsSpace running on this thread
    @@ -362,7 +361,7 @@ public class PhysicsSpace { eventFactory.recycle(physicsCollisionEvent); } } - + public static Future enqueueOnThisThread(Callable callable) { AppTask task = new AppTask(callable); System.out.println("created apptask"); @@ -620,7 +619,7 @@ public class PhysicsSpace { physicsJoints.remove(joint.getObjectId()); dynamicsWorld.removeConstraint(joint.getObjectId()); } - + public Collection getRigidBodyList(){ return new LinkedList(physicsBodies.values()); } @@ -628,19 +627,19 @@ public class PhysicsSpace { public Collection getGhostObjectList(){ return new LinkedList(physicsGhostObjects.values()); } - + public Collection getCharacterList(){ return new LinkedList(physicsCharacters.values()); } - + public Collection getJointList(){ return new LinkedList(physicsJoints.values()); } - + public Collection getVehicleList(){ return new LinkedList(physicsVehicles.values()); } - + /** * Sets the gravity of the PhysicsSpace, set before adding physics objects! * @param gravity @@ -658,7 +657,7 @@ public class PhysicsSpace { dynamicsWorld.getGravity(tempVec); return Converter.convert(tempVec, gravity); } - + /** * applies gravity value to all objects */ @@ -876,30 +875,22 @@ public class PhysicsSpace { public void setWorldMax(Vector3f worldMax) { this.worldMax.set(worldMax); } - - /** - * Enable debug display for physics. - * - * @deprecated in favor of BulletDebugAppState, use - * BulletAppState.setDebugEnabled(boolean) to add automatically - * @param manager AssetManager to use to create debug materials - */ - @Deprecated - public void enableDebug(AssetManager manager) { - debugManager = manager; - } - + /** - * Disable debug display + * Set the number of iterations used by the contact solver. + * + * The default is 10. Use 4 for low quality, 20 for high quality. + * + * @param numIterations The number of iterations used by the contact & constraint solver. */ - public void disableDebug() { - debugManager = null; + public void setSolverNumIterations(int numIterations) { + dynamicsWorld.getSolverInfo().numIterations = numIterations; } - public AssetManager getDebugManager() { - return debugManager; + public int getSolverNumIterations() { + return dynamicsWorld.getSolverInfo().numIterations; } - + /** * interface with Broadphase types */ diff --git a/jme3-jogl/build.gradle b/jme3-jogl/build.gradle index 135656ee6..e82139729 100644 --- a/jme3-jogl/build.gradle +++ b/jme3-jogl/build.gradle @@ -5,7 +5,7 @@ if (!hasProperty('mainClass')) { dependencies { compile project(':jme3-core') compile project(':jme3-desktop') - compile 'org.jogamp.gluegen:gluegen-rt-main:2.2.0' - compile 'org.jogamp.jogl:jogl-all-main:2.2.0' - compile 'org.jogamp.joal:joal-main:2.2.0' + compile 'org.jogamp.gluegen:gluegen-rt-main:2.3.1' + compile 'org.jogamp.jogl:jogl-all-main:2.3.1' + compile 'org.jogamp.joal:joal-main:2.3.1' } diff --git a/jme3-jogl/src/main/java/com/jme3/input/jogl/NewtMouseInput.java b/jme3-jogl/src/main/java/com/jme3/input/jogl/NewtMouseInput.java index d50017ccc..773f62b8a 100644 --- a/jme3-jogl/src/main/java/com/jme3/input/jogl/NewtMouseInput.java +++ b/jme3-jogl/src/main/java/com/jme3/input/jogl/NewtMouseInput.java @@ -45,11 +45,11 @@ import com.jogamp.newt.opengl.GLWindow; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.logging.Logger; -import javax.media.nativewindow.util.Dimension; -import javax.media.nativewindow.util.DimensionImmutable; -import javax.media.nativewindow.util.PixelFormat; -import javax.media.nativewindow.util.PixelRectangle; -import javax.media.nativewindow.util.Point; +import com.jogamp.nativewindow.util.Dimension; +import com.jogamp.nativewindow.util.DimensionImmutable; +import com.jogamp.nativewindow.util.PixelFormat; +import com.jogamp.nativewindow.util.PixelRectangle; +import com.jogamp.nativewindow.util.Point; public class NewtMouseInput implements MouseInput, MouseListener { diff --git a/jme3-jogl/src/main/java/com/jme3/renderer/jogl/JoglRenderer.java b/jme3-jogl/src/main/java/com/jme3/renderer/jogl/JoglRenderer.java index 85e5c7102..111719265 100644 --- a/jme3-jogl/src/main/java/com/jme3/renderer/jogl/JoglRenderer.java +++ b/jme3-jogl/src/main/java/com/jme3/renderer/jogl/JoglRenderer.java @@ -70,15 +70,15 @@ import java.util.EnumSet; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; -import javax.media.nativewindow.NativeWindowFactory; -import javax.media.opengl.GL; -import javax.media.opengl.GL2; -import javax.media.opengl.GL2ES1; -import javax.media.opengl.GL2ES2; -import javax.media.opengl.GL2ES3; -import javax.media.opengl.GL2GL3; -import javax.media.opengl.GL3; -import javax.media.opengl.GLContext; +import com.jogamp.nativewindow.NativeWindowFactory; +import com.jogamp.opengl.GL; +import com.jogamp.opengl.GL2; +import com.jogamp.opengl.GL2ES1; +import com.jogamp.opengl.GL2ES2; +import com.jogamp.opengl.GL2ES3; +import com.jogamp.opengl.GL2GL3; +import com.jogamp.opengl.GL3; +import com.jogamp.opengl.GLContext; import jme3tools.converters.MipMapGenerator; import jme3tools.shader.ShaderDebug; @@ -1800,7 +1800,7 @@ public class JoglRenderer implements Renderer { if (samples > 1) { return GL3.GL_TEXTURE_2D_MULTISAMPLE_ARRAY; } else { - return GL.GL_TEXTURE_2D_ARRAY; + return GL2ES3.GL_TEXTURE_2D_ARRAY; } case ThreeDimensional: return GL2ES2.GL_TEXTURE_3D; @@ -2014,7 +2014,7 @@ public class JoglRenderer implements Renderer { for (int i = 0; i < 6; i++) { TextureUtil.uploadTexture(img, GL.GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, i, 0, linearizeSrgbImages); } - } else if (target == GL.GL_TEXTURE_2D_ARRAY) { + } else if (target == GL2ES3.GL_TEXTURE_2D_ARRAY) { if (!caps.contains(Caps.TextureArray)) { throw new RendererException("Texture arrays not supported by graphics hardware"); } diff --git a/jme3-jogl/src/main/java/com/jme3/renderer/jogl/TextureUtil.java b/jme3-jogl/src/main/java/com/jme3/renderer/jogl/TextureUtil.java index 9bdc0ca2d..8f3c5b156 100644 --- a/jme3-jogl/src/main/java/com/jme3/renderer/jogl/TextureUtil.java +++ b/jme3-jogl/src/main/java/com/jme3/renderer/jogl/TextureUtil.java @@ -36,14 +36,17 @@ import com.jme3.renderer.RendererException; import com.jme3.texture.Image; import com.jme3.texture.Image.Format; import com.jme3.texture.image.ColorSpace; + import java.nio.ByteBuffer; import java.util.logging.Level; import java.util.logging.Logger; -import javax.media.opengl.GL; -import javax.media.opengl.GL2; -import javax.media.opengl.GL2ES2; -import javax.media.opengl.GL2GL3; -import javax.media.opengl.GLContext; + +import com.jogamp.opengl.GL; +import com.jogamp.opengl.GL2; +import com.jogamp.opengl.GL2ES2; +import com.jogamp.opengl.GL2ES3; +import com.jogamp.opengl.GL2GL3; +import com.jogamp.opengl.GLContext; public class TextureUtil { @@ -124,9 +127,9 @@ public class TextureUtil { setFormat(Format.RGB32F, GL.GL_RGB32F, GL.GL_RGB, GL.GL_FLOAT, false); // Special RGB formats - setFormat(Format.RGB111110F, GL.GL_R11F_G11F_B10F, GL.GL_RGB, GL.GL_UNSIGNED_INT_10F_11F_11F_REV, false); + setFormat(Format.RGB111110F, GL2ES3.GL_R11F_G11F_B10F, GL.GL_RGB, GL.GL_UNSIGNED_INT_10F_11F_11F_REV, false); setFormat(Format.RGB9E5, GL2GL3.GL_RGB9_E5, GL.GL_RGB, GL2GL3.GL_UNSIGNED_INT_5_9_9_9_REV, false); - setFormat(Format.RGB16F_to_RGB111110F, GL.GL_R11F_G11F_B10F, GL.GL_RGB, GL.GL_HALF_FLOAT, false); + setFormat(Format.RGB16F_to_RGB111110F, GL2ES3.GL_R11F_G11F_B10F, GL.GL_RGB, GL.GL_HALF_FLOAT, false); setFormat(Format.RGB16F_to_RGB9E5, GL2.GL_RGB9_E5, GL.GL_RGB, GL.GL_HALF_FLOAT, false); // RGBA formats @@ -346,7 +349,7 @@ public class TextureUtil { glFmt.format, glFmt.dataType, data); - }else if (target == GL.GL_TEXTURE_2D_ARRAY){ + }else if (target == GL2ES3.GL_TEXTURE_2D_ARRAY){ // prepare data for 2D array // or upload slice if (index == -1){ diff --git a/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglAbstractDisplay.java b/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglAbstractDisplay.java index 8c6ec6e55..a7f7fbfd7 100644 --- a/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglAbstractDisplay.java +++ b/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglAbstractDisplay.java @@ -45,20 +45,20 @@ import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Logger; -import javax.media.opengl.DebugGL2; -import javax.media.opengl.DebugGL3; -import javax.media.opengl.DebugGL3bc; -import javax.media.opengl.DebugGL4; -import javax.media.opengl.DebugGL4bc; -import javax.media.opengl.DebugGLES1; -import javax.media.opengl.DebugGLES2; -import javax.media.opengl.GL; -import javax.media.opengl.GLAutoDrawable; -import javax.media.opengl.GLCapabilities; -import javax.media.opengl.GLEventListener; -import javax.media.opengl.GLProfile; -import javax.media.opengl.GLRunnable; -import javax.media.opengl.awt.GLCanvas; +import com.jogamp.opengl.DebugGL2; +import com.jogamp.opengl.DebugGL3; +import com.jogamp.opengl.DebugGL3bc; +import com.jogamp.opengl.DebugGL4; +import com.jogamp.opengl.DebugGL4bc; +import com.jogamp.opengl.DebugGLES1; +import com.jogamp.opengl.DebugGLES2; +import com.jogamp.opengl.GL; +import com.jogamp.opengl.GLAutoDrawable; +import com.jogamp.opengl.GLCapabilities; +import com.jogamp.opengl.GLEventListener; +import com.jogamp.opengl.GLProfile; +import com.jogamp.opengl.GLRunnable; +import com.jogamp.opengl.awt.GLCanvas; public abstract class JoglAbstractDisplay extends JoglContext implements GLEventListener { diff --git a/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglCanvas.java b/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglCanvas.java index c4e97570e..9a409b85e 100644 --- a/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglCanvas.java +++ b/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglCanvas.java @@ -35,7 +35,7 @@ package com.jme3.system.jogl; import com.jme3.system.JmeCanvasContext; import java.awt.Canvas; import java.util.logging.Logger; -import javax.media.opengl.GLAutoDrawable; +import com.jogamp.opengl.GLAutoDrawable; public class JoglCanvas extends JoglAbstractDisplay implements JmeCanvasContext { diff --git a/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglContext.java b/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglContext.java index eca36d84b..5d687af8d 100644 --- a/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglContext.java +++ b/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglContext.java @@ -47,14 +47,16 @@ import java.nio.IntBuffer; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; -import javax.media.opengl.GL; -import javax.media.opengl.GL2GL3; -import javax.media.opengl.GLContext; +import com.jogamp.opengl.GL; +import com.jogamp.opengl.GL2GL3; +import com.jogamp.opengl.GLContext; public abstract class JoglContext implements JmeContext { private static final Logger logger = Logger.getLogger(JoglContext.class.getName()); + protected static final String THREAD_NAME = "jME3 Main"; + protected AtomicBoolean created = new AtomicBoolean(false); protected AtomicBoolean renderable = new AtomicBoolean(false); protected final Object createdLock = new Object(); diff --git a/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglDisplay.java b/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglDisplay.java index 363ccd096..3bac0ab53 100644 --- a/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglDisplay.java +++ b/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglDisplay.java @@ -45,7 +45,7 @@ import java.lang.reflect.InvocationTargetException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; -import javax.media.opengl.GLAutoDrawable; +import com.jogamp.opengl.GLAutoDrawable; import javax.swing.JFrame; import javax.swing.SwingUtilities; diff --git a/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglNewtAbstractDisplay.java b/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglNewtAbstractDisplay.java index 4899c9c39..cb75d5d37 100644 --- a/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglNewtAbstractDisplay.java +++ b/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglNewtAbstractDisplay.java @@ -44,19 +44,19 @@ import com.jogamp.opengl.util.AnimatorBase; import com.jogamp.opengl.util.FPSAnimator; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Logger; -import javax.media.opengl.DebugGL2; -import javax.media.opengl.DebugGL3; -import javax.media.opengl.DebugGL3bc; -import javax.media.opengl.DebugGL4; -import javax.media.opengl.DebugGL4bc; -import javax.media.opengl.DebugGLES1; -import javax.media.opengl.DebugGLES2; -import javax.media.opengl.GL; -import javax.media.opengl.GLAutoDrawable; -import javax.media.opengl.GLCapabilities; -import javax.media.opengl.GLEventListener; -import javax.media.opengl.GLProfile; -import javax.media.opengl.GLRunnable; +import com.jogamp.opengl.DebugGL2; +import com.jogamp.opengl.DebugGL3; +import com.jogamp.opengl.DebugGL3bc; +import com.jogamp.opengl.DebugGL4; +import com.jogamp.opengl.DebugGL4bc; +import com.jogamp.opengl.DebugGLES1; +import com.jogamp.opengl.DebugGLES2; +import com.jogamp.opengl.GL; +import com.jogamp.opengl.GLAutoDrawable; +import com.jogamp.opengl.GLCapabilities; +import com.jogamp.opengl.GLEventListener; +import com.jogamp.opengl.GLProfile; +import com.jogamp.opengl.GLRunnable; public abstract class JoglNewtAbstractDisplay extends JoglContext implements GLEventListener { diff --git a/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglNewtCanvas.java b/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglNewtCanvas.java index e4f46d8fb..3ed501580 100644 --- a/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglNewtCanvas.java +++ b/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglNewtCanvas.java @@ -35,7 +35,7 @@ package com.jme3.system.jogl; import com.jme3.system.JmeCanvasContext; import com.jogamp.newt.awt.NewtCanvasAWT; import java.util.logging.Logger; -import javax.media.opengl.GLAutoDrawable; +import com.jogamp.opengl.GLAutoDrawable; public class JoglNewtCanvas extends JoglNewtAbstractDisplay implements JmeCanvasContext { diff --git a/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglNewtDisplay.java b/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglNewtDisplay.java index 011002aff..84a99e8d2 100644 --- a/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglNewtDisplay.java +++ b/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglNewtDisplay.java @@ -42,8 +42,8 @@ import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; -import javax.media.nativewindow.util.Dimension; -import javax.media.opengl.GLAutoDrawable; +import com.jogamp.nativewindow.util.Dimension; +import com.jogamp.opengl.GLAutoDrawable; public class JoglNewtDisplay extends JoglNewtAbstractDisplay { diff --git a/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglOffscreenBuffer.java b/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglOffscreenBuffer.java index 505808878..cd2b84f73 100644 --- a/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglOffscreenBuffer.java +++ b/jme3-jogl/src/main/java/com/jme3/system/jogl/JoglOffscreenBuffer.java @@ -41,12 +41,12 @@ import com.jogamp.newt.NewtVersion; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; -import javax.media.opengl.GL; -import javax.media.opengl.GLCapabilities; -import javax.media.opengl.GLContext; -import javax.media.opengl.GLDrawableFactory; -import javax.media.opengl.GLOffscreenAutoDrawable; -import javax.media.opengl.GLProfile; +import com.jogamp.opengl.GL; +import com.jogamp.opengl.GLCapabilities; +import com.jogamp.opengl.GLContext; +import com.jogamp.opengl.GLDrawableFactory; +import com.jogamp.opengl.GLOffscreenAutoDrawable; +import com.jogamp.opengl.GLProfile; public class JoglOffscreenBuffer extends JoglContext implements Runnable { @@ -146,7 +146,7 @@ public class JoglOffscreenBuffer extends JoglContext implements Runnable { return; } - new Thread(this, "JOGL Renderer Thread").start(); + new Thread(this, THREAD_NAME).start(); if (waitFor) { waitFor(true); } diff --git a/jme3-lwjgl/src/main/java/com/jme3/renderer/lwjgl/LwjglGL.java b/jme3-lwjgl/src/main/java/com/jme3/renderer/lwjgl/LwjglGL.java index 82b8ee72b..bf99c84eb 100644 --- a/jme3-lwjgl/src/main/java/com/jme3/renderer/lwjgl/LwjglGL.java +++ b/jme3-lwjgl/src/main/java/com/jme3/renderer/lwjgl/LwjglGL.java @@ -13,7 +13,7 @@ import java.nio.ShortBuffer; import com.jme3.renderer.opengl.GL4; import org.lwjgl.opengl.*; -public class LwjglGL implements GL, GL2, GL3,GL4 { +public class LwjglGL implements GL, GL2, GL3, GL4 { private static void checkLimit(Buffer buffer) { if (buffer == null) { @@ -27,6 +27,9 @@ public class LwjglGL implements GL, GL2, GL3,GL4 { } } + public void resetStats() { + } + public void glActiveTexture(int param1) { GL13.glActiveTexture(param1); } @@ -237,6 +240,10 @@ public class LwjglGL implements GL, GL2, GL3,GL4 { public String glGetString(int param1) { return GL11.glGetString(param1); } + + public String glGetString(int param1, int param2) { + return GL30.glGetStringi(param1, param2); + } public boolean glIsEnabled(int param1) { return GL11.glIsEnabled(param1); @@ -444,4 +451,10 @@ public class LwjglGL implements GL, GL2, GL3,GL4 { public void glPatchParameter(int count) { GL40.glPatchParameteri(GL40.GL_PATCH_VERTICES,count); } + + @Override + public void glDeleteVertexArrays(IntBuffer arrays) { + checkLimit(arrays); + ARBVertexArrayObject.glDeleteVertexArrays(arrays); + } } diff --git a/jme3-lwjgl/src/main/java/com/jme3/renderer/lwjgl/LwjglGLExt.java b/jme3-lwjgl/src/main/java/com/jme3/renderer/lwjgl/LwjglGLExt.java index 89139282a..2c6a63fd7 100644 --- a/jme3-lwjgl/src/main/java/com/jme3/renderer/lwjgl/LwjglGLExt.java +++ b/jme3-lwjgl/src/main/java/com/jme3/renderer/lwjgl/LwjglGLExt.java @@ -7,12 +7,8 @@ import java.nio.FloatBuffer; import java.nio.IntBuffer; import org.lwjgl.opengl.ARBDrawInstanced; import org.lwjgl.opengl.ARBInstancedArrays; -import org.lwjgl.opengl.ARBPixelBufferObject; import org.lwjgl.opengl.ARBSync; import org.lwjgl.opengl.ARBTextureMultisample; -import org.lwjgl.opengl.EXTFramebufferBlit; -import org.lwjgl.opengl.EXTFramebufferMultisample; -import org.lwjgl.opengl.EXTFramebufferObject; import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GLSync; @@ -30,99 +26,51 @@ public class LwjglGLExt implements GLExt { throw new RendererException("Attempting to upload empty buffer (remaining = 0), that's an error"); } } - - public void glBlitFramebufferEXT(int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, int mask, int filter) { - EXTFramebufferBlit.glBlitFramebufferEXT(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); - } + @Override public void glBufferData(int target, IntBuffer data, int usage) { checkLimit(data); GL15.glBufferData(target, data, usage); } + @Override public void glBufferSubData(int target, long offset, IntBuffer data) { checkLimit(data); GL15.glBufferSubData(target, offset, data); } + @Override public void glDrawArraysInstancedARB(int mode, int first, int count, int primcount) { ARBDrawInstanced.glDrawArraysInstancedARB(mode, first, count, primcount); } + @Override public void glDrawBuffers(IntBuffer bufs) { checkLimit(bufs); GL20.glDrawBuffers(bufs); } + @Override public void glDrawElementsInstancedARB(int mode, int indices_count, int type, long indices_buffer_offset, int primcount) { ARBDrawInstanced.glDrawElementsInstancedARB(mode, indices_count, type, indices_buffer_offset, primcount); } + @Override public void glGetMultisample(int pname, int index, FloatBuffer val) { checkLimit(val); ARBTextureMultisample.glGetMultisample(pname, index, val); } - public void glRenderbufferStorageMultisampleEXT(int target, int samples, int internalformat, int width, int height) { - EXTFramebufferMultisample.glRenderbufferStorageMultisampleEXT(target, samples, internalformat, width, height); - } - + @Override public void glTexImage2DMultisample(int target, int samples, int internalformat, int width, int height, boolean fixedsamplelocations) { ARBTextureMultisample.glTexImage2DMultisample(target, samples, internalformat, width, height, fixedsamplelocations); } + @Override public void glVertexAttribDivisorARB(int index, int divisor) { ARBInstancedArrays.glVertexAttribDivisorARB(index, divisor); } - public void glBindFramebufferEXT(int param1, int param2) { - EXTFramebufferObject.glBindFramebufferEXT(param1, param2); - } - - public void glBindRenderbufferEXT(int param1, int param2) { - EXTFramebufferObject.glBindRenderbufferEXT(param1, param2); - } - - public int glCheckFramebufferStatusEXT(int param1) { - return EXTFramebufferObject.glCheckFramebufferStatusEXT(param1); - } - - public void glDeleteFramebuffersEXT(IntBuffer param1) { - checkLimit(param1); - EXTFramebufferObject.glDeleteFramebuffersEXT(param1); - } - - public void glDeleteRenderbuffersEXT(IntBuffer param1) { - checkLimit(param1); - EXTFramebufferObject.glDeleteRenderbuffersEXT(param1); - } - - public void glFramebufferRenderbufferEXT(int param1, int param2, int param3, int param4) { - EXTFramebufferObject.glFramebufferRenderbufferEXT(param1, param2, param3, param4); - } - - public void glFramebufferTexture2DEXT(int param1, int param2, int param3, int param4, int param5) { - EXTFramebufferObject.glFramebufferTexture2DEXT(param1, param2, param3, param4, param5); - } - - public void glGenFramebuffersEXT(IntBuffer param1) { - checkLimit(param1); - EXTFramebufferObject.glGenFramebuffersEXT(param1); - } - - public void glGenRenderbuffersEXT(IntBuffer param1) { - checkLimit(param1); - EXTFramebufferObject.glGenRenderbuffersEXT(param1); - } - - public void glGenerateMipmapEXT(int param1) { - EXTFramebufferObject.glGenerateMipmapEXT(param1); - } - - public void glRenderbufferStorageEXT(int param1, int param2, int param3, int param4) { - EXTFramebufferObject.glRenderbufferStorageEXT(param1, param2, param3, param4); - } - @Override public Object glFenceSync(int condition, int flags) { return ARBSync.glFenceSync(condition, flags); diff --git a/jme3-lwjgl/src/main/java/com/jme3/renderer/lwjgl/LwjglGLFboEXT.java b/jme3-lwjgl/src/main/java/com/jme3/renderer/lwjgl/LwjglGLFboEXT.java new file mode 100644 index 000000000..159000a6c --- /dev/null +++ b/jme3-lwjgl/src/main/java/com/jme3/renderer/lwjgl/LwjglGLFboEXT.java @@ -0,0 +1,98 @@ +package com.jme3.renderer.lwjgl; + +import com.jme3.renderer.RendererException; +import com.jme3.renderer.opengl.GLFbo; +import java.nio.Buffer; +import java.nio.IntBuffer; +import org.lwjgl.opengl.EXTFramebufferBlit; +import org.lwjgl.opengl.EXTFramebufferMultisample; +import org.lwjgl.opengl.EXTFramebufferObject; + +/** + * Implements GLFbo via GL_EXT_framebuffer_object. + * + * @author Kirill Vainer + */ +public class LwjglGLFboEXT implements GLFbo { + + private static void checkLimit(Buffer buffer) { + if (buffer == null) { + return; + } + if (buffer.limit() == 0) { + throw new RendererException("Attempting to upload empty buffer (limit = 0), that's an error"); + } + if (buffer.remaining() == 0) { + throw new RendererException("Attempting to upload empty buffer (remaining = 0), that's an error"); + } + } + + @Override + public void glBlitFramebufferEXT(int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, int mask, int filter) { + EXTFramebufferBlit.glBlitFramebufferEXT(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); + } + + @Override + public void glRenderbufferStorageMultisampleEXT(int target, int samples, int internalformat, int width, int height) { + EXTFramebufferMultisample.glRenderbufferStorageMultisampleEXT(target, samples, internalformat, width, height); + } + + @Override + public void glBindFramebufferEXT(int param1, int param2) { + EXTFramebufferObject.glBindFramebufferEXT(param1, param2); + } + + @Override + public void glBindRenderbufferEXT(int param1, int param2) { + EXTFramebufferObject.glBindRenderbufferEXT(param1, param2); + } + + @Override + public int glCheckFramebufferStatusEXT(int param1) { + return EXTFramebufferObject.glCheckFramebufferStatusEXT(param1); + } + + @Override + public void glDeleteFramebuffersEXT(IntBuffer param1) { + checkLimit(param1); + EXTFramebufferObject.glDeleteFramebuffersEXT(param1); + } + + @Override + public void glDeleteRenderbuffersEXT(IntBuffer param1) { + checkLimit(param1); + EXTFramebufferObject.glDeleteRenderbuffersEXT(param1); + } + + @Override + public void glFramebufferRenderbufferEXT(int param1, int param2, int param3, int param4) { + EXTFramebufferObject.glFramebufferRenderbufferEXT(param1, param2, param3, param4); + } + + @Override + public void glFramebufferTexture2DEXT(int param1, int param2, int param3, int param4, int param5) { + EXTFramebufferObject.glFramebufferTexture2DEXT(param1, param2, param3, param4, param5); + } + + @Override + public void glGenFramebuffersEXT(IntBuffer param1) { + checkLimit(param1); + EXTFramebufferObject.glGenFramebuffersEXT(param1); + } + + @Override + public void glGenRenderbuffersEXT(IntBuffer param1) { + checkLimit(param1); + EXTFramebufferObject.glGenRenderbuffersEXT(param1); + } + + @Override + public void glGenerateMipmapEXT(int param1) { + EXTFramebufferObject.glGenerateMipmapEXT(param1); + } + + @Override + public void glRenderbufferStorageEXT(int param1, int param2, int param3, int param4) { + EXTFramebufferObject.glRenderbufferStorageEXT(param1, param2, param3, param4); + } +} diff --git a/jme3-lwjgl/src/main/java/com/jme3/renderer/lwjgl/LwjglGLFboGL3.java b/jme3-lwjgl/src/main/java/com/jme3/renderer/lwjgl/LwjglGLFboGL3.java new file mode 100644 index 000000000..acc540273 --- /dev/null +++ b/jme3-lwjgl/src/main/java/com/jme3/renderer/lwjgl/LwjglGLFboGL3.java @@ -0,0 +1,96 @@ +package com.jme3.renderer.lwjgl; + +import com.jme3.renderer.RendererException; +import com.jme3.renderer.opengl.GLFbo; +import java.nio.Buffer; +import java.nio.IntBuffer; +import org.lwjgl.opengl.GL30; + +/** + * Implements GLFbo via OpenGL3+. + * + * @author Kirill Vainer + */ +public class LwjglGLFboGL3 implements GLFbo { + + private static void checkLimit(Buffer buffer) { + if (buffer == null) { + return; + } + if (buffer.limit() == 0) { + throw new RendererException("Attempting to upload empty buffer (limit = 0), that's an error"); + } + if (buffer.remaining() == 0) { + throw new RendererException("Attempting to upload empty buffer (remaining = 0), that's an error"); + } + } + + @Override + public void glBlitFramebufferEXT(int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, int mask, int filter) { + GL30.glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); + } + + @Override + public void glRenderbufferStorageMultisampleEXT(int target, int samples, int internalformat, int width, int height) { + GL30.glRenderbufferStorageMultisample(target, samples, internalformat, width, height); + } + + @Override + public void glBindFramebufferEXT(int param1, int param2) { + GL30.glBindFramebuffer(param1, param2); + } + + @Override + public void glBindRenderbufferEXT(int param1, int param2) { + GL30.glBindRenderbuffer(param1, param2); + } + + @Override + public int glCheckFramebufferStatusEXT(int param1) { + return GL30.glCheckFramebufferStatus(param1); + } + + @Override + public void glDeleteFramebuffersEXT(IntBuffer param1) { + checkLimit(param1); + GL30.glDeleteFramebuffers(param1); + } + + @Override + public void glDeleteRenderbuffersEXT(IntBuffer param1) { + checkLimit(param1); + GL30.glDeleteRenderbuffers(param1); + } + + @Override + public void glFramebufferRenderbufferEXT(int param1, int param2, int param3, int param4) { + GL30.glFramebufferRenderbuffer(param1, param2, param3, param4); + } + + @Override + public void glFramebufferTexture2DEXT(int param1, int param2, int param3, int param4, int param5) { + GL30.glFramebufferTexture2D(param1, param2, param3, param4, param5); + } + + @Override + public void glGenFramebuffersEXT(IntBuffer param1) { + checkLimit(param1); + GL30.glGenFramebuffers(param1); + } + + @Override + public void glGenRenderbuffersEXT(IntBuffer param1) { + checkLimit(param1); + GL30.glGenRenderbuffers(param1); + } + + @Override + public void glGenerateMipmapEXT(int param1) { + GL30.glGenerateMipmap(param1); + } + + @Override + public void glRenderbufferStorageEXT(int param1, int param2, int param3, int param4) { + GL30.glRenderbufferStorage(param1, param2, param3, param4); + } +} diff --git a/jme3-lwjgl/src/main/java/com/jme3/renderer/lwjgl/LwjglRenderer.java b/jme3-lwjgl/src/main/java/com/jme3/renderer/lwjgl/LwjglRenderer.java deleted file mode 100644 index e614d1dfd..000000000 --- a/jme3-lwjgl/src/main/java/com/jme3/renderer/lwjgl/LwjglRenderer.java +++ /dev/null @@ -1,2695 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.renderer.lwjgl; - -import com.jme3.light.LightList; -import com.jme3.material.RenderState; -import com.jme3.material.RenderState.StencilOperation; -import com.jme3.material.RenderState.TestFunction; -import com.jme3.math.*; -import com.jme3.renderer.*; -import com.jme3.scene.Mesh; -import com.jme3.scene.Mesh.Mode; -import com.jme3.scene.VertexBuffer; -import com.jme3.scene.VertexBuffer.Format; -import com.jme3.scene.VertexBuffer.Type; -import com.jme3.scene.VertexBuffer.Usage; -import com.jme3.shader.Attribute; -import com.jme3.shader.Shader; -import com.jme3.shader.Shader.ShaderSource; -import com.jme3.shader.Shader.ShaderType; -import com.jme3.shader.Uniform; -import com.jme3.texture.FrameBuffer; -import com.jme3.texture.FrameBuffer.RenderBuffer; -import com.jme3.texture.Image; -import com.jme3.texture.Texture; -import com.jme3.texture.Texture.WrapAxis; -import com.jme3.util.BufferUtils; -import com.jme3.util.ListMap; -import com.jme3.util.NativeObjectManager; -import java.nio.*; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import jme3tools.converters.MipMapGenerator; -import jme3tools.shader.ShaderDebug; - -import static org.lwjgl.opengl.ARBDrawInstanced.*; -import static org.lwjgl.opengl.ARBInstancedArrays.*; -import static org.lwjgl.opengl.ARBMultisample.*; -import static org.lwjgl.opengl.ARBTextureMultisample.*; -import static org.lwjgl.opengl.ARBVertexArrayObject.*; -import static org.lwjgl.opengl.EXTFramebufferBlit.*; -import static org.lwjgl.opengl.EXTFramebufferMultisample.*; -import static org.lwjgl.opengl.EXTFramebufferObject.*; -import static org.lwjgl.opengl.EXTFramebufferSRGB.*; -import static org.lwjgl.opengl.EXTTextureArray.*; -import static org.lwjgl.opengl.EXTTextureFilterAnisotropic.*; -import static org.lwjgl.opengl.GL11.*; -import static org.lwjgl.opengl.GL12.*; -import static org.lwjgl.opengl.GL13.*; -import static org.lwjgl.opengl.GL14.*; -import static org.lwjgl.opengl.GL15.*; -import static org.lwjgl.opengl.GL20.*; -import org.lwjgl.opengl.GL30; - -/** - * - * Should not be used, has been replaced by Unified Rendering Architechture. - * @deprecated - */ -@Deprecated -public class LwjglRenderer { - - private static final Logger logger = Logger.getLogger(LwjglRenderer.class.getName()); - private static final boolean VALIDATE_SHADER = false; - private final ByteBuffer nameBuf = BufferUtils.createByteBuffer(250); - private final StringBuilder stringBuf = new StringBuilder(250); - private final IntBuffer intBuf1 = BufferUtils.createIntBuffer(1); - private final IntBuffer intBuf16 = BufferUtils.createIntBuffer(16); - private final FloatBuffer floatBuf16 = BufferUtils.createFloatBuffer(16); - private final RenderContext context = new RenderContext(); - private final NativeObjectManager objManager = new NativeObjectManager(); - private final EnumSet caps = EnumSet.noneOf(Caps.class); - - private int vertexTextureUnits; - private int fragTextureUnits; - private int vertexUniforms; - private int fragUniforms; - private int vertexAttribs; - private int maxFBOSamples; - private int maxFBOAttachs; - private int maxMRTFBOAttachs; - private int maxRBSize; - private int maxTexSize; - private int maxCubeTexSize; - private int maxVertCount; - private int maxTriCount; - private int maxColorTexSamples; - private int maxDepthTexSamples; - private FrameBuffer mainFbOverride = null; - private final Statistics statistics = new Statistics(); - private int vpX, vpY, vpW, vpH; - private int clipX, clipY, clipW, clipH; - private boolean linearizeSrgbImages; - private HashSet extensions; - - public LwjglRenderer() { - } - - protected void updateNameBuffer() { - int len = stringBuf.length(); - - nameBuf.position(0); - nameBuf.limit(len); - for (int i = 0; i < len; i++) { - nameBuf.put((byte) stringBuf.charAt(i)); - } - - nameBuf.rewind(); - } - -// @Override - public Statistics getStatistics() { - return statistics; - } - - // @Override - public EnumSet getCaps() { - return caps; - } - - private static HashSet loadExtensions(String extensions) { - HashSet extensionSet = new HashSet(64); - for (String extension : extensions.split(" ")) { - extensionSet.add(extension); - } - return extensionSet; - } - - private static int extractVersion(String prefixStr, String versionStr) { - if (versionStr != null) { - int spaceIdx = versionStr.indexOf(" ", prefixStr.length()); - if (spaceIdx >= 1) { - versionStr = versionStr.substring(prefixStr.length(), spaceIdx).trim(); - } else { - versionStr = versionStr.substring(prefixStr.length()).trim(); - } - - // Find a character which is not a period or digit. - for (int i = 0; i < versionStr.length(); i++) { - char c = versionStr.charAt(i); - if (c != '.' && (c < '0' || c > '9')) { - versionStr = versionStr.substring(0, i); - break; - } - } - - // Pivot on first point. - int firstPoint = versionStr.indexOf("."); - - // Remove everything after second point. - int secondPoint = versionStr.indexOf(".", firstPoint + 1); - - if (secondPoint != -1) { - versionStr = versionStr.substring(0, secondPoint); - } - - String majorVerStr = versionStr.substring(0, firstPoint); - String minorVerStr = versionStr.substring(firstPoint + 1); - - if (minorVerStr.endsWith("0") && minorVerStr.length() > 1) { - minorVerStr = minorVerStr.substring(0, minorVerStr.length() - 1); - } - - int majorVer = Integer.parseInt(majorVerStr); - int minorVer = Integer.parseInt(minorVerStr); - - return majorVer * 100 + minorVer * 10; - } else { - return -1; - } - } - - private boolean hasExtension(String extensionName) { - return extensions.contains(extensionName); - } - - private void loadCapabilities() { - int oglVer = extractVersion("", glGetString(GL_VERSION)); - - if (oglVer >= 200) { - caps.add(Caps.OpenGL20); - if (oglVer >= 210) { - caps.add(Caps.OpenGL21); - if (oglVer >= 300) { - caps.add(Caps.OpenGL30); - if (oglVer >= 310) { - caps.add(Caps.OpenGL31); - if (oglVer >= 320) { - caps.add(Caps.OpenGL32); - } - } - } - } - } - - int glslVer = extractVersion("", glGetString(GL_SHADING_LANGUAGE_VERSION)); - - switch (glslVer) { - default: - if (glslVer < 400) { - break; - } - // so that future OpenGL revisions wont break jme3 - // fall through intentional - case 400: - case 330: - case 150: - caps.add(Caps.GLSL150); - case 140: - caps.add(Caps.GLSL140); - case 130: - caps.add(Caps.GLSL130); - case 120: - caps.add(Caps.GLSL120); - case 110: - caps.add(Caps.GLSL110); - case 100: - caps.add(Caps.GLSL100); - break; - } - - // Workaround, always assume we support GLSL100. - // Some cards just don't report this correctly. - caps.add(Caps.GLSL100); - - extensions = loadExtensions(glGetString(GL_EXTENSIONS)); - } - - @SuppressWarnings("fallthrough") - public void initialize() { - loadCapabilities(); - - // Fix issue in TestRenderToMemory when GL_FRONT is the main - // buffer being used. - context.initialDrawBuf = glGetInteger(GL_DRAW_BUFFER); - context.initialReadBuf = glGetInteger(GL_READ_BUFFER); - - // XXX: This has to be GL_BACK for canvas on Mac - // Since initialDrawBuf is GL_FRONT for pbuffer, gotta - // change this value later on ... -// initialDrawBuf = GL_BACK; -// initialReadBuf = GL_BACK; - - glGetInteger(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, intBuf16); - vertexTextureUnits = intBuf16.get(0); - logger.log(Level.FINER, "VTF Units: {0}", vertexTextureUnits); - if (vertexTextureUnits > 0) { - caps.add(Caps.VertexTextureFetch); - } - - glGetInteger(GL_MAX_TEXTURE_IMAGE_UNITS, intBuf16); - fragTextureUnits = intBuf16.get(0); - logger.log(Level.FINER, "Texture Units: {0}", fragTextureUnits); - - glGetInteger(GL_MAX_VERTEX_UNIFORM_COMPONENTS, intBuf16); - vertexUniforms = intBuf16.get(0); - logger.log(Level.FINER, "Vertex Uniforms: {0}", vertexUniforms); - - glGetInteger(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, intBuf16); - fragUniforms = intBuf16.get(0); - logger.log(Level.FINER, "Fragment Uniforms: {0}", fragUniforms); - - glGetInteger(GL_MAX_VERTEX_ATTRIBS, intBuf16); - vertexAttribs = intBuf16.get(0); - logger.log(Level.FINER, "Vertex Attributes: {0}", vertexAttribs); - - glGetInteger(GL_SUBPIXEL_BITS, intBuf16); - int subpixelBits = intBuf16.get(0); - logger.log(Level.FINER, "Subpixel Bits: {0}", subpixelBits); - - glGetInteger(GL_MAX_ELEMENTS_VERTICES, intBuf16); - maxVertCount = intBuf16.get(0); - logger.log(Level.FINER, "Preferred Batch Vertex Count: {0}", maxVertCount); - - glGetInteger(GL_MAX_ELEMENTS_INDICES, intBuf16); - maxTriCount = intBuf16.get(0); - logger.log(Level.FINER, "Preferred Batch Index Count: {0}", maxTriCount); - - glGetInteger(GL_MAX_TEXTURE_SIZE, intBuf16); - maxTexSize = intBuf16.get(0); - logger.log(Level.FINER, "Maximum Texture Resolution: {0}", maxTexSize); - - glGetInteger(GL_MAX_CUBE_MAP_TEXTURE_SIZE, intBuf16); - maxCubeTexSize = intBuf16.get(0); - logger.log(Level.FINER, "Maximum CubeMap Resolution: {0}", maxCubeTexSize); - - // ctxCaps = GLContext.getCapabilities(); - - if (hasExtension("GL_ARB_color_buffer_float") && - hasExtension("GL_ARB_half_float_pixel")) { - // XXX: Require both 16 and 32 bit float support for FloatColorBuffer. - caps.add(Caps.FloatColorBuffer); - } - - if (hasExtension("GL_ARB_depth_buffer_float")) { - caps.add(Caps.FloatDepthBuffer); - } - - if (caps.contains(Caps.OpenGL30)) { - caps.add(Caps.PackedDepthStencilBuffer); - } - - if (hasExtension("GL_ARB_draw_instanced") && - hasExtension("GL_ARB_instanced_arrays")) { - caps.add(Caps.MeshInstancing); - } - - if (hasExtension("GL_ARB_texture_buffer_object")) { - caps.add(Caps.TextureBuffer); - } - - if (hasExtension("GL_ARB_texture_float") && - hasExtension("GL_ARB_half_float_pixel")) { - caps.add(Caps.FloatTexture); - } - - if (hasExtension("GL_ARB_vertex_array_object") || caps.contains(Caps.OpenGL30)) { - caps.add(Caps.VertexBufferArray); - } - - if (hasExtension("GL_ARB_texture_non_power_of_two") || caps.contains(Caps.OpenGL30)) { - caps.add(Caps.NonPowerOfTwoTextures); - } else { - logger.log(Level.WARNING, "Your graphics card does not " - + "support non-power-of-2 textures. " - + "Some features might not work."); - } - - if (hasExtension("GL_EXT_texture_compression_s3tc")) { - caps.add(Caps.TextureCompressionS3TC); - } - - if (hasExtension("GL_ARB_ES3_compatibility")) { - caps.add(Caps.TextureCompressionETC1); - } - - if (hasExtension("GL_EXT_packed_float") || caps.contains(Caps.OpenGL30)) { - // This format is part of the OGL3 specification - caps.add(Caps.PackedFloatColorBuffer); - - if (hasExtension("GL_ARB_half_float_pixel")) { - // because textures are usually uploaded as RGB16F - // need half-float pixel - caps.add(Caps.PackedFloatTexture); - } - } - - if (hasExtension("GL_EXT_texture_array") || caps.contains(Caps.OpenGL30)) { - caps.add(Caps.TextureArray); - } - - if (hasExtension("GL_EXT_texture_shared_exponent") || caps.contains(Caps.OpenGL30)) { - caps.add(Caps.SharedExponentTexture); - } - - if (hasExtension("GL_EXT_texture_filter_anisotropic")) { - caps.add(Caps.TextureFilterAnisotropic); - } - - if (hasExtension("GL_EXT_framebuffer_object")) { - caps.add(Caps.FrameBuffer); - - glGetInteger(GL_MAX_RENDERBUFFER_SIZE_EXT, intBuf16); - maxRBSize = intBuf16.get(0); - logger.log(Level.FINER, "FBO RB Max Size: {0}", maxRBSize); - - glGetInteger(GL_MAX_COLOR_ATTACHMENTS_EXT, intBuf16); - maxFBOAttachs = intBuf16.get(0); - logger.log(Level.FINER, "FBO Max renderbuffers: {0}", maxFBOAttachs); - - if (hasExtension("GL_EXT_framebuffer_blit")) { - caps.add(Caps.FrameBufferBlit); - } - - if (hasExtension("GL_EXT_framebuffer_multisample")) { - caps.add(Caps.FrameBufferMultisample); - - glGetInteger(GL_MAX_SAMPLES_EXT, intBuf16); - maxFBOSamples = intBuf16.get(0); - logger.log(Level.FINER, "FBO Max Samples: {0}", maxFBOSamples); - } - - if (hasExtension("GL_ARB_texture_multisample")) { - caps.add(Caps.TextureMultisample); - - glGetInteger(GL_MAX_COLOR_TEXTURE_SAMPLES, intBuf16); - maxColorTexSamples = intBuf16.get(0); - logger.log(Level.FINER, "Texture Multisample Color Samples: {0}", maxColorTexSamples); - - glGetInteger(GL_MAX_DEPTH_TEXTURE_SAMPLES, intBuf16); - maxDepthTexSamples = intBuf16.get(0); - logger.log(Level.FINER, "Texture Multisample Depth Samples: {0}", maxDepthTexSamples); - } - - if (hasExtension("GL_ARB_draw_buffers")) { - glGetInteger(GL_MAX_DRAW_BUFFERS, intBuf16); - maxMRTFBOAttachs = intBuf16.get(0); - if (maxMRTFBOAttachs > 1) { - caps.add(Caps.FrameBufferMRT); - logger.log(Level.FINER, "FBO Max MRT renderbuffers: {0}", maxMRTFBOAttachs); - } - } - } - - if (hasExtension("GL_ARB_multisample")) { - glGetInteger(GL_SAMPLE_BUFFERS_ARB, intBuf16); - boolean available = intBuf16.get(0) != 0; - glGetInteger(GL_SAMPLES_ARB, intBuf16); - int samples = intBuf16.get(0); - logger.log(Level.FINER, "Samples: {0}", samples); - boolean enabled = glIsEnabled(GL_MULTISAMPLE_ARB); - if (samples > 0 && available && !enabled) { - glEnable(GL_MULTISAMPLE_ARB); - } - caps.add(Caps.Multisample); - } - - // Supports sRGB pipeline. - if ( (hasExtension("GL_ARB_framebuffer_sRGB") && hasExtension("GL_EXT_texture_sRGB")) - || caps.contains(Caps.OpenGL30) ) { - caps.add(Caps.Srgb); - } - - logger.log(Level.FINE, "Caps: {0}", caps); - } - - public void invalidateState() { - context.reset(); - context.initialDrawBuf = glGetInteger(GL_DRAW_BUFFER); - context.initialReadBuf = glGetInteger(GL_READ_BUFFER); - } - - public void resetGLObjects() { - logger.log(Level.FINE, "Reseting objects and invalidating state"); - objManager.resetObjects(); - statistics.clearMemory(); - invalidateState(); - } - - public void cleanup() { - logger.log(Level.FINE, "Deleting objects and invalidating state"); - objManager.deleteAllObjects(this); - statistics.clearMemory(); - invalidateState(); - } - - private void checkCap(Caps cap) { - if (!caps.contains(cap)) { - throw new UnsupportedOperationException("Required capability missing: " + cap.name()); - } - } - - /*********************************************************************\ - |* Render State *| - \*********************************************************************/ - public void setDepthRange(float start, float end) { - glDepthRange(start, end); - } - - public void clearBuffers(boolean color, boolean depth, boolean stencil) { - int bits = 0; - if (color) { - //See explanations of the depth below, we must enable color write to be able to clear the color buffer - if (context.colorWriteEnabled == false) { - glColorMask(true, true, true, true); - context.colorWriteEnabled = true; - } - bits = GL_COLOR_BUFFER_BIT; - } - if (depth) { - - //glClear(GL_DEPTH_BUFFER_BIT) seems to not work when glDepthMask is false - //here s some link on openl board - //http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=257223 - //if depth clear is requested, we enable the depthMask - if (context.depthWriteEnabled == false) { - glDepthMask(true); - context.depthWriteEnabled = true; - } - bits |= GL_DEPTH_BUFFER_BIT; - } - if (stencil) { - bits |= GL_STENCIL_BUFFER_BIT; - } - if (bits != 0) { - glClear(bits); - } - } - - public void setBackgroundColor(ColorRGBA color) { - glClearColor(color.r, color.g, color.b, color.a); - } - - public void setAlphaToCoverage(boolean value) { - if (caps.contains(Caps.Multisample)) { - if (value) { - glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB); - } else { - glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB); - } - } - } - - public void applyRenderState(RenderState state) { - if (state.isWireframe() && !context.wireframe) { - glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); - context.wireframe = true; - } else if (!state.isWireframe() && context.wireframe) { - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); - context.wireframe = false; - } - - if (state.isDepthTest() && !context.depthTestEnabled) { - glEnable(GL_DEPTH_TEST); - glDepthFunc(convertTestFunction(context.depthFunc)); - context.depthTestEnabled = true; - } else if (!state.isDepthTest() && context.depthTestEnabled) { - glDisable(GL_DEPTH_TEST); - context.depthTestEnabled = false; - } - if (state.getDepthFunc() != context.depthFunc) { - glDepthFunc(convertTestFunction(state.getDepthFunc())); - context.depthFunc = state.getDepthFunc(); - } - - if (state.isAlphaTest() && !context.alphaTestEnabled) { - glEnable(GL_ALPHA_TEST); - glAlphaFunc(convertTestFunction(context.alphaFunc), context.alphaTestFallOff); - context.alphaTestEnabled = true; - } else if (!state.isAlphaTest() && context.alphaTestEnabled) { - glDisable(GL_ALPHA_TEST); - context.alphaTestEnabled = false; - } - if (state.getAlphaFallOff() != context.alphaTestFallOff) { - glAlphaFunc(convertTestFunction(context.alphaFunc), context.alphaTestFallOff); - context.alphaTestFallOff = state.getAlphaFallOff(); - } - if (state.getAlphaFunc() != context.alphaFunc) { - glAlphaFunc(convertTestFunction(state.getAlphaFunc()), context.alphaTestFallOff); - context.alphaFunc = state.getAlphaFunc(); - } - - if (state.isDepthWrite() && !context.depthWriteEnabled) { - glDepthMask(true); - context.depthWriteEnabled = true; - } else if (!state.isDepthWrite() && context.depthWriteEnabled) { - glDepthMask(false); - context.depthWriteEnabled = false; - } - - if (state.isColorWrite() && !context.colorWriteEnabled) { - glColorMask(true, true, true, true); - context.colorWriteEnabled = true; - } else if (!state.isColorWrite() && context.colorWriteEnabled) { - glColorMask(false, false, false, false); - context.colorWriteEnabled = false; - } - - if (state.isPointSprite() && !context.pointSprite) { - // Only enable/disable sprite - if (context.boundTextures[0] != null) { - if (context.boundTextureUnit != 0) { - glActiveTexture(GL_TEXTURE0); - context.boundTextureUnit = 0; - } - glEnable(GL_POINT_SPRITE); - glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); - } - context.pointSprite = true; - } else if (!state.isPointSprite() && context.pointSprite) { - if (context.boundTextures[0] != null) { - if (context.boundTextureUnit != 0) { - glActiveTexture(GL_TEXTURE0); - context.boundTextureUnit = 0; - } - glDisable(GL_POINT_SPRITE); - glDisable(GL_VERTEX_PROGRAM_POINT_SIZE); - context.pointSprite = false; - } - } - - if (state.isPolyOffset()) { - if (!context.polyOffsetEnabled) { - glEnable(GL_POLYGON_OFFSET_FILL); - glPolygonOffset(state.getPolyOffsetFactor(), - state.getPolyOffsetUnits()); - context.polyOffsetEnabled = true; - context.polyOffsetFactor = state.getPolyOffsetFactor(); - context.polyOffsetUnits = state.getPolyOffsetUnits(); - } else { - if (state.getPolyOffsetFactor() != context.polyOffsetFactor - || state.getPolyOffsetUnits() != context.polyOffsetUnits) { - glPolygonOffset(state.getPolyOffsetFactor(), - state.getPolyOffsetUnits()); - context.polyOffsetFactor = state.getPolyOffsetFactor(); - context.polyOffsetUnits = state.getPolyOffsetUnits(); - } - } - } else { - if (context.polyOffsetEnabled) { - glDisable(GL_POLYGON_OFFSET_FILL); - context.polyOffsetEnabled = false; - context.polyOffsetFactor = 0; - context.polyOffsetUnits = 0; - } - } - - if (state.getFaceCullMode() != context.cullMode) { - if (state.getFaceCullMode() == RenderState.FaceCullMode.Off) { - glDisable(GL_CULL_FACE); - } else { - glEnable(GL_CULL_FACE); - } - - switch (state.getFaceCullMode()) { - case Off: - break; - case Back: - glCullFace(GL_BACK); - break; - case Front: - glCullFace(GL_FRONT); - break; - case FrontAndBack: - glCullFace(GL_FRONT_AND_BACK); - break; - default: - throw new UnsupportedOperationException("Unrecognized face cull mode: " - + state.getFaceCullMode()); - } - - context.cullMode = state.getFaceCullMode(); - } - - if (state.getBlendMode() != context.blendMode) { - if (state.getBlendMode() == RenderState.BlendMode.Off) { - glDisable(GL_BLEND); - } else { - glEnable(GL_BLEND); - switch (state.getBlendMode()) { - case Off: - break; - case Additive: - glBlendFunc(GL_ONE, GL_ONE); - break; - case AlphaAdditive: - glBlendFunc(GL_SRC_ALPHA, GL_ONE); - break; - case Color: - glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_COLOR); - break; - case Alpha: - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - break; - case PremultAlpha: - glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); - break; - case Modulate: - glBlendFunc(GL_DST_COLOR, GL_ZERO); - break; - case ModulateX2: - glBlendFunc(GL_DST_COLOR, GL_SRC_COLOR); - break; - case Screen: - glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_COLOR); - break; - case Exclusion: - glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_SRC_COLOR); - break; - default: - throw new UnsupportedOperationException("Unrecognized blend mode: " - + state.getBlendMode()); - } - } - - context.blendMode = state.getBlendMode(); - } - - if (context.stencilTest != state.isStencilTest() - || context.frontStencilStencilFailOperation != state.getFrontStencilStencilFailOperation() - || context.frontStencilDepthFailOperation != state.getFrontStencilDepthFailOperation() - || context.frontStencilDepthPassOperation != state.getFrontStencilDepthPassOperation() - || context.backStencilStencilFailOperation != state.getBackStencilStencilFailOperation() - || context.backStencilDepthFailOperation != state.getBackStencilDepthFailOperation() - || context.backStencilDepthPassOperation != state.getBackStencilDepthPassOperation() - || context.frontStencilFunction != state.getFrontStencilFunction() - || context.backStencilFunction != state.getBackStencilFunction()) { - - context.frontStencilStencilFailOperation = state.getFrontStencilStencilFailOperation(); //terrible looking, I know - context.frontStencilDepthFailOperation = state.getFrontStencilDepthFailOperation(); - context.frontStencilDepthPassOperation = state.getFrontStencilDepthPassOperation(); - context.backStencilStencilFailOperation = state.getBackStencilStencilFailOperation(); - context.backStencilDepthFailOperation = state.getBackStencilDepthFailOperation(); - context.backStencilDepthPassOperation = state.getBackStencilDepthPassOperation(); - context.frontStencilFunction = state.getFrontStencilFunction(); - context.backStencilFunction = state.getBackStencilFunction(); - - if (state.isStencilTest()) { - glEnable(GL_STENCIL_TEST); - glStencilOpSeparate(GL_FRONT, - convertStencilOperation(state.getFrontStencilStencilFailOperation()), - convertStencilOperation(state.getFrontStencilDepthFailOperation()), - convertStencilOperation(state.getFrontStencilDepthPassOperation())); - glStencilOpSeparate(GL_BACK, - convertStencilOperation(state.getBackStencilStencilFailOperation()), - convertStencilOperation(state.getBackStencilDepthFailOperation()), - convertStencilOperation(state.getBackStencilDepthPassOperation())); - glStencilFuncSeparate(GL_FRONT, - convertTestFunction(state.getFrontStencilFunction()), - 0, Integer.MAX_VALUE); - glStencilFuncSeparate(GL_BACK, - convertTestFunction(state.getBackStencilFunction()), - 0, Integer.MAX_VALUE); - } else { - glDisable(GL_STENCIL_TEST); - } - } - } - - private int convertStencilOperation(StencilOperation stencilOp) { - switch (stencilOp) { - case Keep: - return GL_KEEP; - case Zero: - return GL_ZERO; - case Replace: - return GL_REPLACE; - case Increment: - return GL_INCR; - case IncrementWrap: - return GL_INCR_WRAP; - case Decrement: - return GL_DECR; - case DecrementWrap: - return GL_DECR_WRAP; - case Invert: - return GL_INVERT; - default: - throw new UnsupportedOperationException("Unrecognized stencil operation: " + stencilOp); - } - } - - private int convertTestFunction(TestFunction testFunc) { - switch (testFunc) { - case Never: - return GL_NEVER; - case Less: - return GL_LESS; - case LessOrEqual: - return GL_LEQUAL; - case Greater: - return GL_GREATER; - case GreaterOrEqual: - return GL_GEQUAL; - case Equal: - return GL_EQUAL; - case NotEqual: - return GL_NOTEQUAL; - case Always: - return GL_ALWAYS; - default: - throw new UnsupportedOperationException("Unrecognized test function: " + testFunc); - } - } - - /*********************************************************************\ - |* Camera and World transforms *| - \*********************************************************************/ - public void setViewPort(int x, int y, int w, int h) { - if (x != vpX || vpY != y || vpW != w || vpH != h) { - glViewport(x, y, w, h); - vpX = x; - vpY = y; - vpW = w; - vpH = h; - } - } - - public void setClipRect(int x, int y, int width, int height) { - if (!context.clipRectEnabled) { - glEnable(GL_SCISSOR_TEST); - context.clipRectEnabled = true; - } - if (clipX != x || clipY != y || clipW != width || clipH != height) { - glScissor(x, y, width, height); - clipX = x; - clipY = y; - clipW = width; - clipH = height; - } - } - - public void clearClipRect() { - if (context.clipRectEnabled) { - glDisable(GL_SCISSOR_TEST); - context.clipRectEnabled = false; - - clipX = 0; - clipY = 0; - clipW = 0; - clipH = 0; - } - } - - public void postFrame() { - objManager.deleteUnused(this); -// statistics.clearFrame(); - } - - public void setWorldMatrix(Matrix4f worldMatrix) { - } - - public void setViewProjectionMatrices(Matrix4f viewMatrix, Matrix4f projMatrix) { - } - - /*********************************************************************\ - |* Shaders *| - \*********************************************************************/ - protected void updateUniformLocation(Shader shader, Uniform uniform) { - stringBuf.setLength(0); - stringBuf.append(uniform.getName()).append('\0'); - updateNameBuffer(); - int loc = glGetUniformLocation(shader.getId(), nameBuf); - if (loc < 0) { - uniform.setLocation(-1); - // uniform is not declared in shader - logger.log(Level.FINE, "Uniform {0} is not declared in shader {1}.", new Object[]{uniform.getName(), shader.getSources()}); - } else { - uniform.setLocation(loc); - } - } - - protected void bindProgram(Shader shader) { - int shaderId = shader.getId(); - if (context.boundShaderProgram != shaderId) { - glUseProgram(shaderId); - statistics.onShaderUse(shader, true); - context.boundShader = shader; - context.boundShaderProgram = shaderId; - } else { - statistics.onShaderUse(shader, false); - } - } - - protected void updateUniform(Shader shader, Uniform uniform) { - int shaderId = shader.getId(); - - assert uniform.getName() != null; - assert shader.getId() > 0; - - bindProgram(shader); - - int loc = uniform.getLocation(); - if (loc == -1) { - return; - } - - if (loc == -2) { - // get uniform location - updateUniformLocation(shader, uniform); - if (uniform.getLocation() == -1) { - // not declared, ignore - uniform.clearUpdateNeeded(); - return; - } - loc = uniform.getLocation(); - } - - if (uniform.getVarType() == null) { - return; // value not set yet.. - } - statistics.onUniformSet(); - - uniform.clearUpdateNeeded(); - FloatBuffer fb; - IntBuffer ib; - switch (uniform.getVarType()) { - case Float: - Float f = (Float) uniform.getValue(); - glUniform1f(loc, f.floatValue()); - break; - case Vector2: - Vector2f v2 = (Vector2f) uniform.getValue(); - glUniform2f(loc, v2.getX(), v2.getY()); - break; - case Vector3: - Vector3f v3 = (Vector3f) uniform.getValue(); - glUniform3f(loc, v3.getX(), v3.getY(), v3.getZ()); - break; - case Vector4: - Object val = uniform.getValue(); - if (val instanceof ColorRGBA) { - ColorRGBA c = (ColorRGBA) val; - glUniform4f(loc, c.r, c.g, c.b, c.a); - } else if (val instanceof Vector4f) { - Vector4f c = (Vector4f) val; - glUniform4f(loc, c.x, c.y, c.z, c.w); - } else { - Quaternion c = (Quaternion) uniform.getValue(); - glUniform4f(loc, c.getX(), c.getY(), c.getZ(), c.getW()); - } - break; - case Boolean: - Boolean b = (Boolean) uniform.getValue(); - glUniform1i(loc, b.booleanValue() ? GL_TRUE : GL_FALSE); - break; - case Matrix3: - fb = (FloatBuffer) uniform.getValue(); - assert fb.remaining() == 9; - glUniformMatrix3(loc, false, fb); - break; - case Matrix4: - fb = (FloatBuffer) uniform.getValue(); - assert fb.remaining() == 16; - glUniformMatrix4(loc, false, fb); - break; - case IntArray: - ib = (IntBuffer) uniform.getValue(); - glUniform1(loc, ib); - break; - case FloatArray: - fb = (FloatBuffer) uniform.getValue(); - glUniform1(loc, fb); - break; - case Vector2Array: - fb = (FloatBuffer) uniform.getValue(); - glUniform2(loc, fb); - break; - case Vector3Array: - fb = (FloatBuffer) uniform.getValue(); - glUniform3(loc, fb); - break; - case Vector4Array: - fb = (FloatBuffer) uniform.getValue(); - glUniform4(loc, fb); - break; - case Matrix4Array: - fb = (FloatBuffer) uniform.getValue(); - glUniformMatrix4(loc, false, fb); - break; - case Int: - Integer i = (Integer) uniform.getValue(); - glUniform1i(loc, i.intValue()); - break; - default: - throw new UnsupportedOperationException("Unsupported uniform type: " + uniform.getVarType()); - } - } - - protected void updateShaderUniforms(Shader shader) { - ListMap uniforms = shader.getUniformMap(); - for (int i = 0; i < uniforms.size(); i++) { - Uniform uniform = uniforms.getValue(i); - if (uniform.isUpdateNeeded()) { - updateUniform(shader, uniform); - } - } - } - - protected void resetUniformLocations(Shader shader) { - ListMap uniforms = shader.getUniformMap(); - for (int i = 0; i < uniforms.size(); i++) { - Uniform uniform = uniforms.getValue(i); - uniform.reset(); // e.g check location again - } - } - - /* - * (Non-javadoc) - * Only used for fixed-function. Ignored. - */ - public void setLighting(LightList list) { - } - - public int convertShaderType(ShaderType type) { - switch (type) { - case Fragment: - return GL_FRAGMENT_SHADER; - case Vertex: - return GL_VERTEX_SHADER; - default: - throw new UnsupportedOperationException("Unrecognized shader type."); - } - } - - public void updateShaderSourceData(ShaderSource source) { - int id = source.getId(); - if (id == -1) { - // Create id - id = glCreateShader(convertShaderType(source.getType())); - if (id <= 0) { - throw new RendererException("Invalid ID received when trying to create shader."); - } - - source.setId(id); - } else { - throw new RendererException("Cannot recompile shader source"); - } - - // Upload shader source. - // Merge the defines and source code. - String language = source.getLanguage(); - stringBuf.setLength(0); - if (language.startsWith("GLSL")) { - int version = Integer.parseInt(language.substring(4)); - if (version > 100) { - stringBuf.append("#version "); - stringBuf.append(language.substring(4)); - if (version >= 150) { - stringBuf.append(" core"); - } - stringBuf.append("\n"); - } else { - // version 100 does not exist in desktop GLSL. - // put version 110 in that case to enable strict checking - stringBuf.append("#version 110\n"); - } - } - updateNameBuffer(); - - byte[] definesCodeData = source.getDefines().getBytes(); - byte[] sourceCodeData = source.getSource().getBytes(); - ByteBuffer codeBuf = BufferUtils.createByteBuffer(nameBuf.limit() - + definesCodeData.length - + sourceCodeData.length); - codeBuf.put(nameBuf); - codeBuf.put(definesCodeData); - codeBuf.put(sourceCodeData); - codeBuf.flip(); - - glShaderSource(id, codeBuf); - glCompileShader(id); - - glGetShader(id, GL_COMPILE_STATUS, intBuf1); - - boolean compiledOK = intBuf1.get(0) == GL_TRUE; - String infoLog = null; - - if (VALIDATE_SHADER || !compiledOK) { - // even if compile succeeded, check - // log for warnings - glGetShader(id, GL_INFO_LOG_LENGTH, intBuf1); - int length = intBuf1.get(0); - if (length > 3) { - // get infos - ByteBuffer logBuf = BufferUtils.createByteBuffer(length); - glGetShaderInfoLog(id, null, logBuf); - byte[] logBytes = new byte[length]; - logBuf.get(logBytes, 0, length); - // convert to string, etc - infoLog = new String(logBytes); - } - } - - if (compiledOK) { - if (infoLog != null) { - logger.log(Level.WARNING, "{0} compiled successfully, compiler warnings: \n{1}", - new Object[]{source.getName(), infoLog}); - } else { - logger.log(Level.FINE, "{0} compiled successfully.", source.getName()); - } - source.clearUpdateNeeded(); - } else { - logger.log(Level.WARNING, "Bad compile of:\n{0}", - new Object[]{ShaderDebug.formatShaderSource(stringBuf.toString() + source.getDefines() + source.getSource())}); - if (infoLog != null) { - throw new RendererException("compile error in: " + source + "\n" + infoLog); - } else { - throw new RendererException("compile error in: " + source + "\nerror: "); - } - } - } - - public void updateShaderData(Shader shader) { - int id = shader.getId(); - boolean needRegister = false; - if (id == -1) { - // create program - id = glCreateProgram(); - if (id == 0) { - throw new RendererException("Invalid ID (" + id + ") received when trying to create shader program."); - } - - shader.setId(id); - needRegister = true; - } - - for (ShaderSource source : shader.getSources()) { - if (source.isUpdateNeeded()) { - updateShaderSourceData(source); - } - glAttachShader(id, source.getId()); - } - - if (caps.contains(Caps.OpenGL30)) { - // Check if GLSL version is 1.5 for shader - GL30.glBindFragDataLocation(id, 0, "outFragColor"); - // For MRT - for (int i = 0; i < maxMRTFBOAttachs; i++) { - GL30.glBindFragDataLocation(id, i, "outFragData[" + i + "]"); - } - } - - // Link shaders to program - glLinkProgram(id); - - // Check link status - glGetProgram(id, GL_LINK_STATUS, intBuf1); - boolean linkOK = intBuf1.get(0) == GL_TRUE; - String infoLog = null; - - if (VALIDATE_SHADER || !linkOK) { - glGetProgram(id, GL_INFO_LOG_LENGTH, intBuf1); - int length = intBuf1.get(0); - if (length > 3) { - // get infos - ByteBuffer logBuf = BufferUtils.createByteBuffer(length); - glGetProgramInfoLog(id, null, logBuf); - - // convert to string, etc - byte[] logBytes = new byte[length]; - logBuf.get(logBytes, 0, length); - infoLog = new String(logBytes); - } - } - - if (linkOK) { - if (infoLog != null) { - logger.log(Level.WARNING, "Shader linked successfully. Linker warnings: \n{0}", infoLog); - } else { - logger.fine("Shader linked successfully."); - } - shader.clearUpdateNeeded(); - if (needRegister) { - // Register shader for clean up if it was created in this method. - objManager.registerObject(shader); - statistics.onNewShader(); - } else { - // OpenGL spec: uniform locations may change after re-link - resetUniformLocations(shader); - } - } else { - if (infoLog != null) { - throw new RendererException("Shader failed to link, shader:" + shader + "\n" + infoLog); - } else { - throw new RendererException("Shader failed to link, shader:" + shader + "\ninfo: "); - } - } - } - - public void setShader(Shader shader) { - if (shader == null) { - throw new IllegalArgumentException("Shader cannot be null"); - } else { - if (shader.isUpdateNeeded()) { - updateShaderData(shader); - } - - // NOTE: might want to check if any of the - // sources need an update? - - assert shader.getId() > 0; - - updateShaderUniforms(shader); - bindProgram(shader); - } - } - - public void deleteShaderSource(ShaderSource source) { - if (source.getId() < 0) { - logger.warning("Shader source is not uploaded to GPU, cannot delete."); - return; - } - source.clearUpdateNeeded(); - glDeleteShader(source.getId()); - source.resetObject(); - } - - public void deleteShader(Shader shader) { - if (shader.getId() == -1) { - logger.warning("Shader is not uploaded to GPU, cannot delete."); - return; - } - - for (ShaderSource source : shader.getSources()) { - if (source.getId() != -1) { - glDetachShader(shader.getId(), source.getId()); - deleteShaderSource(source); - } - } - - glDeleteProgram(shader.getId()); - statistics.onDeleteShader(); - shader.resetObject(); - } - - /*********************************************************************\ - |* Framebuffers *| - \*********************************************************************/ - public void copyFrameBuffer(FrameBuffer src, FrameBuffer dst) { - copyFrameBuffer(src, dst, true); - } - - public void copyFrameBuffer(FrameBuffer src, FrameBuffer dst, boolean copyDepth) { - if (caps.contains(Caps.FrameBufferBlit)) { - int srcX0 = 0; - int srcY0 = 0; - int srcX1; - int srcY1; - - int dstX0 = 0; - int dstY0 = 0; - int dstX1; - int dstY1; - - int prevFBO = context.boundFBO; - - if (mainFbOverride != null) { - if (src == null) { - src = mainFbOverride; - } - if (dst == null) { - dst = mainFbOverride; - } - } - - if (src != null && src.isUpdateNeeded()) { - updateFrameBuffer(src); - } - - if (dst != null && dst.isUpdateNeeded()) { - updateFrameBuffer(dst); - } - - if (src == null) { - glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, 0); - srcX0 = vpX; - srcY0 = vpY; - srcX1 = vpX + vpW; - srcY1 = vpY + vpH; - } else { - glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, src.getId()); - srcX1 = src.getWidth(); - srcY1 = src.getHeight(); - } - if (dst == null) { - glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, 0); - dstX0 = vpX; - dstY0 = vpY; - dstX1 = vpX + vpW; - dstY1 = vpY + vpH; - } else { - glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, dst.getId()); - dstX1 = dst.getWidth(); - dstY1 = dst.getHeight(); - } - int mask = GL_COLOR_BUFFER_BIT; - if (copyDepth) { - mask |= GL_DEPTH_BUFFER_BIT; - } - glBlitFramebufferEXT(srcX0, srcY0, srcX1, srcY1, - dstX0, dstY0, dstX1, dstY1, mask, - GL_NEAREST); - - - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, prevFBO); - try { - checkFrameBufferError(); - } catch (IllegalStateException ex) { - logger.log(Level.SEVERE, "Source FBO:\n{0}", src); - logger.log(Level.SEVERE, "Dest FBO:\n{0}", dst); - throw ex; - } - } else { - throw new RendererException("EXT_framebuffer_blit required."); - // TODO: support non-blit copies? - } - } - - private String getTargetBufferName(int buffer) { - switch (buffer) { - case GL_NONE: - return "NONE"; - case GL_FRONT: - return "GL_FRONT"; - case GL_BACK: - return "GL_BACK"; - default: - if (buffer >= GL_COLOR_ATTACHMENT0_EXT - && buffer <= GL_COLOR_ATTACHMENT15_EXT) { - return "GL_COLOR_ATTACHMENT" - + (buffer - GL_COLOR_ATTACHMENT0_EXT); - } else { - return "UNKNOWN? " + buffer; - } - } - } - - private void printRealRenderBufferInfo(FrameBuffer fb, RenderBuffer rb, String name) { - System.out.println("== Renderbuffer " + name + " =="); - System.out.println("RB ID: " + rb.getId()); - System.out.println("Is proper? " + glIsRenderbufferEXT(rb.getId())); - - int attachment = convertAttachmentSlot(rb.getSlot()); - - int type = glGetFramebufferAttachmentParameteriEXT(GL_DRAW_FRAMEBUFFER_EXT, - attachment, - GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT); - - int rbName = glGetFramebufferAttachmentParameteriEXT(GL_DRAW_FRAMEBUFFER_EXT, - attachment, - GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT); - - switch (type) { - case GL_NONE: - System.out.println("Type: None"); - break; - case GL_TEXTURE: - System.out.println("Type: Texture"); - break; - case GL_RENDERBUFFER_EXT: - System.out.println("Type: Buffer"); - System.out.println("RB ID: " + rbName); - break; - } - - - - } - - private void printRealFrameBufferInfo(FrameBuffer fb) { - boolean doubleBuffer = glGetBoolean(GL_DOUBLEBUFFER); - String drawBuf = getTargetBufferName(glGetInteger(GL_DRAW_BUFFER)); - String readBuf = getTargetBufferName(glGetInteger(GL_READ_BUFFER)); - - int fbId = fb.getId(); - int curDrawBinding = glGetInteger(GL_DRAW_FRAMEBUFFER_BINDING_EXT); - int curReadBinding = glGetInteger(GL_READ_FRAMEBUFFER_BINDING_EXT); - - System.out.println("=== OpenGL FBO State ==="); - System.out.println("Context doublebuffered? " + doubleBuffer); - System.out.println("FBO ID: " + fbId); - System.out.println("Is proper? " + glIsFramebufferEXT(fbId)); - System.out.println("Is bound to draw? " + (fbId == curDrawBinding)); - System.out.println("Is bound to read? " + (fbId == curReadBinding)); - System.out.println("Draw buffer: " + drawBuf); - System.out.println("Read buffer: " + readBuf); - - if (context.boundFBO != fbId) { - glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, fbId); - context.boundFBO = fbId; - } - - if (fb.getDepthBuffer() != null) { - printRealRenderBufferInfo(fb, fb.getDepthBuffer(), "Depth"); - } - for (int i = 0; i < fb.getNumColorBuffers(); i++) { - printRealRenderBufferInfo(fb, fb.getColorBuffer(i), "Color" + i); - } - } - - private void checkFrameBufferError() { - int status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); - switch (status) { - case GL_FRAMEBUFFER_COMPLETE_EXT: - break; - case GL_FRAMEBUFFER_UNSUPPORTED_EXT: - //Choose different formats - throw new IllegalStateException("Framebuffer object format is " - + "unsupported by the video hardware."); - case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT: - throw new IllegalStateException("Framebuffer has erronous attachment."); - case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT: - throw new IllegalStateException("Framebuffer doesn't have any renderbuffers attached."); - case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT: - throw new IllegalStateException("Framebuffer attachments must have same dimensions."); - case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT: - throw new IllegalStateException("Framebuffer attachments must have same formats."); - case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT: - throw new IllegalStateException("Incomplete draw buffer."); - case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT: - throw new IllegalStateException("Incomplete read buffer."); - case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT: - throw new IllegalStateException("Incomplete multisample buffer."); - default: - //Programming error; will fail on all hardware - throw new IllegalStateException("Some video driver error " - + "or programming error occured. " - + "Framebuffer object status is invalid. "); - } - } - - private void updateRenderBuffer(FrameBuffer fb, RenderBuffer rb) { - int id = rb.getId(); - if (id == -1) { - glGenRenderbuffersEXT(intBuf1); - id = intBuf1.get(0); - rb.setId(id); - } - - if (context.boundRB != id) { - glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, id); - context.boundRB = id; - } - - if (fb.getWidth() > maxRBSize || fb.getHeight() > maxRBSize) { - throw new RendererException("Resolution " + fb.getWidth() - + ":" + fb.getHeight() + " is not supported."); - } - - TextureUtil.GLImageFormat glFmt = TextureUtil.getImageFormatWithError(caps, rb.getFormat(), fb.isSrgb()); - - if (fb.getSamples() > 1 && caps.contains(Caps.FrameBufferMultisample)) { - int samples = fb.getSamples(); - if (maxFBOSamples < samples) { - samples = maxFBOSamples; - } - glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, - samples, - glFmt.internalFormat, - fb.getWidth(), - fb.getHeight()); - } else { - glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, - glFmt.internalFormat, - fb.getWidth(), - fb.getHeight()); - } - } - - private int convertAttachmentSlot(int attachmentSlot) { - // can also add support for stencil here - if (attachmentSlot == FrameBuffer.SLOT_DEPTH) { - return GL_DEPTH_ATTACHMENT_EXT; - } else if (attachmentSlot == FrameBuffer.SLOT_DEPTH_STENCIL) { - // NOTE: Using depth stencil format requires GL3, this is already - // checked via render caps. - return GL30.GL_DEPTH_STENCIL_ATTACHMENT; - } else if (attachmentSlot < 0 || attachmentSlot >= 16) { - throw new UnsupportedOperationException("Invalid FBO attachment slot: " + attachmentSlot); - } - - return GL_COLOR_ATTACHMENT0_EXT + attachmentSlot; - } - - public void updateRenderTexture(FrameBuffer fb, RenderBuffer rb) { - Texture tex = rb.getTexture(); - Image image = tex.getImage(); - if (image.isUpdateNeeded()) { - updateTexImageData(image, tex.getType(), 0); - - // NOTE: For depth textures, sets nearest/no-mips mode - // Required to fix "framebuffer unsupported" - // for old NVIDIA drivers! - setupTextureParams(tex); - } - - glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, - convertAttachmentSlot(rb.getSlot()), - convertTextureType(tex.getType(), image.getMultiSamples(), rb.getFace()), - image.getId(), - 0); - } - - public void updateFrameBufferAttachment(FrameBuffer fb, RenderBuffer rb) { - boolean needAttach; - if (rb.getTexture() == null) { - // if it hasn't been created yet, then attach is required. - needAttach = rb.getId() == -1; - updateRenderBuffer(fb, rb); - } else { - needAttach = false; - updateRenderTexture(fb, rb); - } - if (needAttach) { - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, - convertAttachmentSlot(rb.getSlot()), - GL_RENDERBUFFER_EXT, - rb.getId()); - } - } - - public void updateFrameBuffer(FrameBuffer fb) { - int id = fb.getId(); - if (id == -1) { - // create FBO - glGenFramebuffersEXT(intBuf1); - id = intBuf1.get(0); - fb.setId(id); - objManager.registerObject(fb); - - statistics.onNewFrameBuffer(); - } - - if (context.boundFBO != id) { - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, id); - // binding an FBO automatically sets draw buf to GL_COLOR_ATTACHMENT0 - context.boundDrawBuf = 0; - context.boundFBO = id; - } - - FrameBuffer.RenderBuffer depthBuf = fb.getDepthBuffer(); - if (depthBuf != null) { - updateFrameBufferAttachment(fb, depthBuf); - } - - for (int i = 0; i < fb.getNumColorBuffers(); i++) { - FrameBuffer.RenderBuffer colorBuf = fb.getColorBuffer(i); - updateFrameBufferAttachment(fb, colorBuf); - } - - fb.clearUpdateNeeded(); - } - - public Vector2f[] getFrameBufferSamplePositions(FrameBuffer fb) { - if (fb.getSamples() <= 1) { - throw new IllegalArgumentException("Framebuffer must be multisampled"); - } - if (!caps.contains(Caps.TextureMultisample)) { - throw new RendererException("Multisampled textures are not supported"); - } - - setFrameBuffer(fb); - - Vector2f[] samplePositions = new Vector2f[fb.getSamples()]; - FloatBuffer samplePos = BufferUtils.createFloatBuffer(2); - for (int i = 0; i < samplePositions.length; i++) { - glGetMultisample(GL_SAMPLE_POSITION, i, samplePos); - samplePos.clear(); - samplePositions[i] = new Vector2f(samplePos.get(0) - 0.5f, - samplePos.get(1) - 0.5f); - } - return samplePositions; - } - - public void setMainFrameBufferOverride(FrameBuffer fb) { - mainFbOverride = fb; - } - - public void setFrameBuffer(FrameBuffer fb) { - if (!caps.contains(Caps.FrameBuffer)) { - throw new RendererException("Framebuffer objects are not supported" + - " by the video hardware"); - } - - if (fb == null && mainFbOverride != null) { - fb = mainFbOverride; - } - - if (context.boundFB == fb) { - if (fb == null || !fb.isUpdateNeeded()) { - return; - } - } - - // generate mipmaps for last FB if needed - if (context.boundFB != null) { - for (int i = 0; i < context.boundFB.getNumColorBuffers(); i++) { - RenderBuffer rb = context.boundFB.getColorBuffer(i); - Texture tex = rb.getTexture(); - if (tex != null - && tex.getMinFilter().usesMipMapLevels()) { - setTexture(0, rb.getTexture()); - - int textureType = convertTextureType(tex.getType(), tex.getImage().getMultiSamples(), rb.getFace()); - glEnable(textureType); - glGenerateMipmapEXT(textureType); - glDisable(textureType); - } - } - } - - if (fb == null) { - // unbind any fbos - if (context.boundFBO != 0) { - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); - statistics.onFrameBufferUse(null, true); - - context.boundFBO = 0; - } - // select back buffer - if (context.boundDrawBuf != -1) { - glDrawBuffer(context.initialDrawBuf); - context.boundDrawBuf = -1; - } - if (context.boundReadBuf != -1) { - glReadBuffer(context.initialReadBuf); - context.boundReadBuf = -1; - } - - context.boundFB = null; - } else { - if (fb.getNumColorBuffers() == 0 && fb.getDepthBuffer() == null) { - throw new IllegalArgumentException("The framebuffer: " + fb - + "\nDoesn't have any color/depth buffers"); - } - - if (fb.isUpdateNeeded()) { - updateFrameBuffer(fb); - } - - if (context.boundFBO != fb.getId()) { - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb.getId()); - statistics.onFrameBufferUse(fb, true); - - // update viewport to reflect framebuffer's resolution - setViewPort(0, 0, fb.getWidth(), fb.getHeight()); - - context.boundFBO = fb.getId(); - } else { - statistics.onFrameBufferUse(fb, false); - } - if (fb.getNumColorBuffers() == 0) { - // make sure to select NONE as draw buf - // no color buffer attached. select NONE - if (context.boundDrawBuf != -2) { - glDrawBuffer(GL_NONE); - context.boundDrawBuf = -2; - } - if (context.boundReadBuf != -2) { - glReadBuffer(GL_NONE); - context.boundReadBuf = -2; - } - } else { - if (fb.getNumColorBuffers() > maxFBOAttachs) { - throw new RendererException("Framebuffer has more color " - + "attachments than are supported" - + " by the video hardware!"); - } - if (fb.isMultiTarget()) { - if (fb.getNumColorBuffers() > maxMRTFBOAttachs) { - throw new RendererException("Framebuffer has more" - + " multi targets than are supported" - + " by the video hardware!"); - } - - if (context.boundDrawBuf != 100 + fb.getNumColorBuffers()) { - intBuf16.clear(); - for (int i = 0; i < fb.getNumColorBuffers(); i++) { - intBuf16.put(GL_COLOR_ATTACHMENT0_EXT + i); - } - - intBuf16.flip(); - glDrawBuffers(intBuf16); - context.boundDrawBuf = 100 + fb.getNumColorBuffers(); - } - } else { - RenderBuffer rb = fb.getColorBuffer(fb.getTargetIndex()); - // select this draw buffer - if (context.boundDrawBuf != rb.getSlot()) { - glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT + rb.getSlot()); - context.boundDrawBuf = rb.getSlot(); - } - } - } - - assert fb.getId() >= 0; - assert context.boundFBO == fb.getId(); - - context.boundFB = fb; - - try { - checkFrameBufferError(); - } catch (IllegalStateException ex) { - logger.log(Level.SEVERE, "=== jMonkeyEngine FBO State ===\n{0}", fb); - printRealFrameBufferInfo(fb); - throw ex; - } - } - } - - public void readFrameBuffer(FrameBuffer fb, ByteBuffer byteBuf) { - if (fb != null) { - RenderBuffer rb = fb.getColorBuffer(); - if (rb == null) { - throw new IllegalArgumentException("Specified framebuffer" - + " does not have a colorbuffer"); - } - - setFrameBuffer(fb); - if (context.boundReadBuf != rb.getSlot()) { - glReadBuffer(GL_COLOR_ATTACHMENT0_EXT + rb.getSlot()); - context.boundReadBuf = rb.getSlot(); - } - } else { - setFrameBuffer(null); - } - - glReadPixels(vpX, vpY, vpW, vpH, /*GL_RGBA*/ GL_BGRA, GL_UNSIGNED_BYTE, byteBuf); - } - - private void deleteRenderBuffer(FrameBuffer fb, RenderBuffer rb) { - intBuf1.put(0, rb.getId()); - glDeleteRenderbuffersEXT(intBuf1); - } - - public void deleteFrameBuffer(FrameBuffer fb) { - if (fb.getId() != -1) { - if (context.boundFBO == fb.getId()) { - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); - context.boundFBO = 0; - } - - if (fb.getDepthBuffer() != null) { - deleteRenderBuffer(fb, fb.getDepthBuffer()); - } - if (fb.getColorBuffer() != null) { - deleteRenderBuffer(fb, fb.getColorBuffer()); - } - - intBuf1.put(0, fb.getId()); - glDeleteFramebuffersEXT(intBuf1); - fb.resetObject(); - - statistics.onDeleteFrameBuffer(); - } - } - - /*********************************************************************\ - |* Textures *| - \*********************************************************************/ - private int convertTextureType(Texture.Type type, int samples, int face) { - if (samples > 1 && !caps.contains(Caps.TextureMultisample)) { - throw new RendererException("Multisample textures are not supported" + - " by the video hardware."); - } - - switch (type) { - case TwoDimensional: - if (samples > 1) { - return GL_TEXTURE_2D_MULTISAMPLE; - } else { - return GL_TEXTURE_2D; - } - case TwoDimensionalArray: - if (samples > 1) { - return GL_TEXTURE_2D_MULTISAMPLE_ARRAY; - } else { - return GL_TEXTURE_2D_ARRAY_EXT; - } - case ThreeDimensional: - return GL_TEXTURE_3D; - case CubeMap: - if (face < 0) { - return GL_TEXTURE_CUBE_MAP; - } else if (face < 6) { - return GL_TEXTURE_CUBE_MAP_POSITIVE_X + face; - } else { - throw new UnsupportedOperationException("Invalid cube map face index: " + face); - } - default: - throw new UnsupportedOperationException("Unknown texture type: " + type); - } - } - - private int convertMagFilter(Texture.MagFilter filter) { - switch (filter) { - case Bilinear: - return GL_LINEAR; - case Nearest: - return GL_NEAREST; - default: - throw new UnsupportedOperationException("Unknown mag filter: " + filter); - } - } - - private int convertMinFilter(Texture.MinFilter filter, boolean haveMips) { - if (haveMips){ - switch (filter) { - case Trilinear: - return GL_LINEAR_MIPMAP_LINEAR; - case BilinearNearestMipMap: - return GL_LINEAR_MIPMAP_NEAREST; - case NearestLinearMipMap: - return GL_NEAREST_MIPMAP_LINEAR; - case NearestNearestMipMap: - return GL_NEAREST_MIPMAP_NEAREST; - case BilinearNoMipMaps: - return GL_LINEAR; - case NearestNoMipMaps: - return GL_NEAREST; - default: - throw new UnsupportedOperationException("Unknown min filter: " + filter); - } - } else { - switch (filter) { - case Trilinear: - case BilinearNearestMipMap: - case BilinearNoMipMaps: - return GL_LINEAR; - case NearestLinearMipMap: - case NearestNearestMipMap: - case NearestNoMipMaps: - return GL_NEAREST; - default: - throw new UnsupportedOperationException("Unknown min filter: " + filter); - } - } - } - - private int convertWrapMode(Texture.WrapMode mode) { - switch (mode) { - case BorderClamp: - return GL_CLAMP_TO_BORDER; - case Clamp: - // Falldown intentional. - case EdgeClamp: - return GL_CLAMP_TO_EDGE; - case Repeat: - return GL_REPEAT; - case MirroredRepeat: - return GL_MIRRORED_REPEAT; - default: - throw new UnsupportedOperationException("Unknown wrap mode: " + mode); - } - } - - @SuppressWarnings("fallthrough") - private void setupTextureParams(Texture tex) { - Image image = tex.getImage(); - int target = convertTextureType(tex.getType(), image != null ? image.getMultiSamples() : 1, -1); - - boolean haveMips = true; - - if (image != null) { - haveMips = image.isGeneratedMipmapsRequired() || image.hasMipmaps(); - } - - // filter things - int minFilter = convertMinFilter(tex.getMinFilter(), haveMips); - int magFilter = convertMagFilter(tex.getMagFilter()); - glTexParameteri(target, GL_TEXTURE_MIN_FILTER, minFilter); - glTexParameteri(target, GL_TEXTURE_MAG_FILTER, magFilter); - - if (tex.getAnisotropicFilter() > 1) { - if (caps.contains(Caps.TextureFilterAnisotropic)) { - glTexParameterf(target, - GL_TEXTURE_MAX_ANISOTROPY_EXT, - tex.getAnisotropicFilter()); - } - } - - if (context.pointSprite) { - return; // Attempt to fix glTexParameter crash for some ATI GPUs - } - - // repeat modes - switch (tex.getType()) { - case ThreeDimensional: - case CubeMap: // cubemaps use 3D coords - glTexParameteri(target, GL_TEXTURE_WRAP_R, convertWrapMode(tex.getWrap(WrapAxis.R))); - //There is no break statement on purpose here - case TwoDimensional: - case TwoDimensionalArray: - glTexParameteri(target, GL_TEXTURE_WRAP_T, convertWrapMode(tex.getWrap(WrapAxis.T))); - // fall down here is intentional.. -// case OneDimensional: - glTexParameteri(target, GL_TEXTURE_WRAP_S, convertWrapMode(tex.getWrap(WrapAxis.S))); - break; - default: - throw new UnsupportedOperationException("Unknown texture type: " + tex.getType()); - } - - if(tex.isNeedCompareModeUpdate()){ - // R to Texture compare mode - if (tex.getShadowCompareMode() != Texture.ShadowCompareMode.Off) { - glTexParameteri(target, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE); - glTexParameteri(target, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY); - if (tex.getShadowCompareMode() == Texture.ShadowCompareMode.GreaterOrEqual) { - glTexParameteri(target, GL_TEXTURE_COMPARE_FUNC, GL_GEQUAL); - } else { - glTexParameteri(target, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); - } - }else{ - //restoring default value - glTexParameteri(target, GL_TEXTURE_COMPARE_MODE, GL_NONE); - } - tex.compareModeUpdated(); - } - } - - /** - * Uploads the given image to the GL driver. - * - * @param img The image to upload - * @param type How the data in the image argument should be interpreted. - * @param unit The texture slot to be used to upload the image, not important - */ - public void updateTexImageData(Image img, Texture.Type type, int unit) { - int texId = img.getId(); - if (texId == -1) { - // create texture - glGenTextures(intBuf1); - texId = intBuf1.get(0); - img.setId(texId); - objManager.registerObject(img); - - statistics.onNewTexture(); - } - - // bind texture - int target = convertTextureType(type, img.getMultiSamples(), -1); - if (context.boundTextureUnit != unit) { - glActiveTexture(GL_TEXTURE0 + unit); - context.boundTextureUnit = unit; - } - if (context.boundTextures[unit] != img) { - glBindTexture(target, texId); - context.boundTextures[unit] = img; - - statistics.onTextureUse(img, true); - } - - if (!img.hasMipmaps() && img.isGeneratedMipmapsRequired()) { - // Image does not have mipmaps, but they are required. - // Generate from base level. - - if (!caps.contains(Caps.OpenGL30) && !caps.contains(Caps.OpenGLES20)) { - glTexParameteri(target, GL_GENERATE_MIPMAP, GL_TRUE); - img.setMipmapsGenerated(true); - } else { - // For OpenGL3 and up. - // We'll generate mipmaps via glGenerateMipmapEXT (see below) - } - } else if (img.hasMipmaps()) { - // Image already has mipmaps, set the max level based on the - // number of mipmaps we have. - glTexParameteri(target, GL_TEXTURE_MAX_LEVEL, img.getMipMapSizes().length - 1); - } else { - // Image does not have mipmaps and they are not required. - // Specify that that the texture has no mipmaps. - glTexParameteri(target, GL_TEXTURE_MAX_LEVEL, 0); - } - - int imageSamples = img.getMultiSamples(); - if (imageSamples > 1) { - if (img.getFormat().isDepthFormat()) { - img.setMultiSamples(Math.min(maxDepthTexSamples, imageSamples)); - } else { - img.setMultiSamples(Math.min(maxColorTexSamples, imageSamples)); - } - } - - // Yes, some OpenGL2 cards (GeForce 5) still dont support NPOT. - if (!caps.contains(Caps.NonPowerOfTwoTextures) && img.isNPOT()) { - if (img.getData(0) == null) { - throw new RendererException("non-power-of-2 framebuffer textures are not supported by the video hardware"); - } else { - MipMapGenerator.resizeToPowerOf2(img); - } - } - - // Check if graphics card doesn't support multisample textures - if (!caps.contains(Caps.TextureMultisample)) { - if (img.getMultiSamples() > 1) { - throw new RendererException("Multisample textures not supported by graphics hardware"); - } - } - - if (target == GL_TEXTURE_CUBE_MAP) { - // Check max texture size before upload - if (img.getWidth() > maxCubeTexSize || img.getHeight() > maxCubeTexSize) { - throw new RendererException("Cannot upload cubemap " + img + ". The maximum supported cubemap resolution is " + maxCubeTexSize); - } - if (img.getWidth() != img.getHeight()) { - throw new RendererException("Cubemaps must have square dimensions"); - } - } else { - if (img.getWidth() > maxTexSize || img.getHeight() > maxTexSize) { - throw new RendererException("Cannot upload texture " + img + ". The maximum supported texture resolution is " + maxTexSize); - } - } - - if (target == GL_TEXTURE_CUBE_MAP) { - List data = img.getData(); - if (data.size() != 6) { - logger.log(Level.WARNING, "Invalid texture: {0}\n" - + "Cubemap textures must contain 6 data units.", img); - return; - } - for (int i = 0; i < 6; i++) { - TextureUtil.uploadTexture(caps, img, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, i, 0, linearizeSrgbImages); - } - } else if (target == GL_TEXTURE_2D_ARRAY_EXT) { - if (!caps.contains(Caps.TextureArray)) { - throw new RendererException("Texture arrays not supported by graphics hardware"); - } - - List data = img.getData(); - - // -1 index specifies prepare data for 2D Array - TextureUtil.uploadTexture(caps, img, target, -1, 0, linearizeSrgbImages); - - for (int i = 0; i < data.size(); i++) { - // upload each slice of 2D array in turn - // this time with the appropriate index - TextureUtil.uploadTexture(caps, img, target, i, 0, linearizeSrgbImages); - } - } else { - TextureUtil.uploadTexture(caps, img, target, 0, 0, linearizeSrgbImages); - } - - if (img.getMultiSamples() != imageSamples) { - img.setMultiSamples(imageSamples); - } - - if (caps.contains(Caps.OpenGL30)) { - if (!img.hasMipmaps() && img.isGeneratedMipmapsRequired() && img.getData() != null) { - // XXX: Required for ATI - glEnable(target); - glGenerateMipmapEXT(target); - glDisable(target); - img.setMipmapsGenerated(true); - } - } - - img.clearUpdateNeeded(); - } - - public void setTexture(int unit, Texture tex) { - Image image = tex.getImage(); - if (image.isUpdateNeeded() || (image.isGeneratedMipmapsRequired() && !image.isMipmapsGenerated())) { - updateTexImageData(image, tex.getType(), unit); - } - - int texId = image.getId(); - assert texId != -1; - - Image[] textures = context.boundTextures; - - int type = convertTextureType(tex.getType(), image.getMultiSamples(), -1); -// if (!context.textureIndexList.moveToNew(unit)) { -// if (context.boundTextureUnit != unit){ -// glActiveTexture(GL_TEXTURE0 + unit); -// context.boundTextureUnit = unit; -// } -// glEnable(type); -// } - - if (context.boundTextureUnit != unit) { - glActiveTexture(GL_TEXTURE0 + unit); - context.boundTextureUnit = unit; - } - if (textures[unit] != image) { - glBindTexture(type, texId); - textures[unit] = image; - - statistics.onTextureUse(image, true); - } else { - statistics.onTextureUse(image, false); - } - - setupTextureParams(tex); - } - - public void modifyTexture(Texture tex, Image pixels, int x, int y) { - setTexture(0, tex); - TextureUtil.uploadSubTexture(caps, pixels, convertTextureType(tex.getType(), pixels.getMultiSamples(), -1), 0, x, y, linearizeSrgbImages); - } - - public void clearTextureUnits() { -// IDList textureList = context.textureIndexList; -// Image[] textures = context.boundTextures; -// for (int i = 0; i < textureList.oldLen; i++) { -// int idx = textureList.oldList[i]; -// if (context.boundTextureUnit != idx){ -// glActiveTexture(GL_TEXTURE0 + idx); -// context.boundTextureUnit = idx; -// } -// glDisable(convertTextureType(textures[idx].getType())); -// textures[idx] = null; -// } -// context.textureIndexList.copyNewToOld(); - } - - public void deleteImage(Image image) { - int texId = image.getId(); - if (texId != -1) { - intBuf1.put(0, texId); - intBuf1.position(0).limit(1); - glDeleteTextures(intBuf1); - image.resetObject(); - - statistics.onDeleteTexture(); - } - } - - /*********************************************************************\ - |* Vertex Buffers and Attributes *| - \*********************************************************************/ - private int convertUsage(Usage usage) { - switch (usage) { - case Static: - return GL_STATIC_DRAW; - case Dynamic: - return GL_DYNAMIC_DRAW; - case Stream: - return GL_STREAM_DRAW; - default: - throw new UnsupportedOperationException("Unknown usage type."); - } - } - - private int convertFormat(Format format) { - switch (format) { - case Byte: - return GL_BYTE; - case UnsignedByte: - return GL_UNSIGNED_BYTE; - case Short: - return GL_SHORT; - case UnsignedShort: - return GL_UNSIGNED_SHORT; - case Int: - return GL_INT; - case UnsignedInt: - return GL_UNSIGNED_INT; - case Float: - return GL_FLOAT; - case Double: - return GL_DOUBLE; - default: - throw new UnsupportedOperationException("Unknown buffer format."); - - } - } - - public void updateBufferData(VertexBuffer vb) { - int bufId = vb.getId(); - boolean created = false; - if (bufId == -1) { - // create buffer - glGenBuffers(intBuf1); - bufId = intBuf1.get(0); - vb.setId(bufId); - objManager.registerObject(vb); - - //statistics.onNewVertexBuffer(); - - created = true; - } - - // bind buffer - int target; - if (vb.getBufferType() == VertexBuffer.Type.Index) { - target = GL_ELEMENT_ARRAY_BUFFER; - if (context.boundElementArrayVBO != bufId) { - glBindBuffer(target, bufId); - context.boundElementArrayVBO = bufId; - //statistics.onVertexBufferUse(vb, true); - } else { - //statistics.onVertexBufferUse(vb, false); - } - } else { - target = GL_ARRAY_BUFFER; - if (context.boundArrayVBO != bufId) { - glBindBuffer(target, bufId); - context.boundArrayVBO = bufId; - //statistics.onVertexBufferUse(vb, true); - } else { - //statistics.onVertexBufferUse(vb, false); - } - } - - int usage = convertUsage(vb.getUsage()); - vb.getData().rewind(); - - if (created || vb.hasDataSizeChanged()) { - // upload data based on format - switch (vb.getFormat()) { - case Byte: - case UnsignedByte: - glBufferData(target, (ByteBuffer) vb.getData(), usage); - break; - // case Half: - case Short: - case UnsignedShort: - glBufferData(target, (ShortBuffer) vb.getData(), usage); - break; - case Int: - case UnsignedInt: - glBufferData(target, (IntBuffer) vb.getData(), usage); - break; - case Float: - glBufferData(target, (FloatBuffer) vb.getData(), usage); - break; - case Double: - glBufferData(target, (DoubleBuffer) vb.getData(), usage); - break; - default: - throw new UnsupportedOperationException("Unknown buffer format."); - } - } else { - // Invalidate buffer data (orphan) before uploading new data. - - - switch (vb.getFormat()) { - case Byte: - case UnsignedByte: - glBufferSubData(target, 0, (ByteBuffer) vb.getData()); - break; - case Short: - case UnsignedShort: - glBufferSubData(target, 0, (ShortBuffer) vb.getData()); - break; - case Int: - case UnsignedInt: - glBufferSubData(target, 0, (IntBuffer) vb.getData()); - break; - case Float: - glBufferSubData(target, 0, (FloatBuffer) vb.getData()); - break; - case Double: - glBufferSubData(target, 0, (DoubleBuffer) vb.getData()); - break; - default: - throw new UnsupportedOperationException("Unknown buffer format."); - } - } - - vb.clearUpdateNeeded(); - } - - public void deleteBuffer(VertexBuffer vb) { - int bufId = vb.getId(); - if (bufId != -1) { - // delete buffer - intBuf1.put(0, bufId); - intBuf1.position(0).limit(1); - glDeleteBuffers(intBuf1); - vb.resetObject(); - - //statistics.onDeleteVertexBuffer(); - } - } - - public void clearVertexAttribs() { - IDList attribList = context.attribIndexList; - for (int i = 0; i < attribList.oldLen; i++) { - int idx = attribList.oldList[i]; - glDisableVertexAttribArray(idx); - if (context.boundAttribs[idx].isInstanced()) { - glVertexAttribDivisorARB(idx, 0); - } - context.boundAttribs[idx] = null; - } - context.attribIndexList.copyNewToOld(); - } - - public void setVertexAttrib(VertexBuffer vb, VertexBuffer idb) { - if (vb.getBufferType() == VertexBuffer.Type.Index) { - throw new IllegalArgumentException("Index buffers not allowed to be set to vertex attrib"); - } - - int programId = context.boundShaderProgram; - - if (programId > 0) { - Attribute attrib = context.boundShader.getAttribute(vb.getBufferType()); - int loc = attrib.getLocation(); - if (loc == -1) { - return; // not defined - } - if (loc == -2) { - stringBuf.setLength(0); - stringBuf.append("in").append(vb.getBufferType().name()).append('\0'); - updateNameBuffer(); - loc = glGetAttribLocation(programId, nameBuf); - - // not really the name of it in the shader (inPosition\0) but - // the internal name of the enum (Position). - if (loc < 0) { - attrib.setLocation(-1); - return; // not available in shader. - } else { - attrib.setLocation(loc); - } - } - - if (vb.isInstanced()) { - if (!caps.contains(Caps.MeshInstancing)) { - throw new RendererException("Instancing is required, " - + "but not supported by the " - + "graphics hardware"); - } - } - int slotsRequired = 1; - if (vb.getNumComponents() > 4) { - if (vb.getNumComponents() % 4 != 0) { - throw new RendererException("Number of components in multi-slot " - + "buffers must be divisible by 4"); - } - slotsRequired = vb.getNumComponents() / 4; - } - - if (vb.isUpdateNeeded() && idb == null) { - updateBufferData(vb); - } - - VertexBuffer[] attribs = context.boundAttribs; - for (int i = 0; i < slotsRequired; i++) { - if (!context.attribIndexList.moveToNew(loc + i)) { - glEnableVertexAttribArray(loc + i); - //System.out.println("Enabled ATTRIB IDX: "+loc); - } - } - if (attribs[loc] != vb) { - // NOTE: Use id from interleaved buffer if specified - int bufId = idb != null ? idb.getId() : vb.getId(); - assert bufId != -1; - if (context.boundArrayVBO != bufId) { - glBindBuffer(GL_ARRAY_BUFFER, bufId); - context.boundArrayVBO = bufId; - //statistics.onVertexBufferUse(vb, true); - } else { - //statistics.onVertexBufferUse(vb, false); - } - - if (slotsRequired == 1) { - glVertexAttribPointer(loc, - vb.getNumComponents(), - convertFormat(vb.getFormat()), - vb.isNormalized(), - vb.getStride(), - vb.getOffset()); - } else { - for (int i = 0; i < slotsRequired; i++) { - // The pointer maps the next 4 floats in the slot. - // E.g. - // P1: XXXX____________XXXX____________ - // P2: ____XXXX____________XXXX________ - // P3: ________XXXX____________XXXX____ - // P4: ____________XXXX____________XXXX - // stride = 4 bytes in float * 4 floats in slot * num slots - // offset = 4 bytes in float * 4 floats in slot * slot index - glVertexAttribPointer(loc + i, - 4, - convertFormat(vb.getFormat()), - vb.isNormalized(), - 4 * 4 * slotsRequired, - 4 * 4 * i); - } - } - - for (int i = 0; i < slotsRequired; i++) { - int slot = loc + i; - if (vb.isInstanced() && (attribs[slot] == null || !attribs[slot].isInstanced())) { - // non-instanced -> instanced - glVertexAttribDivisorARB(slot, vb.getInstanceSpan()); - } else if (!vb.isInstanced() && attribs[slot] != null && attribs[slot].isInstanced()) { - // instanced -> non-instanced - glVertexAttribDivisorARB(slot, 0); - } - attribs[slot] = vb; - } - } - } else { - throw new IllegalStateException("Cannot render mesh without shader bound"); - } - } - - public void setVertexAttrib(VertexBuffer vb) { - setVertexAttrib(vb, null); - } - - public void drawTriangleArray(Mesh.Mode mode, int count, int vertCount) { - boolean useInstancing = count > 1 && caps.contains(Caps.MeshInstancing); - if (useInstancing) { - glDrawArraysInstancedARB(convertElementMode(mode), 0, - vertCount, count); - } else { - glDrawArrays(convertElementMode(mode), 0, vertCount); - } - } - - public void drawTriangleList(VertexBuffer indexBuf, Mesh mesh, int count) { - if (indexBuf.getBufferType() != VertexBuffer.Type.Index) { - throw new IllegalArgumentException("Only index buffers are allowed as triangle lists."); - } - - if (indexBuf.isUpdateNeeded()) { - updateBufferData(indexBuf); - } - - int bufId = indexBuf.getId(); - assert bufId != -1; - - if (context.boundElementArrayVBO != bufId) { - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufId); - context.boundElementArrayVBO = bufId; - //statistics.onVertexBufferUse(indexBuf, true); - } else { - //statistics.onVertexBufferUse(indexBuf, true); - } - - int vertCount = mesh.getVertexCount(); - boolean useInstancing = count > 1 && caps.contains(Caps.MeshInstancing); - - if (mesh.getMode() == Mode.Hybrid) { - int[] modeStart = mesh.getModeStart(); - int[] elementLengths = mesh.getElementLengths(); - - int elMode = convertElementMode(Mode.Triangles); - int fmt = convertFormat(indexBuf.getFormat()); - int elSize = indexBuf.getFormat().getComponentSize(); - int listStart = modeStart[0]; - int stripStart = modeStart[1]; - int fanStart = modeStart[2]; - int curOffset = 0; - for (int i = 0; i < elementLengths.length; i++) { - if (i == stripStart) { - elMode = convertElementMode(Mode.TriangleStrip); - } else if (i == fanStart) { - elMode = convertElementMode(Mode.TriangleFan); - } - int elementLength = elementLengths[i]; - - if (useInstancing) { - glDrawElementsInstancedARB(elMode, - elementLength, - fmt, - curOffset, - count); - } else { - glDrawRangeElements(elMode, - 0, - vertCount, - elementLength, - fmt, - curOffset); - } - - curOffset += elementLength * elSize; - } - } else { - if (useInstancing) { - glDrawElementsInstancedARB(convertElementMode(mesh.getMode()), - indexBuf.getData().limit(), - convertFormat(indexBuf.getFormat()), - 0, - count); - } else { - glDrawRangeElements(convertElementMode(mesh.getMode()), - 0, - vertCount, - indexBuf.getData().limit(), - convertFormat(indexBuf.getFormat()), - 0); - } - } - } - - /*********************************************************************\ - |* Render Calls *| - \*********************************************************************/ - public int convertElementMode(Mesh.Mode mode) { - switch (mode) { - case Points: - return GL_POINTS; - case Lines: - return GL_LINES; - case LineLoop: - return GL_LINE_LOOP; - case LineStrip: - return GL_LINE_STRIP; - case Triangles: - return GL_TRIANGLES; - case TriangleFan: - return GL_TRIANGLE_FAN; - case TriangleStrip: - return GL_TRIANGLE_STRIP; - default: - throw new UnsupportedOperationException("Unrecognized mesh mode: " + mode); - } - } - - public void updateVertexArray(Mesh mesh, VertexBuffer instanceData) { - int id = mesh.getId(); - if (id == -1) { - IntBuffer temp = intBuf1; - glGenVertexArrays(temp); - id = temp.get(0); - mesh.setId(id); - } - - if (context.boundVertexArray != id) { - glBindVertexArray(id); - context.boundVertexArray = id; - } - - VertexBuffer interleavedData = mesh.getBuffer(Type.InterleavedData); - if (interleavedData != null && interleavedData.isUpdateNeeded()) { - updateBufferData(interleavedData); - } - - if (instanceData != null) { - setVertexAttrib(instanceData, null); - } - - for (VertexBuffer vb : mesh.getBufferList().getArray()) { - if (vb.getBufferType() == Type.InterleavedData - || vb.getUsage() == Usage.CpuOnly // ignore cpu-only buffers - || vb.getBufferType() == Type.Index) { - continue; - } - - if (vb.getStride() == 0) { - // not interleaved - setVertexAttrib(vb); - } else { - // interleaved - setVertexAttrib(vb, interleavedData); - } - } - } - - private void renderMeshVertexArray(Mesh mesh, int lod, int count, VertexBuffer instanceData) { - if (mesh.getId() == -1) { - updateVertexArray(mesh, instanceData); - } else { - // TODO: Check if it was updated - } - - if (context.boundVertexArray != mesh.getId()) { - glBindVertexArray(mesh.getId()); - context.boundVertexArray = mesh.getId(); - } - -// IntMap buffers = mesh.getBuffers(); - VertexBuffer indices; - if (mesh.getNumLodLevels() > 0) { - indices = mesh.getLodLevel(lod); - } else { - indices = mesh.getBuffer(Type.Index); - } - if (indices != null) { - drawTriangleList(indices, mesh, count); - } else { - drawTriangleArray(mesh.getMode(), count, mesh.getVertexCount()); - } - clearVertexAttribs(); - clearTextureUnits(); - } - - private void renderMeshDefault(Mesh mesh, int lod, int count, VertexBuffer[] instanceData) { - - // Here while count is still passed in. Can be removed when/if - // the method is collapsed again. -pspeed - count = Math.max(mesh.getInstanceCount(), count); - - VertexBuffer interleavedData = mesh.getBuffer(Type.InterleavedData); - if (interleavedData != null && interleavedData.isUpdateNeeded()) { - updateBufferData(interleavedData); - } - - VertexBuffer indices; - if (mesh.getNumLodLevels() > 0) { - indices = mesh.getLodLevel(lod); - } else { - indices = mesh.getBuffer(Type.Index); - } - - if (instanceData != null) { - for (VertexBuffer vb : instanceData) { - setVertexAttrib(vb, null); - } - } - - for (VertexBuffer vb : mesh.getBufferList().getArray()) { - if (vb.getBufferType() == Type.InterleavedData - || vb.getUsage() == Usage.CpuOnly // ignore cpu-only buffers - || vb.getBufferType() == Type.Index) { - continue; - } - - if (vb.getStride() == 0) { - // not interleaved - setVertexAttrib(vb); - } else { - // interleaved - setVertexAttrib(vb, interleavedData); - } - } - - if (indices != null) { - drawTriangleList(indices, mesh, count); - } else { - drawTriangleArray(mesh.getMode(), count, mesh.getVertexCount()); - } - clearVertexAttribs(); - clearTextureUnits(); - } - - public void renderMesh(Mesh mesh, int lod, int count, VertexBuffer[] instanceData) { - if (mesh.getVertexCount() == 0) { - return; - } - - if (context.pointSprite && mesh.getMode() != Mode.Points) { - // XXX: Hack, disable point sprite mode if mesh not in point mode - if (context.boundTextures[0] != null) { - if (context.boundTextureUnit != 0) { - glActiveTexture(GL_TEXTURE0); - context.boundTextureUnit = 0; - } - glDisable(GL_POINT_SPRITE); - glDisable(GL_VERTEX_PROGRAM_POINT_SIZE); - context.pointSprite = false; - } - } - - if (context.pointSize != mesh.getPointSize()) { - glPointSize(mesh.getPointSize()); - context.pointSize = mesh.getPointSize(); - } - if (context.lineWidth != mesh.getLineWidth()) { - glLineWidth(mesh.getLineWidth()); - context.lineWidth = mesh.getLineWidth(); - } - - statistics.onMeshDrawn(mesh, lod, count); -// if (ctxCaps.GL_ARB_vertex_array_object){ -// renderMeshVertexArray(mesh, lod, count); -// }else{ - renderMeshDefault(mesh, lod, count, instanceData); -// } - } - - public void setMainFrameBufferSrgb(boolean enableSrgb) { - // Gamma correction - - if (!caps.contains(Caps.Srgb)) { - // Not supported, sorry. - - logger.warning("sRGB framebuffer is not supported " + - "by video hardware, but was requested."); - - return; - } - - setFrameBuffer(null); - - if (enableSrgb) { - if (!glGetBoolean(GL_FRAMEBUFFER_SRGB_CAPABLE_EXT)) { - logger.warning("Driver claims that default framebuffer " - + "is not sRGB capable. Enabling anyway."); - } - - - - glEnable(GL_FRAMEBUFFER_SRGB_EXT); - - logger.log(Level.FINER, "SRGB FrameBuffer enabled (Gamma Correction)"); - } else { - glDisable(GL_FRAMEBUFFER_SRGB_EXT); - } - } - - public void setLinearizeSrgbImages(boolean linearize) { - if (caps.contains(Caps.Srgb)) { - linearizeSrgbImages = linearize; - } - } -} diff --git a/jme3-lwjgl/src/main/java/com/jme3/renderer/lwjgl/TextureUtil.java b/jme3-lwjgl/src/main/java/com/jme3/renderer/lwjgl/TextureUtil.java deleted file mode 100644 index 41dddd6ae..000000000 --- a/jme3-lwjgl/src/main/java/com/jme3/renderer/lwjgl/TextureUtil.java +++ /dev/null @@ -1,514 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package com.jme3.renderer.lwjgl; - -import com.jme3.renderer.Caps; -import com.jme3.renderer.RendererException; -import com.jme3.texture.Image; -import com.jme3.texture.Image.Format; -import com.jme3.texture.image.ColorSpace; -import java.nio.ByteBuffer; -import java.util.EnumSet; -import java.util.logging.Level; -import java.util.logging.Logger; -import static org.lwjgl.opengl.ARBDepthBufferFloat.*; -import static org.lwjgl.opengl.ARBES3Compatibility.*; -import static org.lwjgl.opengl.ARBHalfFloatPixel.*; -import static org.lwjgl.opengl.ARBTextureFloat.*; -import static org.lwjgl.opengl.ARBTextureMultisample.*; -import static org.lwjgl.opengl.EXTPackedDepthStencil.*; -import static org.lwjgl.opengl.EXTPackedFloat.*; -import static org.lwjgl.opengl.EXTTextureArray.*; -import static org.lwjgl.opengl.EXTTextureCompressionS3TC.*; -import static org.lwjgl.opengl.EXTTextureSRGB.*; -import static org.lwjgl.opengl.EXTTextureSharedExponent.*; -import static org.lwjgl.opengl.GL11.*; -import static org.lwjgl.opengl.GL12.*; -import static org.lwjgl.opengl.GL13.*; -import static org.lwjgl.opengl.GL14.*; - -/** - * - * Should not be used, has been replaced by Unified Rendering Architechture. - * @deprecated - */ -@Deprecated -class TextureUtil { - - static class GLImageFormat { - - int internalFormat; - int format; - int dataType; - boolean compressed; - - public GLImageFormat(int internalFormat, int format, int dataType, boolean compressed) { - this.internalFormat = internalFormat; - this.format = format; - this.dataType = dataType; - this.compressed = compressed; - } - } - - private static final GLImageFormat[] formatToGL = new GLImageFormat[Format.values().length]; - - private static void setFormat(Format format, int glInternalFormat, int glFormat, int glDataType, boolean glCompressed){ - formatToGL[format.ordinal()] = new GLImageFormat(glInternalFormat, glFormat, glDataType, glCompressed); - } - - static { - // Alpha formats - setFormat(Format.Alpha8, GL_ALPHA8, GL_ALPHA, GL_UNSIGNED_BYTE, false); - - // Luminance formats - setFormat(Format.Luminance8, GL_LUMINANCE8, GL_LUMINANCE, GL_UNSIGNED_BYTE, false); - setFormat(Format.Luminance16F, GL_LUMINANCE16F_ARB, GL_LUMINANCE, GL_HALF_FLOAT_ARB, false); - setFormat(Format.Luminance32F, GL_LUMINANCE32F_ARB, GL_LUMINANCE, GL_FLOAT, false); - - // Luminance alpha formats - setFormat(Format.Luminance8Alpha8, GL_LUMINANCE8_ALPHA8, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, false); - setFormat(Format.Luminance16FAlpha16F, GL_LUMINANCE_ALPHA16F_ARB, GL_LUMINANCE_ALPHA, GL_HALF_FLOAT_ARB, false); - - // Depth formats - setFormat(Format.Depth, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, false); - setFormat(Format.Depth16, GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, false); - setFormat(Format.Depth24, GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false); - setFormat(Format.Depth32, GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false); - setFormat(Format.Depth32F, GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_FLOAT, false); - - // Depth stencil formats - setFormat(Format.Depth24Stencil8, GL_DEPTH24_STENCIL8_EXT, GL_DEPTH_STENCIL_EXT, GL_UNSIGNED_INT_24_8_EXT, false); - - // RGB formats - setFormat(Format.BGR8, GL_RGB8, GL_BGR, GL_UNSIGNED_BYTE, false); - setFormat(Format.ARGB8, GL_RGBA8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8, false); - setFormat(Format.BGRA8, GL_RGBA8, GL_BGRA, GL_UNSIGNED_BYTE, false); - setFormat(Format.RGB8, GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE, false); - setFormat(Format.RGB16F, GL_RGB16F_ARB, GL_RGB, GL_HALF_FLOAT_ARB, false); - setFormat(Format.RGB32F, GL_RGB32F_ARB, GL_RGB, GL_FLOAT, false); - - // Special RGB formats - setFormat(Format.RGB111110F, GL_R11F_G11F_B10F_EXT, GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV_EXT, false); - setFormat(Format.RGB9E5, GL_RGB9_E5_EXT, GL_RGB, GL_UNSIGNED_INT_5_9_9_9_REV_EXT, false); - setFormat(Format.RGB16F_to_RGB111110F, GL_R11F_G11F_B10F_EXT, GL_RGB, GL_HALF_FLOAT_ARB, false); - setFormat(Format.RGB16F_to_RGB9E5, GL_RGB9_E5_EXT, GL_RGB, GL_HALF_FLOAT_ARB, false); - - // RGBA formats - setFormat(Format.ABGR8, GL_RGBA8, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, false); - setFormat(Format.RGB5A1, GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, false); - setFormat(Format.RGBA8, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, false); - setFormat(Format.RGBA16F, GL_RGBA16F_ARB, GL_RGBA, GL_HALF_FLOAT_ARB, false); - setFormat(Format.RGBA32F, GL_RGBA32F_ARB, GL_RGBA, GL_FLOAT, false); - - // DXT formats - setFormat(Format.DXT1, GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_RGB, GL_UNSIGNED_BYTE, true); - setFormat(Format.DXT1A, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_RGBA, GL_UNSIGNED_BYTE, true); - setFormat(Format.DXT3, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_RGBA, GL_UNSIGNED_BYTE, true); - setFormat(Format.DXT5, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_RGBA, GL_UNSIGNED_BYTE, true); - - // ETC1 support on regular OpenGL requires ES3 compatibility extension. - // NOTE: ETC2 is backwards compatible with ETC1, so we can - // upload ETC1 textures as ETC2. - setFormat(Format.ETC1, GL_COMPRESSED_RGB8_ETC2, GL_RGB, GL_UNSIGNED_BYTE, true); - } - - //sRGB formats - private static final GLImageFormat sRGB_RGB8 = new GLImageFormat(GL_SRGB8_EXT, GL_RGB, GL_UNSIGNED_BYTE, false); - private static final GLImageFormat sRGB_RGBA8 = new GLImageFormat(GL_SRGB8_ALPHA8_EXT, GL_RGBA, GL_UNSIGNED_BYTE, false); - private static final GLImageFormat sRGB_Luminance8 = new GLImageFormat(GL_SLUMINANCE8_EXT, GL_LUMINANCE, GL_UNSIGNED_BYTE, false); - private static final GLImageFormat sRGB_LuminanceAlpha8 = new GLImageFormat(GL_SLUMINANCE8_ALPHA8_EXT, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, false); - private static final GLImageFormat sRGB_BGR8 = new GLImageFormat(GL_SRGB8_EXT, GL_BGR, GL_UNSIGNED_BYTE, false); - private static final GLImageFormat sRGB_ABGR8 = new GLImageFormat(GL_SRGB8_ALPHA8_EXT, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, false); - private static final GLImageFormat sRGB_ARGB8 = new GLImageFormat(GL_SRGB8_ALPHA8_EXT, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8, false); - private static final GLImageFormat sRGB_BGRA8 = new GLImageFormat(GL_SRGB8_ALPHA8_EXT, GL_BGRA, GL_UNSIGNED_BYTE, false); - private static final GLImageFormat sRGB_DXT1 = new GLImageFormat(GL_COMPRESSED_SRGB_S3TC_DXT1_EXT,GL_RGB, GL_UNSIGNED_BYTE, true); - private static final GLImageFormat sRGB_DXT1A = new GLImageFormat(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT, GL_RGBA, GL_UNSIGNED_BYTE, true); - private static final GLImageFormat sRGB_DXT3 = new GLImageFormat(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, GL_RGBA, GL_UNSIGNED_BYTE, true); - private static final GLImageFormat sRGB_DXT5 = new GLImageFormat(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, GL_RGBA, GL_UNSIGNED_BYTE, true); - - public static GLImageFormat getImageFormat(EnumSet caps, Format fmt, boolean isSrgb){ - switch (fmt){ - case ETC1: - if (!caps.contains(Caps.TextureCompressionETC1)) { - return null; - } - break; - case DXT1: - case DXT1A: - case DXT3: - case DXT5: - if (!caps.contains(Caps.TextureCompressionS3TC)) { - return null; - } - break; - case Depth24Stencil8: - if (!caps.contains(Caps.PackedDepthStencilBuffer)){ - return null; - } - break; - case Luminance16F: - case Luminance16FAlpha16F: - case Luminance32F: - case RGB16F: - case RGB32F: - case RGBA16F: - case RGBA32F: - if (!caps.contains(Caps.FloatTexture)){ - return null; - } - break; - case Depth32F: - if (!caps.contains(Caps.FloatDepthBuffer)){ - return null; - } - break; - case RGB9E5: - case RGB16F_to_RGB9E5: - if (!caps.contains(Caps.SharedExponentTexture)){ - return null; - } - break; - case RGB111110F: - case RGB16F_to_RGB111110F: - if (!caps.contains(Caps.PackedFloatTexture)){ - return null; - } - break; - } - if (isSrgb) { - return getSrgbFormat(fmt); - } else { - return formatToGL[fmt.ordinal()]; - } - } - - public static GLImageFormat getImageFormatWithError(EnumSet caps, Format fmt, boolean isSrgb) { - GLImageFormat glFmt = getImageFormat(caps, fmt, isSrgb); - if (glFmt == null) { - throw new RendererException("Image format '" + fmt + "' is unsupported by the video hardware."); - } - return glFmt; - } - - private static GLImageFormat getSrgbFormat(Format fmt){ - switch (fmt) { - case RGB8: - return sRGB_RGB8; - case RGBA8: - return sRGB_RGBA8; - case BGR8: - return sRGB_BGR8; - case ABGR8: - return sRGB_ABGR8; - case ARGB8: - return sRGB_ARGB8; - case BGRA8: - return sRGB_BGRA8; - case Luminance8: - return sRGB_Luminance8; - case Luminance8Alpha8: - return sRGB_LuminanceAlpha8; - case DXT1: - return sRGB_DXT1; - case DXT1A: - return sRGB_DXT1A; - case DXT3: - return sRGB_DXT3; - case DXT5: - return sRGB_DXT5; - default: - Logger.getLogger(TextureUtil.class.getName()).log(Level.WARNING, "Format {0} has no sRGB equivalent, using linear format.", fmt.toString()); - return formatToGL[fmt.ordinal()]; - } - } - - public static void uploadTexture(EnumSet caps, - Image image, - int target, - int index, - int border, - boolean linearizeSrgb){ - - Image.Format fmt = image.getFormat(); - GLImageFormat glFmt = getImageFormatWithError(caps, fmt, image.getColorSpace() == ColorSpace.sRGB && linearizeSrgb); - - ByteBuffer data; - if (index >= 0 && image.getData() != null && image.getData().size() > 0){ - data = image.getData(index); - }else{ - data = null; - } - - int width = image.getWidth(); - int height = image.getHeight(); - int depth = image.getDepth(); - - if (data != null) { - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - } - - int[] mipSizes = image.getMipMapSizes(); - int pos = 0; - // TODO: Remove unneccessary allocation - if (mipSizes == null){ - if (data != null) - mipSizes = new int[]{ data.capacity() }; - else - mipSizes = new int[]{ width * height * fmt.getBitsPerPixel() / 8 }; - } - - boolean subtex = false; - int samples = image.getMultiSamples(); - - for (int i = 0; i < mipSizes.length; i++){ - int mipWidth = Math.max(1, width >> i); - int mipHeight = Math.max(1, height >> i); - int mipDepth = Math.max(1, depth >> i); - - if (data != null){ - data.position(pos); - data.limit(pos + mipSizes[i]); - } - - if (glFmt.compressed && data != null){ - if (target == GL_TEXTURE_3D){ - glCompressedTexImage3D(target, - i, - glFmt.internalFormat, - mipWidth, - mipHeight, - mipDepth, - border, - data); - } else if (target == GL_TEXTURE_2D_ARRAY_EXT) { - // Upload compressed texture array slice - glCompressedTexSubImage3D(target, - i, - 0, - 0, - index, - mipWidth, - mipHeight, - 1, - glFmt.internalFormat, - data); - }else{ - //all other targets use 2D: array, cubemap, 2d - glCompressedTexImage2D(target, - i, - glFmt.internalFormat, - mipWidth, - mipHeight, - border, - data); - } - }else{ - if (target == GL_TEXTURE_3D){ - glTexImage3D(target, - i, - glFmt.internalFormat, - mipWidth, - mipHeight, - mipDepth, - border, - glFmt.format, - glFmt.dataType, - data); - }else if (target == GL_TEXTURE_2D_ARRAY_EXT){ - // prepare data for 2D array - // or upload slice - if (index == -1){ - glTexImage3D(target, - i, - glFmt.internalFormat, - mipWidth, - mipHeight, - image.getData().size(), //# of slices - border, - glFmt.format, - glFmt.dataType, - data); - }else{ - glTexSubImage3D(target, - i, // level - 0, // xoffset - 0, // yoffset - index, // zoffset - mipWidth, // width - mipHeight, // height - 1, // depth - glFmt.format, - glFmt.dataType, - data); - } - }else{ - if (subtex){ - if (samples > 1){ - throw new IllegalStateException("Cannot update multisample textures"); - } - - glTexSubImage2D(target, - i, - 0, 0, - mipWidth, mipHeight, - glFmt.format, - glFmt.dataType, - data); - }else{ - if (samples > 1){ - glTexImage2DMultisample(target, - samples, - glFmt.internalFormat, - mipWidth, - mipHeight, - true); - }else{ - glTexImage2D(target, - i, - glFmt.internalFormat, - mipWidth, - mipHeight, - border, - glFmt.format, - glFmt.dataType, - data); - } - } - } - } - - pos += mipSizes[i]; - } - } - - /** - * Update the texture currently bound to target at with data from the given Image at position x and y. The parameter - * index is used as the zoffset in case a 3d texture or texture 2d array is being updated. - * - * @param image Image with the source data (this data will be put into the texture) - * @param target the target texture - * @param index the mipmap level to update - * @param x the x position where to put the image in the texture - * @param y the y position where to put the image in the texture - */ - public static void uploadSubTexture( - EnumSet caps, - Image image, - int target, - int index, - int x, - int y, - boolean linearizeSrgb) { - Image.Format fmt = image.getFormat(); - GLImageFormat glFmt = getImageFormatWithError(caps, fmt, image.getColorSpace() == ColorSpace.sRGB && linearizeSrgb); - - ByteBuffer data = null; - if (index >= 0 && image.getData() != null && image.getData().size() > 0) { - data = image.getData(index); - } - - int width = image.getWidth(); - int height = image.getHeight(); - int depth = image.getDepth(); - - if (data != null) { - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - } - - int[] mipSizes = image.getMipMapSizes(); - int pos = 0; - - // TODO: Remove unneccessary allocation - if (mipSizes == null){ - if (data != null) { - mipSizes = new int[]{ data.capacity() }; - } else { - mipSizes = new int[]{ width * height * fmt.getBitsPerPixel() / 8 }; - } - } - - int samples = image.getMultiSamples(); - - for (int i = 0; i < mipSizes.length; i++){ - int mipWidth = Math.max(1, width >> i); - int mipHeight = Math.max(1, height >> i); - int mipDepth = Math.max(1, depth >> i); - - if (data != null){ - data.position(pos); - data.limit(pos + mipSizes[i]); - } - - // to remove the cumbersome if/then/else stuff below we'll update the pos right here and use continue after each - // gl*Image call in an attempt to unclutter things a bit - pos += mipSizes[i]; - - int glFmtInternal = glFmt.internalFormat; - int glFmtFormat = glFmt.format; - int glFmtDataType = glFmt.dataType; - - if (glFmt.compressed && data != null){ - if (target == GL_TEXTURE_3D){ - glCompressedTexSubImage3D(target, i, x, y, index, mipWidth, mipHeight, mipDepth, glFmtInternal, data); - continue; - } - - // all other targets use 2D: array, cubemap, 2d - glCompressedTexSubImage2D(target, i, x, y, mipWidth, mipHeight, glFmtInternal, data); - continue; - } - - if (target == GL_TEXTURE_3D){ - glTexSubImage3D(target, i, x, y, index, mipWidth, mipHeight, mipDepth, glFmtFormat, glFmtDataType, data); - continue; - } - - if (target == GL_TEXTURE_2D_ARRAY_EXT){ - // prepare data for 2D array or upload slice - if (index == -1){ - glTexSubImage3D(target, i, x, y, index, mipWidth, mipHeight, mipDepth, glFmtFormat, glFmtDataType, data); - continue; - } - - glTexSubImage3D(target, i, x, y, index, width, height, 1, glFmtFormat, glFmtDataType, data); - continue; - } - - if (samples > 1){ - throw new IllegalStateException("Cannot update multisample textures"); - } - - glTexSubImage2D(target, i, x, y, mipWidth, mipHeight, glFmtFormat, glFmtDataType, data); - } - } -} diff --git a/jme3-lwjgl/src/main/java/com/jme3/system/lwjgl/LwjglAbstractDisplay.java b/jme3-lwjgl/src/main/java/com/jme3/system/lwjgl/LwjglAbstractDisplay.java index ee6a81c53..7cdca0a57 100644 --- a/jme3-lwjgl/src/main/java/com/jme3/system/lwjgl/LwjglAbstractDisplay.java +++ b/jme3-lwjgl/src/main/java/com/jme3/system/lwjgl/LwjglAbstractDisplay.java @@ -181,7 +181,9 @@ public abstract class LwjglAbstractDisplay extends LwjglContext implements Runna // check input after we synchronize with framerate. // this reduces input lag. - Display.processMessages(); + if (renderable.get()){ + Display.processMessages(); + } // Subclasses just call GLObjectManager clean up objects here // it is safe .. for now. diff --git a/jme3-lwjgl/src/main/java/com/jme3/system/lwjgl/LwjglCanvas.java b/jme3-lwjgl/src/main/java/com/jme3/system/lwjgl/LwjglCanvas.java index f1fcc34a2..2452e470b 100644 --- a/jme3-lwjgl/src/main/java/com/jme3/system/lwjgl/LwjglCanvas.java +++ b/jme3-lwjgl/src/main/java/com/jme3/system/lwjgl/LwjglCanvas.java @@ -96,7 +96,7 @@ public class LwjglCanvas extends LwjglAbstractDisplay implements JmeCanvasContex canvas.setFocusable(true); canvas.setIgnoreRepaint(true); - renderThread = new Thread(LwjglCanvas.this, "LWJGL Renderer Thread"); + renderThread = new Thread(LwjglCanvas.this, THREAD_NAME); renderThread.start(); }else if (needClose.get()){ return; @@ -162,7 +162,7 @@ public class LwjglCanvas extends LwjglAbstractDisplay implements JmeCanvasContex if (renderThread == null){ logger.log(Level.FINE, "MAIN: Creating OGL thread."); - renderThread = new Thread(LwjglCanvas.this, "LWJGL Renderer Thread"); + renderThread = new Thread(LwjglCanvas.this, THREAD_NAME); renderThread.start(); } // do not do anything. diff --git a/jme3-lwjgl/src/main/java/com/jme3/system/lwjgl/LwjglContext.java b/jme3-lwjgl/src/main/java/com/jme3/system/lwjgl/LwjglContext.java index e318d24a2..c88f7b734 100644 --- a/jme3-lwjgl/src/main/java/com/jme3/system/lwjgl/LwjglContext.java +++ b/jme3-lwjgl/src/main/java/com/jme3/system/lwjgl/LwjglContext.java @@ -39,13 +39,18 @@ import com.jme3.renderer.Renderer; import com.jme3.renderer.RendererException; import com.jme3.renderer.lwjgl.LwjglGL; import com.jme3.renderer.lwjgl.LwjglGLExt; +import com.jme3.renderer.lwjgl.LwjglGLFboEXT; +import com.jme3.renderer.lwjgl.LwjglGLFboGL3; import com.jme3.renderer.opengl.GL; import com.jme3.renderer.opengl.GL2; import com.jme3.renderer.opengl.GL3; +import com.jme3.renderer.opengl.GL4; import com.jme3.renderer.opengl.GLDebugDesktop; import com.jme3.renderer.opengl.GLExt; import com.jme3.renderer.opengl.GLFbo; import com.jme3.renderer.opengl.GLRenderer; +import com.jme3.renderer.opengl.GLTiming; +import com.jme3.renderer.opengl.GLTimingState; import com.jme3.renderer.opengl.GLTracer; import com.jme3.system.AppSettings; import com.jme3.system.JmeContext; @@ -67,6 +72,8 @@ public abstract class LwjglContext implements JmeContext { private static final Logger logger = Logger.getLogger(LwjglContext.class.getName()); + protected static final String THREAD_NAME = "jME3 Main"; + protected AtomicBoolean created = new AtomicBoolean(false); protected AtomicBoolean renderable = new AtomicBoolean(false); protected final Object createdLock = new Object(); @@ -201,28 +208,44 @@ public abstract class LwjglContext implements JmeContext { } if (settings.getRenderer().equals(AppSettings.LWJGL_OPENGL2) - || settings.getRenderer().equals(AppSettings.LWJGL_OPENGL3)) { + || settings.getRenderer().equals(AppSettings.LWJGL_OPENGL3)) { GL gl = new LwjglGL(); - GLFbo glfbo = new LwjglGLExt(); + GLExt glext = new LwjglGLExt(); + GLFbo glfbo; + + if (GLContext.getCapabilities().OpenGL30) { + glfbo = new LwjglGLFboGL3(); + } else { + glfbo = new LwjglGLFboEXT(); + } if (settings.getBoolean("GraphicsDebug")) { - gl = new GLDebugDesktop(gl, glfbo); + gl = new GLDebugDesktop(gl, glext, glfbo); + glext = (GLExt) gl; glfbo = (GLFbo) gl; } + if (settings.getBoolean("GraphicsTiming")) { + GLTimingState timingState = new GLTimingState(); + gl = (GL) GLTiming.createGLTiming(gl, timingState, GL.class, GL2.class, GL3.class, GL4.class); + glext = (GLExt) GLTiming.createGLTiming(glext, timingState, GLExt.class); + glfbo = (GLFbo) GLTiming.createGLTiming(glfbo, timingState, GLFbo.class); + } + if (settings.getBoolean("GraphicsTrace")) { - gl = (GL) GLTracer.createDesktopGlTracer(gl, GL.class, GL2.class, GL3.class); - glfbo = (GLFbo) GLTracer.createDesktopGlTracer(glfbo, GLExt.class); + gl = (GL) GLTracer.createDesktopGlTracer(gl, GL.class, GL2.class, GL3.class, GL4.class); + glext = (GLExt) GLTracer.createDesktopGlTracer(glext, GLExt.class); + glfbo = (GLFbo) GLTracer.createDesktopGlTracer(glfbo, GLFbo.class); } - renderer = new GLRenderer(gl, glfbo); + renderer = new GLRenderer(gl, glext, glfbo); renderer.initialize(); } else { throw new UnsupportedOperationException("Unsupported renderer: " + settings.getRenderer()); } if (GLContext.getCapabilities().GL_ARB_debug_output && settings.getBoolean("GraphicsDebug")) { - ARBDebugOutput.glDebugMessageCallbackARB(new ARBDebugOutputCallback()); + ARBDebugOutput.glDebugMessageCallbackARB(new ARBDebugOutputCallback(new LwjglGLDebugOutputHandler())); } renderer.setMainFrameBufferSrgb(settings.getGammaCorrection()); diff --git a/jme3-lwjgl/src/main/java/com/jme3/system/lwjgl/LwjglDisplay.java b/jme3-lwjgl/src/main/java/com/jme3/system/lwjgl/LwjglDisplay.java index 4ecfc9a49..853e02933 100644 --- a/jme3-lwjgl/src/main/java/com/jme3/system/lwjgl/LwjglDisplay.java +++ b/jme3-lwjgl/src/main/java/com/jme3/system/lwjgl/LwjglDisplay.java @@ -166,7 +166,7 @@ public class LwjglDisplay extends LwjglAbstractDisplay { return; } - new Thread(this, "LWJGL Renderer Thread").start(); + new Thread(this, THREAD_NAME).start(); if (waitFor) waitFor(true); } diff --git a/jme3-lwjgl/src/main/java/com/jme3/system/lwjgl/LwjglGLDebugOutputHandler.java b/jme3-lwjgl/src/main/java/com/jme3/system/lwjgl/LwjglGLDebugOutputHandler.java new file mode 100644 index 000000000..c8f329f13 --- /dev/null +++ b/jme3-lwjgl/src/main/java/com/jme3/system/lwjgl/LwjglGLDebugOutputHandler.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.system.lwjgl; + +import java.util.HashMap; +import org.lwjgl.opengl.ARBDebugOutput; +import org.lwjgl.opengl.ARBDebugOutputCallback; + +class LwjglGLDebugOutputHandler implements ARBDebugOutputCallback.Handler { + + private static final HashMap constMap = new HashMap(); + private static final String MESSAGE_FORMAT = + "[JME3] OpenGL debug message\r\n" + + " ID: %d\r\n" + + " Source: %s\r\n" + + " Type: %s\r\n" + + " Severity: %s\r\n" + + " Message: %s"; + + static { + constMap.put(ARBDebugOutput.GL_DEBUG_SOURCE_API_ARB, "API"); + constMap.put(ARBDebugOutput.GL_DEBUG_SOURCE_APPLICATION_ARB, "APPLICATION"); + constMap.put(ARBDebugOutput.GL_DEBUG_SOURCE_OTHER_ARB, "OTHER"); + constMap.put(ARBDebugOutput.GL_DEBUG_SOURCE_SHADER_COMPILER_ARB, "SHADER_COMPILER"); + constMap.put(ARBDebugOutput.GL_DEBUG_SOURCE_THIRD_PARTY_ARB, "THIRD_PARTY"); + constMap.put(ARBDebugOutput.GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB, "WINDOW_SYSTEM"); + + constMap.put(ARBDebugOutput.GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB, "DEPRECATED_BEHAVIOR"); + constMap.put(ARBDebugOutput.GL_DEBUG_TYPE_ERROR_ARB, "ERROR"); + constMap.put(ARBDebugOutput.GL_DEBUG_TYPE_OTHER_ARB, "OTHER"); + constMap.put(ARBDebugOutput.GL_DEBUG_TYPE_PERFORMANCE_ARB, "PERFORMANCE"); + constMap.put(ARBDebugOutput.GL_DEBUG_TYPE_PORTABILITY_ARB, "PORTABILITY"); + constMap.put(ARBDebugOutput.GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB, "UNDEFINED_BEHAVIOR"); + + constMap.put(ARBDebugOutput.GL_DEBUG_SEVERITY_HIGH_ARB, "HIGH"); + constMap.put(ARBDebugOutput.GL_DEBUG_SEVERITY_MEDIUM_ARB, "MEDIUM"); + constMap.put(ARBDebugOutput.GL_DEBUG_SEVERITY_LOW_ARB, "LOW"); + } + + @Override + public void handleMessage(int source, int type, int id, int severity, String message) { + String sourceStr = constMap.get(source); + String typeStr = constMap.get(type); + String severityStr = constMap.get(severity); + + System.err.println(String.format(MESSAGE_FORMAT, id, sourceStr, typeStr, severityStr, message)); + } + +} diff --git a/jme3-lwjgl/src/main/java/com/jme3/system/lwjgl/LwjglOffscreenBuffer.java b/jme3-lwjgl/src/main/java/com/jme3/system/lwjgl/LwjglOffscreenBuffer.java index efdb5dfdf..b06db1b29 100644 --- a/jme3-lwjgl/src/main/java/com/jme3/system/lwjgl/LwjglOffscreenBuffer.java +++ b/jme3-lwjgl/src/main/java/com/jme3/system/lwjgl/LwjglOffscreenBuffer.java @@ -170,7 +170,7 @@ public class LwjglOffscreenBuffer extends LwjglContext implements Runnable { return; } - new Thread(this, "LWJGL Renderer Thread").start(); + new Thread(this, THREAD_NAME).start(); if (waitFor) waitFor(true); } diff --git a/jme3-networking/src/main/java/com/jme3/network/Client.java b/jme3-networking/src/main/java/com/jme3/network/Client.java index 6837a4d86..3ef9134df 100644 --- a/jme3-networking/src/main/java/com/jme3/network/Client.java +++ b/jme3-networking/src/main/java/com/jme3/network/Client.java @@ -31,6 +31,8 @@ */ package com.jme3.network; +import com.jme3.network.service.ClientServiceManager; + /** * Represents a remote connection to a server that can be used @@ -53,6 +55,12 @@ public interface Client extends MessageConnection */ public boolean isConnected(); + /** + * Returns true if this client has been started and is still + * running. + */ + public boolean isStarted(); + /** * Returns a unique ID for this client within the remote * server or -1 if this client isn't fully connected to the @@ -72,6 +80,12 @@ public interface Client extends MessageConnection * be able to connect to. */ public int getVersion(); + + /** + * Returns the manager for client services. Client services extend + * the functionality of the client. + */ + public ClientServiceManager getServices(); /** * Sends a message to the server. diff --git a/jme3-networking/src/main/java/com/jme3/network/Server.java b/jme3-networking/src/main/java/com/jme3/network/Server.java index 72926eab7..a52cb33bf 100644 --- a/jme3-networking/src/main/java/com/jme3/network/Server.java +++ b/jme3-networking/src/main/java/com/jme3/network/Server.java @@ -33,6 +33,8 @@ package com.jme3.network; import java.util.Collection; +import com.jme3.network.service.HostedServiceManager; + /** * Represents a host that can send and receive messages to * a set of remote client connections. @@ -54,6 +56,12 @@ public interface Server */ public int getVersion(); + /** + * Returns the manager for hosted services. Hosted services extend + * the functionality of the server. + */ + public HostedServiceManager getServices(); + /** * Sends the specified message to all connected clients. */ diff --git a/jme3-networking/src/main/java/com/jme3/network/base/DefaultClient.java b/jme3-networking/src/main/java/com/jme3/network/base/DefaultClient.java index 54e8fd7f9..b297a933b 100644 --- a/jme3-networking/src/main/java/com/jme3/network/base/DefaultClient.java +++ b/jme3-networking/src/main/java/com/jme3/network/base/DefaultClient.java @@ -37,6 +37,8 @@ import com.jme3.network.kernel.Connector; import com.jme3.network.message.ChannelInfoMessage; import com.jme3.network.message.ClientRegistrationMessage; import com.jme3.network.message.DisconnectMessage; +import com.jme3.network.service.ClientServiceManager; +import com.jme3.network.service.serializer.ClientSerializerRegistrationsService; import java.io.IOException; import java.nio.ByteBuffer; import java.util.*; @@ -54,7 +56,7 @@ import java.util.logging.Logger; */ public class DefaultClient implements Client { - static Logger log = Logger.getLogger(DefaultClient.class.getName()); + static final Logger log = Logger.getLogger(DefaultClient.class.getName()); // First two channels are reserved for reliable and // unreliable. Note: channels are endpoint specific so these @@ -80,10 +82,14 @@ public class DefaultClient implements Client private ConnectorFactory connectorFactory; + private ClientServiceManager services; + public DefaultClient( String gameName, int version ) { this.gameName = gameName; this.version = version; + this.services = new ClientServiceManager(this); + addStandardServices(); } public DefaultClient( String gameName, int version, Connector reliable, Connector fast, @@ -93,6 +99,10 @@ public class DefaultClient implements Client setPrimaryConnectors( reliable, fast, connectorFactory ); } + protected void addStandardServices() { + services.addService(new ClientSerializerRegistrationsService()); + } + protected void setPrimaryConnectors( Connector reliable, Connector fast, ConnectorFactory connectorFactory ) { if( reliable == null ) @@ -167,6 +177,10 @@ public class DefaultClient implements Client continue; send(ch, reg, false); } + } + + public boolean isStarted() { + return isRunning; } protected void waitForConnected() @@ -200,6 +214,11 @@ public class DefaultClient implements Client { return version; } + + public ClientServiceManager getServices() + { + return services; + } public void send( Message message ) { @@ -260,7 +279,7 @@ public class DefaultClient implements Client { checkRunning(); - closeConnections( null ); + closeConnections( null ); } protected void closeConnections( DisconnectInfo info ) @@ -268,6 +287,10 @@ public class DefaultClient implements Client if( !isRunning ) return; + // Let the services get a chance to stop before we + // kill the connection. + services.stop(); + // Send a close message // Tell the thread it's ok to die @@ -285,6 +308,9 @@ public class DefaultClient implements Client fireDisconnected(info); isRunning = false; + + // Terminate the services + services.terminate(); } public void addClientStateListener( ClientStateListener listener ) @@ -333,6 +359,12 @@ public class DefaultClient implements Client l.clientConnected( this ); } } + + protected void startServices() + { + // Let the services know we are finally started + services.start(); + } protected void fireDisconnected( DisconnectInfo info ) { @@ -391,11 +423,19 @@ public class DefaultClient implements Client // Pull off the connection management messages we're // interested in and then pass on the rest. if( m instanceof ClientRegistrationMessage ) { - // Then we've gotten our real id - this.id = (int)((ClientRegistrationMessage)m).getId(); - log.log( Level.FINE, "Connection established, id:{0}.", this.id ); - connecting.countDown(); - fireConnected(); + ClientRegistrationMessage crm = (ClientRegistrationMessage)m; + // See if it has a real ID + if( crm.getId() >= 0 ) { + // Then we've gotten our real id + this.id = (int)crm.getId(); + log.log( Level.FINE, "Connection established, id:{0}.", this.id ); + connecting.countDown(); + fireConnected(); + } else { + // Else it's a message letting us know that the + // hosted services have been started + startServices(); + } return; } else if( m instanceof ChannelInfoMessage ) { // This is an interum step in the connection process and diff --git a/jme3-networking/src/main/java/com/jme3/network/base/DefaultServer.java b/jme3-networking/src/main/java/com/jme3/network/base/DefaultServer.java index 3816fbace..2b9add2ef 100644 --- a/jme3-networking/src/main/java/com/jme3/network/base/DefaultServer.java +++ b/jme3-networking/src/main/java/com/jme3/network/base/DefaultServer.java @@ -37,6 +37,8 @@ import com.jme3.network.kernel.Kernel; import com.jme3.network.message.ChannelInfoMessage; import com.jme3.network.message.ClientRegistrationMessage; import com.jme3.network.message.DisconnectMessage; +import com.jme3.network.service.HostedServiceManager; +import com.jme3.network.service.serializer.ServerSerializerRegistrationsService; import java.io.IOException; import java.nio.ByteBuffer; import java.util.*; @@ -55,7 +57,7 @@ import java.util.logging.Logger; */ public class DefaultServer implements Server { - static Logger log = Logger.getLogger(DefaultServer.class.getName()); + static final Logger log = Logger.getLogger(DefaultServer.class.getName()); // First two channels are reserved for reliable and // unreliable @@ -85,6 +87,8 @@ public class DefaultServer implements Server = new MessageListenerRegistry(); private List connectionListeners = new CopyOnWriteArrayList(); + private HostedServiceManager services; + public DefaultServer( String gameName, int version, Kernel reliable, Kernel fast ) { if( reliable == null ) @@ -92,6 +96,8 @@ public class DefaultServer implements Server this.gameName = gameName; this.version = version; + this.services = new HostedServiceManager(this); + addStandardServices(); reliableAdapter = new KernelAdapter( this, reliable, dispatcher, true ); channels.add( reliableAdapter ); @@ -101,6 +107,10 @@ public class DefaultServer implements Server } } + protected void addStandardServices() { + services.addService(new ServerSerializerRegistrationsService()); + } + public String getGameName() { return gameName; @@ -110,6 +120,11 @@ public class DefaultServer implements Server { return version; } + + public HostedServiceManager getServices() + { + return services; + } public int addChannel( int port ) { @@ -164,7 +179,10 @@ public class DefaultServer implements Server ka.start(); } - isRunning = true; + isRunning = true; + + // Start the services + services.start(); } public boolean isRunning() @@ -177,13 +195,20 @@ public class DefaultServer implements Server if( !isRunning ) throw new IllegalStateException( "Server is not started." ); + // First stop the services since we are about to + // kill the connections they are using + services.stop(); + try { // Kill the adpaters, they will kill the kernels for( KernelAdapter ka : channels ) { ka.close(); } - isRunning = false; + isRunning = false; + + // Now terminate all of the services + services.terminate(); } catch( InterruptedException e ) { throw new RuntimeException( "Interrupted while closing", e ); } @@ -198,7 +223,7 @@ public class DefaultServer implements Server { if( connections.isEmpty() ) return; - + ByteBuffer buffer = MessageProtocol.messageToBuffer(message, null); FilterAdapter adapter = filter == null ? null : new FilterAdapter(filter); @@ -387,7 +412,14 @@ public class DefaultServer implements Server // Now we can notify the listeners about the // new connection. - fireConnectionAdded( addedConnection ); + fireConnectionAdded( addedConnection ); + + // Send a second registration message with an invalid ID + // to let the connection know that it can start its services + m = new ClientRegistrationMessage(); + m.setId(-1); + m.setReliable(true); + addedConnection.send(m); } } @@ -396,6 +428,18 @@ public class DefaultServer implements Server return endpointConnections.get(endpoint); } + protected void removeConnecting( Endpoint p ) + { + // No easy lookup for connecting Connections + // from endpoint. + for( Map.Entry e : connecting.entrySet() ) { + if( e.getValue().hasEndpoint(p) ) { + connecting.remove(e.getKey()); + return; + } + } + } + protected void connectionClosed( Endpoint p ) { if( p.isConnected() ) { @@ -411,10 +455,10 @@ public class DefaultServer implements Server // Also note: this method will be called multiple times per // HostedConnection if it has multiple endpoints. - Connection removed = null; + Connection removed; synchronized( this ) { // Just in case the endpoint was still connecting - connecting.values().remove(p); + removeConnecting(p); // And the regular management removed = (Connection)endpointConnections.remove(p); @@ -452,6 +496,16 @@ public class DefaultServer implements Server id = nextId.getAndIncrement(); channels = new Endpoint[channelCount]; } + + boolean hasEndpoint( Endpoint p ) + { + for( Endpoint e : channels ) { + if( p == e ) { + return true; + } + } + return false; + } void setChannel( int channel, Endpoint p ) { @@ -557,6 +611,7 @@ public class DefaultServer implements Server return Collections.unmodifiableSet(sessionData.keySet()); } + @Override public String toString() { return "Connection[ id=" + id + ", reliable=" + channels[CH_RELIABLE] diff --git a/jme3-networking/src/main/java/com/jme3/network/base/MessageProtocol.java b/jme3-networking/src/main/java/com/jme3/network/base/MessageProtocol.java index a8d0d39fd..6751ecc3f 100644 --- a/jme3-networking/src/main/java/com/jme3/network/base/MessageProtocol.java +++ b/jme3-networking/src/main/java/com/jme3/network/base/MessageProtocol.java @@ -181,7 +181,7 @@ public class MessageProtocol Message m = (Message)obj; messages.add(m); } catch( IOException e ) { - throw new RuntimeException( "Error deserializing object", e ); + throw new RuntimeException( "Error deserializing object, clas ID:" + buffer.getShort(0), e ); } } } diff --git a/jme3-networking/src/main/java/com/jme3/network/kernel/udp/UdpConnector.java b/jme3-networking/src/main/java/com/jme3/network/kernel/udp/UdpConnector.java index 20682ecee..bf0f7ddb1 100644 --- a/jme3-networking/src/main/java/com/jme3/network/kernel/udp/UdpConnector.java +++ b/jme3-networking/src/main/java/com/jme3/network/kernel/udp/UdpConnector.java @@ -113,7 +113,6 @@ public class UdpConnector implements Connector public ByteBuffer read() { checkClosed(); - try { DatagramPacket packet = new DatagramPacket( buffer, buffer.length ); sock.receive(packet); @@ -132,7 +131,6 @@ public class UdpConnector implements Connector public void write( ByteBuffer data ) { checkClosed(); - try { DatagramPacket p = new DatagramPacket( data.array(), data.position(), data.remaining(), remoteAddress ); diff --git a/jme3-networking/src/main/java/com/jme3/network/message/SerializerRegistrationsMessage.java b/jme3-networking/src/main/java/com/jme3/network/message/SerializerRegistrationsMessage.java new file mode 100644 index 000000000..9c3896475 --- /dev/null +++ b/jme3-networking/src/main/java/com/jme3/network/message/SerializerRegistrationsMessage.java @@ -0,0 +1,190 @@ +/* + * $Id: SerializerRegistrationsMessage.java 3829 2014-11-24 07:25:43Z pspeed $ + * + * Copyright (c) 2012, Paul Speed + * All rights reserved. + */ + +package com.jme3.network.message; + +import com.jme3.network.AbstractMessage; +import com.jme3.network.serializing.Serializable; +import com.jme3.network.serializing.Serializer; +import com.jme3.network.serializing.SerializerRegistration; +import com.jme3.network.serializing.serializers.FieldSerializer; +import java.util.*; +import java.util.jar.Attributes; +import java.util.logging.Level; +import java.util.logging.Logger; + + +/** + * Holds a compiled set of message registration information that + * can be sent over the wire. The received message can then be + * used to register all of the classes using the same IDs and + * same ordering, etc.. The intent is that the server compiles + * this message once it is sure that all serializable classes have + * been registered. It can then send this to each new client and + * they can use it to register all of the classes without requiring + * exactly reproducing the same calls that the server did to register + * messages. + * + *

    Normally, JME recommends that apps have a common utility method + * that they call on both client and server. However, this makes + * pluggable services nearly impossible as some central class has to + * know about all registered serializers. This message implementation + * gets around by only requiring registration on the server.

    + * + * @author Paul Speed + */ +@Serializable +public class SerializerRegistrationsMessage extends AbstractMessage { + + static final Logger log = Logger.getLogger(SerializerRegistrationsMessage.class.getName()); + + public static final Set ignore = new HashSet(); + static { + // We could build this automatically but then we + // risk making a client and server out of date simply because + // their JME versions are out of date. + ignore.add(Boolean.class); + ignore.add(Float.class); + ignore.add(Boolean.class); + ignore.add(Byte.class); + ignore.add(Character.class); + ignore.add(Short.class); + ignore.add(Integer.class); + ignore.add(Long.class); + ignore.add(Float.class); + ignore.add(Double.class); + ignore.add(String.class); + + ignore.add(DisconnectMessage.class); + ignore.add(ClientRegistrationMessage.class); + + ignore.add(Date.class); + ignore.add(AbstractCollection.class); + ignore.add(AbstractList.class); + ignore.add(AbstractSet.class); + ignore.add(ArrayList.class); + ignore.add(HashSet.class); + ignore.add(LinkedHashSet.class); + ignore.add(LinkedList.class); + ignore.add(TreeSet.class); + ignore.add(Vector.class); + ignore.add(AbstractMap.class); + ignore.add(Attributes.class); + ignore.add(HashMap.class); + ignore.add(Hashtable.class); + ignore.add(IdentityHashMap.class); + ignore.add(TreeMap.class); + ignore.add(WeakHashMap.class); + ignore.add(Enum.class); + + ignore.add(GZIPCompressedMessage.class); + ignore.add(ZIPCompressedMessage.class); + + ignore.add(ChannelInfoMessage.class); + + ignore.add(SerializerRegistrationsMessage.class); + ignore.add(SerializerRegistrationsMessage.Registration.class); + } + + public static SerializerRegistrationsMessage INSTANCE; + public static Registration[] compiled; + private static final Serializer fieldSerializer = new FieldSerializer(); + + private Registration[] registrations; + + public SerializerRegistrationsMessage() { + setReliable(true); + } + + public SerializerRegistrationsMessage( Registration... registrations ) { + setReliable(true); + this.registrations = registrations; + } + + public static void compile() { + + // Let's just see what they are here + List list = new ArrayList(); + for( SerializerRegistration reg : Serializer.getSerializerRegistrations() ) { + Class type = reg.getType(); + if( ignore.contains(type) ) + continue; + if( type.isPrimitive() ) + continue; + + list.add(new Registration(reg)); + } + + if( log.isLoggable(Level.FINE) ) { + log.log( Level.FINE, "Number of registered classes:{0}", list.size()); + for( Registration reg : list ) { + log.log( Level.FINE, " {0}", reg); + } + } + compiled = list.toArray(new Registration[list.size()]); + + INSTANCE = new SerializerRegistrationsMessage(compiled); + + Serializer.setReadOnly(true); + } + + public void registerAll() { + for( Registration reg : registrations ) { + log.log( Level.INFO, "Registering:{0}", reg); + reg.register(); + } + } + + @Serializable + public static final class Registration { + + private short id; + private String className; + private String serializerClassName; + + public Registration() { + } + + public Registration( SerializerRegistration reg ) { + + this.id = reg.getId(); + this.className = reg.getType().getName(); + if( reg.getSerializer().getClass() != FieldSerializer.class ) { + this.serializerClassName = reg.getSerializer().getClass().getName(); + } + } + + public void register() { + try { + Class type = Class.forName(className); + Serializer serializer; + if( serializerClassName == null ) { + serializer = fieldSerializer; + } else { + Class serializerType = Class.forName(serializerClassName); + serializer = (Serializer)serializerType.newInstance(); + } + SerializerRegistration result = Serializer.registerClassForId(id, type, serializer); + log.log( Level.FINE, " result:{0}", result); + } catch( ClassNotFoundException e ) { + throw new RuntimeException( "Class not found attempting to register:" + this, e ); + } catch( InstantiationException e ) { + throw new RuntimeException( "Error instantiating serializer registering:" + this, e ); + } catch( IllegalAccessException e ) { + throw new RuntimeException( "Error instantiating serializer registering:" + this, e ); + } + } + + @Override + public String toString() { + return "Registration[" + id + " = " + className + ", serializer=" + serializerClassName + "]"; + } + } +} + + + diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/Serializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/Serializer.java index a7d20da54..d4c054403 100644 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/Serializer.java +++ b/jme3-networking/src/main/java/com/jme3/network/serializing/Serializer.java @@ -71,6 +71,8 @@ public abstract class Serializer { private static boolean strictRegistration = true; + private static volatile boolean locked = false; + // Registers the classes we already have serializers for. static { @@ -168,6 +170,20 @@ public abstract class Serializer { return nextAvailableId--; } + /** + * Can put the registry in a read-only state such that additional attempts + * to register classes will fail. This can be used by servers to lock the + * registry to avoid accidentally registering classes after a full registry + * set has been compiled. + */ + public static void setReadOnly( boolean b ) { + locked = b; + } + + public static boolean isReadOnly() { + return locked; + } + /** * Directly registers a class for a specific ID. Generally, use the regular * registerClass() method. This method is intended for framework code that might @@ -175,7 +191,11 @@ public abstract class Serializer { */ public static SerializerRegistration registerClassForId( short id, Class cls, Serializer serializer ) { - SerializerRegistration reg = new SerializerRegistration(serializer, cls, id); + if( locked ) { + throw new RuntimeException("Serializer registry locked trying to register class:" + cls); + } + + SerializerRegistration reg = new SerializerRegistration(serializer, cls, id); idRegistrations.put(id, reg); classRegistrations.put(cls, reg); diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/GZIPSerializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/GZIPSerializer.java index 01dbd1d41..7579e84c5 100644 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/GZIPSerializer.java +++ b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/GZIPSerializer.java @@ -87,7 +87,8 @@ public class GZIPSerializer extends Serializer { ByteArrayOutputStream byteArrayOutput = new ByteArrayOutputStream(); GZIPOutputStream gzipOutput = new GZIPOutputStream(byteArrayOutput); - gzipOutput.write(tempBuffer.array()); + tempBuffer.flip(); + gzipOutput.write(tempBuffer.array(), 0, tempBuffer.limit()); gzipOutput.flush(); gzipOutput.finish(); gzipOutput.close(); diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/ZIPSerializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/ZIPSerializer.java index 1241c1341..ad7d7162d 100644 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/ZIPSerializer.java +++ b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/ZIPSerializer.java @@ -98,7 +98,8 @@ public class ZIPSerializer extends Serializer { ZipEntry zipEntry = new ZipEntry("zip"); zipOutput.putNextEntry(zipEntry); - zipOutput.write(tempBuffer.array()); + tempBuffer.flip(); + zipOutput.write(tempBuffer.array(), 0, tempBuffer.limit()); zipOutput.flush(); zipOutput.closeEntry(); zipOutput.close(); diff --git a/jme3-networking/src/main/java/com/jme3/network/service/AbstractClientService.java b/jme3-networking/src/main/java/com/jme3/network/service/AbstractClientService.java new file mode 100644 index 000000000..d1a848dac --- /dev/null +++ b/jme3-networking/src/main/java/com/jme3/network/service/AbstractClientService.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jme3.network.service; + +import com.jme3.network.Client; + +/** + * Convenient base class for ClientServices providing some default ClientService + * interface implementations as well as a few convenience methods + * such as getServiceManager() and getService(type). Subclasses + * must at least override the onInitialize() method to handle + * service initialization. + * + * @author Paul Speed + */ +public abstract class AbstractClientService extends AbstractService + implements ClientService { + + protected AbstractClientService() { + } + + /** + * Returns the client for this client service or null if + * the service is not yet attached. + */ + protected Client getClient() { + ClientServiceManager csm = getServiceManager(); + return csm == null ? null : csm.getClient(); + } + +} diff --git a/jme3-networking/src/main/java/com/jme3/network/service/AbstractHostedConnectionService.java b/jme3-networking/src/main/java/com/jme3/network/service/AbstractHostedConnectionService.java new file mode 100644 index 000000000..485712b95 --- /dev/null +++ b/jme3-networking/src/main/java/com/jme3/network/service/AbstractHostedConnectionService.java @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jme3.network.service; + +import com.jme3.network.HostedConnection; +import com.jme3.network.Server; +import java.util.logging.Level; +import java.util.logging.Logger; + + +/** + * Convenient base class for HostedServices providing some default HostedService + * interface implementations as well as a few convenience methods + * such as getServiceManager() and getService(type). This implementation + * enhances the default capabilities provided by AbstractHostedService by + * adding automatic connection management. + * + *

    Subclasses must at least override the onInitialize(), startHostingOnConnection(), and + * stopHostingOnConnection() methods to handle service and connection initialization.

    + * + *

    An autoHost flag controls whether startHostingOnConnection() is called + * automatically when new connections are detected. If autoHohst is false then it + * is up to the implementation or appliction to specifically start hosting at + * some point.

    + * + * @author Paul Speed + */ +public abstract class AbstractHostedConnectionService extends AbstractHostedService { + + static final Logger log = Logger.getLogger(AbstractHostedConnectionService.class.getName()); + + private boolean autoHost; + + /** + * Creates a new HostedService that will autohost connections + * when detected. + */ + protected AbstractHostedConnectionService() { + this(true); + } + + /** + * Creates a new HostedService that will automatically host + * connections only if autoHost is true. + */ + protected AbstractHostedConnectionService( boolean autoHost ) { + this.autoHost = autoHost; + } + + /** + * When set to true, all new connections will automatically have + * hosting services attached to them by calling startHostingOnConnection(). + * If this is set to false then it is up to the application or other services + * to eventually call startHostingOnConnection(). + * + *

    Reasons for doing this vary but usually would be because + * the client shouldn't be allowed to perform any service-related calls until + * it has provided more information... for example, logging in.

    + */ + public void setAutoHost( boolean b ) { + this.autoHost = b; + } + + /** + * Returns true if this service automatically attaches + * hosting capabilities to new connections. + */ + public boolean getAutoHost() { + return autoHost; + } + + + /** + * Performs implementation specific connection hosting setup. + * Generally this involves setting up some handlers or session + * attributes on the connection. If autoHost is true then this + * method is called automatically during connectionAdded() + * processing. + */ + public abstract void startHostingOnConnection( HostedConnection hc ); + + /** + * Performs implementation specific connection tear-down. + * This will be called automatically when the connectionRemoved() + * event occurs... whether the application has already called it + * or not. + */ + public abstract void stopHostingOnConnection( HostedConnection hc ); + + /** + * Called internally when a new connection is detected for + * the server. If the current autoHost property is true then + * startHostingOnConnection(hc) is called. + */ + @Override + public void connectionAdded(Server server, HostedConnection hc) { + if( log.isLoggable(Level.FINEST) ) { + log.log(Level.FINEST, "connectionAdded({0}, {1})", new Object[]{server, hc}); + } + if( autoHost ) { + startHostingOnConnection(hc); + } + } + + /** + * Called internally when an existing connection is leaving + * the server. This method always calls stopHostingOnConnection(hc). + * Implementations should be aware that if they stopHostingOnConnection() + * early that they will get a second call when the connection goes away. + */ + @Override + public void connectionRemoved(Server server, HostedConnection hc) { + if( log.isLoggable(Level.FINEST) ) { + log.log(Level.FINEST, "connectionRemoved({0}, {1})", new Object[]{server, hc}); + } + stopHostingOnConnection(hc); + } +} diff --git a/jme3-networking/src/main/java/com/jme3/network/service/AbstractHostedService.java b/jme3-networking/src/main/java/com/jme3/network/service/AbstractHostedService.java new file mode 100644 index 000000000..051c0d259 --- /dev/null +++ b/jme3-networking/src/main/java/com/jme3/network/service/AbstractHostedService.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jme3.network.service; + +import com.jme3.network.HostedConnection; +import com.jme3.network.Server; + + +/** + * Convenient base class for HostedServices providing some default HostedService + * interface implementations as well as a few convenience methods + * such as getServiceManager() and getService(type). Subclasses + * must at least override the onInitialize() method to handle + * service initialization. + * + * @author Paul Speed + */ +public abstract class AbstractHostedService extends AbstractService + implements HostedService { + + protected AbstractHostedService() { + } + + /** + * Returns the server for this hosted service or null if + * the service is not yet attached. + */ + protected Server getServer() { + HostedServiceManager hsm = getServiceManager(); + return hsm == null ? null : hsm.getServer(); + } + + /** + * Default implementation does nothing. Implementations can + * override this to peform custom new connection behavior. + */ + @Override + public void connectionAdded(Server server, HostedConnection hc) { + } + + /** + * Default implementation does nothing. Implementations can + * override this to peform custom leaving connection behavior. + */ + @Override + public void connectionRemoved(Server server, HostedConnection hc) { + } + +} diff --git a/jme3-networking/src/main/java/com/jme3/network/service/AbstractService.java b/jme3-networking/src/main/java/com/jme3/network/service/AbstractService.java new file mode 100644 index 000000000..370b1c5af --- /dev/null +++ b/jme3-networking/src/main/java/com/jme3/network/service/AbstractService.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jme3.network.service; + + +/** + * Base class providing some default Service interface implementations + * as well as a few convenience methods such as getServiceManager() + * and getService(type). Subclasses must at least override the + * onInitialize() method to handle service initialization. + * + * @author Paul Speed + */ +public abstract class AbstractService implements Service { + + private S serviceManager; + + protected AbstractService() { + } + + /** + * Returns the ServiceManager that was passed to + * initialize() during service initialization. + */ + protected S getServiceManager() { + return serviceManager; + } + + /** + * Retrieves the first sibling service of the specified + * type. + */ + protected > T getService( Class type ) { + return type.cast(serviceManager.getService(type)); + } + + /** + * Initializes this service by keeping a reference to + * the service manager and calling onInitialize(). + */ + @Override + public final void initialize( S serviceManager ) { + this.serviceManager = serviceManager; + onInitialize(serviceManager); + } + + /** + * Called during initialize() for the subclass to perform + * implementation specific initialization. + */ + protected abstract void onInitialize( S serviceManager ); + + /** + * Default implementation does nothing. Implementations can + * override this to peform custom startup behavior. + */ + @Override + public void start() { + } + + /** + * Default implementation does nothing. Implementations can + * override this to peform custom stop behavior. + */ + @Override + public void stop() { + } + + /** + * Default implementation does nothing. Implementations can + * override this to peform custom termination behavior. + */ + @Override + public void terminate( S serviceManager ) { + } + + @Override + public String toString() { + return getClass().getName() + "[serviceManager.class=" + serviceManager.getClass() + "]"; + } +} diff --git a/jme3-networking/src/main/java/com/jme3/network/service/ClientService.java b/jme3-networking/src/main/java/com/jme3/network/service/ClientService.java new file mode 100644 index 000000000..c8057cb31 --- /dev/null +++ b/jme3-networking/src/main/java/com/jme3/network/service/ClientService.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jme3.network.service; + + +/** + * Interface implemented by Client-side services that augment + * a network Client's functionality. + * + * @author Paul Speed + */ +public interface ClientService extends Service { + + /** + * Called when the service is first attached to the service + * manager. + */ + @Override + public void initialize( ClientServiceManager serviceManager ); + + /** + * Called when the service manager is started or if the + * service is added to an already started service manager. + */ + @Override + public void start(); + + /** + * Called when the service is shutting down. All services + * are stopped and any service manager resources are closed + * before the services are terminated. + */ + @Override + public void stop(); + + /** + * The service manager is fully shutting down. All services + * have been stopped and related connections closed. + */ + @Override + public void terminate( ClientServiceManager serviceManager ); +} diff --git a/jme3-networking/src/main/java/com/jme3/network/service/ClientServiceManager.java b/jme3-networking/src/main/java/com/jme3/network/service/ClientServiceManager.java new file mode 100644 index 000000000..dc204fb2f --- /dev/null +++ b/jme3-networking/src/main/java/com/jme3/network/service/ClientServiceManager.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jme3.network.service; + +import com.jme3.network.Client; + + +/** + * Manages ClientServices on behalf of a network Client object. + * + * @author Paul Speed + */ +public class ClientServiceManager extends ServiceManager { + + private Client client; + + /** + * Creates a new ClientServiceManager for the specified network Client. + */ + public ClientServiceManager( Client client ) { + this.client = client; + } + + /** + * Returns the network Client associated with this ClientServiceManager. + */ + public Client getClient() { + return client; + } + + /** + * Returns 'this' and is what is passed to ClientService.initialize() + * and ClientService.termnate(); + */ + @Override + protected final ClientServiceManager getParent() { + return this; + } + + /** + * Adds the specified ClientService and initializes it. If the service manager + * has already been started then the service will also be started. + */ + public void addService( ClientService s ) { + super.addService(s); + } + + /** + * Adds all of the specified ClientServices and initializes them. If the service manager + * has already been started then the services will also be started. + * This is a convenience method that delegates to addService(), thus each + * service will be initialized (and possibly started) in sequence rather + * than doing them all at the end. + */ + public void addServices( ClientService... services ) { + for( ClientService s : services ) { + super.addService(s); + } + } + + /** + * Removes the specified ClientService from this service manager, stopping + * and terminating it as required. If this service manager is in a + * started state then the service will be stopped. After removal, + * the service will be terminated. + */ + public void removeService( ClientService s ) { + super.removeService(s); + } +} diff --git a/jme3-networking/src/main/java/com/jme3/network/service/HostedService.java b/jme3-networking/src/main/java/com/jme3/network/service/HostedService.java new file mode 100644 index 000000000..f522b72d6 --- /dev/null +++ b/jme3-networking/src/main/java/com/jme3/network/service/HostedService.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jme3.network.service; + +import com.jme3.network.ConnectionListener; + + +/** + * Interface implemented by Server-side services that augment + * a network Server's functionality. + * + * @author Paul Speed + */ +public interface HostedService extends Service, ConnectionListener { + + /** + * Called when the service is first attached to the service + * manager. + */ + @Override + public void initialize( HostedServiceManager serviceManager ); + + /** + * Called when the service manager is started or if the + * service is added to an already started service manager. + */ + @Override + public void start(); + + /** + * Called when the service is shutting down. All services + * are stopped and any service manager resources are closed + * before the services are terminated. + */ + @Override + public void stop(); + + /** + * The service manager is fully shutting down. All services + * have been stopped and related connections closed. + */ + @Override + public void terminate( HostedServiceManager serviceManager ); +} diff --git a/jme3-networking/src/main/java/com/jme3/network/service/HostedServiceManager.java b/jme3-networking/src/main/java/com/jme3/network/service/HostedServiceManager.java new file mode 100644 index 000000000..3606ba44b --- /dev/null +++ b/jme3-networking/src/main/java/com/jme3/network/service/HostedServiceManager.java @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jme3.network.service; + +import com.jme3.network.ConnectionListener; +import com.jme3.network.HostedConnection; +import com.jme3.network.Server; + + +/** + * Manages HostedServices on behalf of a network Server object. + * All HostedServices are automatically informed about new and + * leaving connections. + * + * @author Paul Speed + */ +public class HostedServiceManager extends ServiceManager { + + private Server server; + private ConnectionObserver connectionObserver; + + /** + * Creates a HostedServiceManager for the specified network Server. + */ + public HostedServiceManager( Server server ) { + this.server = server; + this.connectionObserver = new ConnectionObserver(); + server.addConnectionListener(connectionObserver); + } + + /** + * Returns the network Server associated with this HostedServiceManager. + */ + public Server getServer() { + return server; + } + + /** + * Returns 'this' and is what is passed to HostedService.initialize() + * and HostedService.termnate(); + */ + @Override + protected final HostedServiceManager getParent() { + return this; + } + + /** + * Adds the specified HostedService and initializes it. If the service manager + * has already been started then the service will also be started. + */ + public void addService( HostedService s ) { + super.addService(s); + } + + /** + * Adds all of the specified HostedServices and initializes them. If the service manager + * has already been started then the services will also be started. + * This is a convenience method that delegates to addService(), thus each + * service will be initialized (and possibly started) in sequence rather + * than doing them all at the end. + */ + public void addServices( HostedService... services ) { + for( HostedService s : services ) { + super.addService(s); + } + } + + /** + * Removes the specified HostedService from this service manager, stopping + * and terminating it as required. If this service manager is in a + * started state then the service will be stopped. After removal, + * the service will be terminated. + */ + public void removeService( HostedService s ) { + super.removeService(s); + } + + /** + * Called internally when a new connection has been added so that the + * services can be notified. + */ + protected void addConnection( HostedConnection hc ) { + for( Service s : getServices() ) { + ((HostedService)s).connectionAdded(server, hc); + } + } + + /** + * Called internally when a connection has been removed so that the + * services can be notified. + */ + protected void removeConnection( HostedConnection hc ) { + for( Service s : getServices() ) { + ((HostedService)s).connectionRemoved(server, hc); + } + } + + protected class ConnectionObserver implements ConnectionListener { + + @Override + public void connectionAdded(Server server, HostedConnection hc) { + addConnection(hc); + } + + @Override + public void connectionRemoved(Server server, HostedConnection hc) { + removeConnection(hc); + } + } +} diff --git a/jme3-networking/src/main/java/com/jme3/network/service/Service.java b/jme3-networking/src/main/java/com/jme3/network/service/Service.java new file mode 100644 index 000000000..f56c90dda --- /dev/null +++ b/jme3-networking/src/main/java/com/jme3/network/service/Service.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jme3.network.service; + + +/** + * The base interface for managed services. + * + * @author Paul Speed + */ +public interface Service { + + /** + * Called when the service is first attached to the service + * manager. + */ + public void initialize( S serviceManager ); + + /** + * Called when the service manager is started or if the + * service is added to an already started service manager. + */ + public void start(); + + /** + * Called when the service manager is shutting down. All services + * are stopped and any service manager resources are closed + * before the services are terminated. + */ + public void stop(); + + /** + * The service manager is fully shutting down. All services + * have been stopped and related connections closed. + */ + public void terminate( S serviceManager ); +} diff --git a/jme3-networking/src/main/java/com/jme3/network/service/ServiceManager.java b/jme3-networking/src/main/java/com/jme3/network/service/ServiceManager.java new file mode 100644 index 000000000..b8ee7d3c4 --- /dev/null +++ b/jme3-networking/src/main/java/com/jme3/network/service/ServiceManager.java @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jme3.network.service; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * The base service manager class from which the HostedServiceManager + * and ClientServiceManager classes are derived. This manages the + * the underlying services and their life cycles. + * + * @author Paul Speed + */ +public abstract class ServiceManager { + + private List> services = new CopyOnWriteArrayList>(); + private volatile boolean started = false; + + protected ServiceManager() { + } + + /** + * Retreives the 'parent' of this service manager, usually + * a more specifically typed version of 'this' but it can be + * anything the seervices are expecting. + */ + protected abstract T getParent(); + + /** + * Returns the complete list of services managed by this + * service manager. This list is thread safe following the + * CopyOnWriteArrayList semantics. + */ + protected List> getServices() { + return services; + } + + /** + * Starts this service manager and all services that it contains. + * Any services added after the service manager has started will have + * their start() methods called. + */ + public void start() { + if( started ) { + return; + } + for( Service s : services ) { + s.start(); + } + started = true; + } + + /** + * Returns true if this service manager has been started. + */ + public boolean isStarted() { + return started; + } + + /** + * Stops all services and puts the service manager into a stopped state. + */ + public void stop() { + if( !started ) { + throw new IllegalStateException(getClass().getSimpleName() + " not started."); + } + for( Service s : services ) { + s.stop(); + } + started = false; + } + + /** + * Adds the specified service and initializes it. If the service manager + * has already been started then the service will also be started. + */ + public > void addService( S s ) { + services.add(s); + s.initialize(getParent()); + if( started ) { + s.start(); + } + } + + /** + * Removes the specified service from this service manager, stopping + * and terminating it as required. If this service manager is in a + * started state then the service will be stopped. After removal, + * the service will be terminated. + */ + public > void removeService( S s ) { + if( started ) { + s.stop(); + } + services.remove(s); + s.terminate(getParent()); + } + + /** + * Terminates all services. If the service manager has not been + * stopped yet then it will be stopped. + */ + public void terminate() { + if( started ) { + stop(); + } + for( Service s : services ) { + s.terminate(getParent()); + } + } + + /** + * Retrieves the first service of the specified type. + */ + public > S getService( Class type ) { + for( Service s : services ) { + if( type.isInstance(s) ) { + return type.cast(s); + } + } + return null; + } + + @Override + public String toString() { + return getClass().getName() + "[services=" + services + "]"; + } +} + diff --git a/jme3-networking/src/main/java/com/jme3/network/service/rpc/RpcClientService.java b/jme3-networking/src/main/java/com/jme3/network/service/rpc/RpcClientService.java new file mode 100644 index 000000000..a74a7c7d1 --- /dev/null +++ b/jme3-networking/src/main/java/com/jme3/network/service/rpc/RpcClientService.java @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jme3.network.service.rpc; + +import com.jme3.network.Client; +import com.jme3.network.util.ObjectMessageDelegator; +import com.jme3.network.service.AbstractClientService; +import com.jme3.network.service.ClientServiceManager; + + +/** + * RPC service that can be added to a network Client to + * add RPC send/receive capabilities. Remote procedure + * calls can be made to the server and responses retrieved. + * Any remote procedure calls that the server performs for + * this connection will be received by this service and delegated + * to the appropriate RpcHandlers. + * + * @author Paul Speed + */ +public class RpcClientService extends AbstractClientService { + + private RpcConnection rpc; + private ObjectMessageDelegator delegator; + + /** + * Creates a new RpcClientService that can be registered + * with the network Client object. + */ + public RpcClientService() { + } + + /** + * Returns the underlying RPC connection for use by other + * services that may require a more generic non-client/server + * specific RPC object with which to interact. + */ + public RpcConnection getRpcConnection() { + return rpc; + } + + /** + * Used internally to setup the RpcConnection and MessageDelegator. + */ + @Override + protected void onInitialize( ClientServiceManager serviceManager ) { + Client client = serviceManager.getClient(); + this.rpc = new RpcConnection(client); + + delegator = new ObjectMessageDelegator(rpc, true); + client.addMessageListener(delegator, delegator.getMessageTypes()); + } + + /** + * Used internally to unregister the RPC MessageDelegator that + * was previously added to the network Client. + */ + @Override + public void terminate( ClientServiceManager serviceManager ) { + Client client = serviceManager.getClient(); + client.removeMessageListener(delegator, delegator.getMessageTypes()); + } + + /** + * Performs a synchronous call on the server against the specified + * object using the specified procedure ID. Both inboud and outbound + * communication is done on the specified channel. + */ + public Object callAndWait( byte channel, short objId, short procId, Object... args ) { + return rpc.callAndWait(channel, objId, procId, args); + } + + /** + * Performs an asynchronous call on the server against the specified + * object using the specified procedure ID. Communication is done + * over the specified channel. No responses are received and none + * are waited for. + */ + public void callAsync( byte channel, short objId, short procId, Object... args ) { + rpc.callAsync(channel, objId, procId, args); + } + + /** + * Register a handler that will be called when the server + * performs a remove procedure call against this client. + * Only one handler per object ID can be registered at any given time, + * though the same handler can be registered for multiple object + * IDs. + */ + public void registerHandler( short objId, RpcHandler handler ) { + rpc.registerHandler(objId, handler); + } + + /** + * Removes a previously registered handler for the specified + * object ID. + */ + public void removeHandler( short objId, RpcHandler handler ) { + rpc.removeHandler(objId, handler); + } + +} diff --git a/jme3-networking/src/main/java/com/jme3/network/service/rpc/RpcConnection.java b/jme3-networking/src/main/java/com/jme3/network/service/rpc/RpcConnection.java new file mode 100644 index 000000000..f457e426b --- /dev/null +++ b/jme3-networking/src/main/java/com/jme3/network/service/rpc/RpcConnection.java @@ -0,0 +1,265 @@ +/* + * Copyright (c) 2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jme3.network.service.rpc; + +import com.jme3.network.MessageConnection; +import com.jme3.network.service.rpc.msg.RpcCallMessage; +import com.jme3.network.service.rpc.msg.RpcResponseMessage; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicLong; +import java.util.logging.Level; +import java.util.logging.Logger; + + +/** + * Wraps a message connection to provide RPC call support. This + * is used internally by the RpcClientService and RpcHostedService to manage + * network messaging. + * + * @author Paul Speed + */ +public class RpcConnection { + + static final Logger log = Logger.getLogger(RpcConnection.class.getName()); + + /** + * The underlying connection upon which RPC call messages are sent + * and RPC response messages are received. It can be a Client or + * a HostedConnection depending on the mode of the RPC service. + */ + private MessageConnection connection; + + /** + * The objectId index of RpcHandler objects that are used to perform the + * RPC calls for a particular object. + */ + private Map handlers = new ConcurrentHashMap(); + + /** + * Provides unique messages IDs for outbound synchronous call + * messages. These are then used in the responses index to + * locate the proper ResponseHolder objects. + */ + private AtomicLong sequenceNumber = new AtomicLong(); + + /** + * Tracks the ResponseHolder objects for sent message IDs. When the + * response is received, the appropriate handler is found here and the + * response or error set, thus releasing the waiting caller. + */ + private Map responses = new ConcurrentHashMap(); + + /** + * Creates a new RpcConnection for the specified network connection. + */ + public RpcConnection( MessageConnection connection ) { + this.connection = connection; + } + + /** + * Clears any pending synchronous calls causing them to + * throw an exception with the message "Closing connection". + */ + public void close() { + // Let any pending waits go free + for( ResponseHolder holder : responses.values() ) { + holder.release(); + } + } + + /** + * Performs a remote procedure call with the specified arguments and waits + * for the response. Both the outbound message and inbound response will + * be sent on the specified channel. + */ + public Object callAndWait( byte channel, short objId, short procId, Object... args ) { + + RpcCallMessage msg = new RpcCallMessage(sequenceNumber.getAndIncrement(), + channel, objId, procId, args); + + // Need to register an object so we can wait for the response. + // ...before we send it. Just in case. + ResponseHolder holder = new ResponseHolder(msg); + responses.put(msg.getMessageId(), holder); + + if( log.isLoggable(Level.FINEST) ) { + log.log(Level.FINEST, "Sending:{0} on channel:{1}", new Object[]{msg, channel}); + } + + // Prevent non-async messages from being send as UDP + // because there is a high probabilty that this would block + // forever waiting for a response. For async calls it's ok + // so it doesn't do the check. + if( channel >= 0 ) { + connection.send(channel, msg); + } else { + connection.send(msg); + } + + return holder.getResponse(); + } + + /** + * Performs a remote procedure call with the specified arguments but does + * not wait for a response. The outbound message is sent on the specified channel. + * There is no inbound response message. + */ + public void callAsync( byte channel, short objId, short procId, Object... args ) { + + RpcCallMessage msg = new RpcCallMessage(-1, channel, objId, procId, args); + if( log.isLoggable(Level.FINEST) ) { + log.log(Level.FINEST, "Sending:{0} on channel:{1}", new Object[]{msg, channel}); + } + connection.send(channel, msg); + } + + /** + * Register a handler that can be called by the other end + * of the connection using the specified object ID. Only one + * handler per object ID can be registered at any given time, + * though the same handler can be registered for multiple object + * IDs. + */ + public void registerHandler( short objId, RpcHandler handler ) { + handlers.put(objId, handler); + } + + /** + * Removes a previously registered handler for the specified + * object ID. + */ + public void removeHandler( short objId, RpcHandler handler ) { + RpcHandler removing = handlers.get(objId); + if( handler != removing ) { + throw new IllegalArgumentException("Handler not registered for object ID:" + + objId + ", handler:" + handler ); + } + handlers.remove(objId); + } + + protected void send( byte channel, RpcResponseMessage msg ) { + if( channel >= 0 ) { + connection.send(channel, msg); + } else { + connection.send(msg); + } + } + + /** + * Called internally when an RpcCallMessage is received from + * the remote connection. + */ + public void handleMessage( RpcCallMessage msg ) { + + if( log.isLoggable(Level.FINEST) ) { + log.log(Level.FINEST, "handleMessage({0})", msg); + } + RpcHandler handler = handlers.get(msg.getObjectId()); + try { + if( handler == null ) { + throw new RuntimeException("Handler not found for objectID:" + msg.getObjectId()); + } + Object result = handler.call(this, msg.getObjectId(), msg.getProcedureId(), msg.getArguments()); + if( !msg.isAsync() ) { + send(msg.getChannel(), new RpcResponseMessage(msg.getMessageId(), result)); + } + } catch( Exception e ) { + if( !msg.isAsync() ) { + send(msg.getChannel(), new RpcResponseMessage(msg.getMessageId(), e)); + } else { + log.log(Level.SEVERE, "Error invoking async call for:" + msg, e); + } + } + } + + /** + * Called internally when an RpcResponseMessage is received from + * the remote connection. + */ + public void handleMessage( RpcResponseMessage msg ) { + if( log.isLoggable(Level.FINEST) ) { + log.log(Level.FINEST, "handleMessage({0})", msg); + } + ResponseHolder holder = responses.remove(msg.getMessageId()); + if( holder == null ) { + return; + } + holder.setResponse(msg); + } + + /** + * Sort of like a Future, holds a locked reference to a response + * until the remote call has completed and returned a response. + */ + private class ResponseHolder { + private Object response; + private String error; + private RpcCallMessage msg; + boolean received = false; + + public ResponseHolder( RpcCallMessage msg ) { + this.msg = msg; + } + + public synchronized void setResponse( RpcResponseMessage msg ) { + this.response = msg.getResult(); + this.error = msg.getError(); + this.received = true; + notifyAll(); + } + + public synchronized Object getResponse() { + try { + while(!received) { + wait(); + } + } catch( InterruptedException e ) { + throw new RuntimeException("Interrupted waiting for respone to:" + msg, e); + } + if( error != null ) { + throw new RuntimeException("Error calling remote procedure:" + msg + "\n" + error); + } + return response; + } + + public synchronized void release() { + if( received ) { + return; + } + // Else signal an error for the callers + this.error = "Closing connection"; + this.received = true; + } + } +} diff --git a/jme3-networking/src/main/java/com/jme3/network/service/rpc/RpcHandler.java b/jme3-networking/src/main/java/com/jme3/network/service/rpc/RpcHandler.java new file mode 100644 index 000000000..d7d99981d --- /dev/null +++ b/jme3-networking/src/main/java/com/jme3/network/service/rpc/RpcHandler.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jme3.network.service.rpc; + + +/** + * Implementations of this interface can be registered with + * the RpcClientService or RpcHostService to handle the + * remote procedure calls for a given object or objects. + * + * @author Paul Speed + */ +public interface RpcHandler { + + /** + * Called when a remote procedure call request is received for a particular + * object from the other end of the network connection. + */ + public Object call( RpcConnection conn, short objectId, short procId, Object... args ); +} + + diff --git a/jme3-networking/src/main/java/com/jme3/network/service/rpc/RpcHostedService.java b/jme3-networking/src/main/java/com/jme3/network/service/rpc/RpcHostedService.java new file mode 100644 index 000000000..2d6f28593 --- /dev/null +++ b/jme3-networking/src/main/java/com/jme3/network/service/rpc/RpcHostedService.java @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jme3.network.service.rpc; + +import com.jme3.network.HostedConnection; +import com.jme3.network.Server; +import com.jme3.network.serializing.Serializer; +import com.jme3.network.service.AbstractHostedConnectionService; +import com.jme3.network.util.SessionDataDelegator; +import com.jme3.network.service.HostedServiceManager; +import com.jme3.network.service.rpc.msg.RpcCallMessage; +import com.jme3.network.service.rpc.msg.RpcResponseMessage; +import java.util.Arrays; +import java.util.logging.Level; +import java.util.logging.Logger; + + +/** + * RPC service that can be added to a network Server to + * add RPC send/receive capabilities. For a particular + * HostedConnection, Remote procedure calls can be made to the + * associated Client and responses retrieved. Any remote procedure + * calls that the Client performs for this connection will be + * received by this service and delegated to the appropriate RpcHandlers. + * + * Note: it can be dangerous for a server to perform synchronous + * RPC calls to a client but especially so if not done as part + * of the response to some other message. ie: iterating over all + * or some HostedConnections to perform synchronous RPC calls + * will be slow and potentially block the server's threads in ways + * that can cause deadlocks or odd contention. + * + * @author Paul Speed + */ +public class RpcHostedService extends AbstractHostedConnectionService { + + private static final String ATTRIBUTE_NAME = "rpcSession"; + + static final Logger log = Logger.getLogger(RpcHostedService.class.getName()); + + private SessionDataDelegator delegator; + + /** + * Creates a new RPC host service that can be registered + * with the Network server and will automatically 'host' + * RPC services and each new network connection. + */ + public RpcHostedService() { + this(true); + } + + /** + * Creates a new RPC host service that can be registered + * with the Network server and will optionally 'host' + * RPC services and each new network connection depending + * on the specified 'autoHost' flag. + */ + public RpcHostedService( boolean autoHost ) { + super(autoHost); + + // This works for me... has to be different in + // the general case + Serializer.registerClasses(RpcCallMessage.class, RpcResponseMessage.class); + } + + /** + * Used internally to setup the message delegator that will + * handle HostedConnection specific messages and forward them + * to that connection's RpcConnection. + */ + @Override + protected void onInitialize( HostedServiceManager serviceManager ) { + Server server = serviceManager.getServer(); + + // A general listener for forwarding the messages + // to the client-specific handler + this.delegator = new SessionDataDelegator(RpcConnection.class, + ATTRIBUTE_NAME, + true); + server.addMessageListener(delegator, delegator.getMessageTypes()); + + if( log.isLoggable(Level.FINEST) ) { + log.log(Level.FINEST, "Registered delegator for message types:{0}", Arrays.asList(delegator.getMessageTypes())); + } + } + + /** + * Retrieves the RpcConnection for the specified HostedConnection + * if that HostedConnection has had RPC services started using + * startHostingOnConnection() (or via autohosting). Returns null + * if the connection currently doesn't have RPC hosting services + * attached. + */ + public RpcConnection getRpcConnection( HostedConnection hc ) { + return hc.getAttribute(ATTRIBUTE_NAME); + } + + /** + * Sets up RPC hosting services for the hosted connection allowing + * getRpcConnection() to return a valid RPC connection object. + * This method is called automatically for all new connections if + * autohost is set to true. + */ + @Override + public void startHostingOnConnection( HostedConnection hc ) { + if( log.isLoggable(Level.FINEST) ) { + log.log(Level.FINEST, "startHostingOnConnection:{0}", hc); + } + hc.setAttribute(ATTRIBUTE_NAME, new RpcConnection(hc)); + } + + /** + * Removes any RPC hosting services associated with the specified + * connection. Calls to getRpcConnection() will return null for + * this connection. The connection's RpcConnection is also closed, + * releasing any waiting synchronous calls with a "Connection closing" + * error. + * This method is called automatically for all leaving connections if + * autohost is set to true. + */ + @Override + public void stopHostingOnConnection( HostedConnection hc ) { + RpcConnection rpc = hc.getAttribute(ATTRIBUTE_NAME); + if( rpc == null ) { + return; + } + if( log.isLoggable(Level.FINEST) ) { + log.log(Level.FINEST, "stopHostingOnConnection:{0}", hc); + } + hc.setAttribute(ATTRIBUTE_NAME, null); + rpc.close(); + } + + /** + * Used internally to remove the message delegator from the + * server. + */ + @Override + public void terminate(HostedServiceManager serviceManager) { + Server server = serviceManager.getServer(); + server.removeMessageListener(delegator, delegator.getMessageTypes()); + } + +} + diff --git a/jme3-networking/src/main/java/com/jme3/network/service/rpc/msg/RpcCallMessage.java b/jme3-networking/src/main/java/com/jme3/network/service/rpc/msg/RpcCallMessage.java new file mode 100644 index 000000000..11c5db591 --- /dev/null +++ b/jme3-networking/src/main/java/com/jme3/network/service/rpc/msg/RpcCallMessage.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jme3.network.service.rpc.msg; + +import com.jme3.network.AbstractMessage; +import com.jme3.network.serializing.Serializable; + + +/** + * Used internally to send RPC call information to + * the other end of a connection for execution. + * + * @author Paul Speed + */ +@Serializable +public class RpcCallMessage extends AbstractMessage { + + private long msgId; + private byte channel; + private short objId; + private short procId; + private Object[] args; + + public RpcCallMessage() { + } + + public RpcCallMessage( long msgId, byte channel, short objId, short procId, Object... args ) { + this.msgId = msgId; + this.channel = channel; + this.objId = objId; + this.procId = procId; + this.args = args; + } + + public long getMessageId() { + return msgId; + } + + public byte getChannel() { + return channel; + } + + public boolean isAsync() { + return msgId == -1; + } + + public short getObjectId() { + return objId; + } + + public short getProcedureId() { + return procId; + } + + public Object[] getArguments() { + return args; + } + + @Override + public String toString() { + return getClass().getSimpleName() + "[#" + msgId + ", channel=" + channel + + (isAsync() ? ", async" : ", sync") + + ", objId=" + objId + + ", procId=" + procId + + ", args.length=" + (args == null ? 0 : args.length) + + "]"; + } +} diff --git a/jme3-networking/src/main/java/com/jme3/network/service/rpc/msg/RpcResponseMessage.java b/jme3-networking/src/main/java/com/jme3/network/service/rpc/msg/RpcResponseMessage.java new file mode 100644 index 000000000..efb0def6a --- /dev/null +++ b/jme3-networking/src/main/java/com/jme3/network/service/rpc/msg/RpcResponseMessage.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jme3.network.service.rpc.msg; + +import com.jme3.network.AbstractMessage; +import com.jme3.network.serializing.Serializable; +import java.io.PrintWriter; +import java.io.StringWriter; + + +/** + * Used internally to send an RPC call's response back to + * the caller. + * + * @author Paul Speed + */ +@Serializable +public class RpcResponseMessage extends AbstractMessage { + + private long msgId; + private Object result; + private String error; + + public RpcResponseMessage() { + } + + public RpcResponseMessage( long msgId, Object result ) { + this.msgId = msgId; + this.result = result; + } + + public RpcResponseMessage( long msgId, Throwable t ) { + this.msgId = msgId; + + StringWriter sOut = new StringWriter(); + PrintWriter out = new PrintWriter(sOut); + t.printStackTrace(out); + out.close(); + this.error = sOut.toString(); + } + + public long getMessageId() { + return msgId; + } + + public Object getResult() { + return result; + } + + public String getError() { + return error; + } + + @Override + public String toString() { + return getClass().getSimpleName() + "[#" + msgId + ", result=" + result + + "]"; + } +} diff --git a/jme3-networking/src/main/java/com/jme3/network/service/serializer/ClientSerializerRegistrationsService.java b/jme3-networking/src/main/java/com/jme3/network/service/serializer/ClientSerializerRegistrationsService.java new file mode 100644 index 000000000..911ce0fb1 --- /dev/null +++ b/jme3-networking/src/main/java/com/jme3/network/service/serializer/ClientSerializerRegistrationsService.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jme3.network.service.serializer; + +import com.jme3.network.Client; +import com.jme3.network.Message; +import com.jme3.network.MessageListener; +import com.jme3.network.message.SerializerRegistrationsMessage; +import com.jme3.network.serializing.Serializer; +import com.jme3.network.service.AbstractClientService; +import com.jme3.network.service.ClientServiceManager; + + +/** + * + * + * @author Paul Speed + */ +public class ClientSerializerRegistrationsService extends AbstractClientService + implements MessageListener { + + @Override + protected void onInitialize( ClientServiceManager serviceManager ) { + // Make sure our message type is registered + // This is the minimum we'd need just to be able to register + // the rest... otherwise we can't even receive this message. + Serializer.registerClass(SerializerRegistrationsMessage.class); + Serializer.registerClass(SerializerRegistrationsMessage.Registration.class); + + // Add our listener for that message type + serviceManager.getClient().addMessageListener(this, SerializerRegistrationsMessage.class); + } + + public void messageReceived( Client source, Message m ) { + // We only wait for one kind of message... + SerializerRegistrationsMessage msg = (SerializerRegistrationsMessage)m; + msg.registerAll(); + } +} diff --git a/jme3-networking/src/main/java/com/jme3/network/service/serializer/ServerSerializerRegistrationsService.java b/jme3-networking/src/main/java/com/jme3/network/service/serializer/ServerSerializerRegistrationsService.java new file mode 100644 index 000000000..b24a8db5f --- /dev/null +++ b/jme3-networking/src/main/java/com/jme3/network/service/serializer/ServerSerializerRegistrationsService.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jme3.network.service.serializer; + +import com.jme3.network.HostedConnection; +import com.jme3.network.Server; +import com.jme3.network.message.SerializerRegistrationsMessage; +import com.jme3.network.serializing.Serializer; +import com.jme3.network.service.AbstractHostedService; +import com.jme3.network.service.HostedServiceManager; + + +/** + * + * + * @author Paul Speed + */ +public class ServerSerializerRegistrationsService extends AbstractHostedService { + + @Override + protected void onInitialize( HostedServiceManager serviceManager ) { + // Make sure our message type is registered + Serializer.registerClass(SerializerRegistrationsMessage.class); + Serializer.registerClass(SerializerRegistrationsMessage.Registration.class); + } + + @Override + public void start() { + // Compile the registrations into a message we will + // send to all connecting clients + SerializerRegistrationsMessage.compile(); + } + + @Override + public void connectionAdded(Server server, HostedConnection hc) { + // Just in case + super.connectionAdded(server, hc); + + // Send the client the registration information + hc.send(SerializerRegistrationsMessage.INSTANCE); + } +} diff --git a/jme3-networking/src/main/java/com/jme3/network/util/AbstractMessageDelegator.java b/jme3-networking/src/main/java/com/jme3/network/util/AbstractMessageDelegator.java new file mode 100644 index 000000000..a73496ea8 --- /dev/null +++ b/jme3-networking/src/main/java/com/jme3/network/util/AbstractMessageDelegator.java @@ -0,0 +1,314 @@ +/* + * Copyright (c) 2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jme3.network.util; + +import com.jme3.network.Message; +import com.jme3.network.MessageConnection; +import com.jme3.network.MessageListener; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; + + +/** + * A MessageListener implementation that will forward messages to methods + * of a delegate object. These methods can be automapped or manually + * specified. Subclasses provide specific implementations for how to + * find the actual delegate object. + * + * @author Paul Speed + */ +public abstract class AbstractMessageDelegator + implements MessageListener { + + static final Logger log = Logger.getLogger(AbstractMessageDelegator.class.getName()); + + private Class delegateType; + private Map methods = new HashMap(); + private Class[] messageTypes; + + /** + * Creates an AbstractMessageDelegator that will forward received + * messages to methods of the specified delegate type. If automap + * is true then reflection is used to lookup probably message handling + * methods. + */ + protected AbstractMessageDelegator( Class delegateType, boolean automap ) { + this.delegateType = delegateType; + if( automap ) { + automap(); + } + } + + /** + * Returns the array of messages known to be handled by this message + * delegator. + */ + public Class[] getMessageTypes() { + if( messageTypes == null ) { + messageTypes = methods.keySet().toArray(new Class[methods.size()]); + } + return messageTypes; + } + + /** + * Returns true if the specified method is valid for the specified + * message type. This is used internally during automapping to + * provide implementation specific filting of methods. + * This implementation checks for methods that take either the connection and message + * type arguments (in that order) or just the message type. + */ + protected boolean isValidMethod( Method m, Class messageType ) { + + if( log.isLoggable(Level.FINEST) ) { + log.log(Level.FINEST, "isValidMethod({0}, {1})", new Object[]{m, messageType}); + } + + // Parameters must be S and message type or just message type + Class[] parms = m.getParameterTypes(); + if( parms.length != 2 && parms.length != 1 ) { + log.finest("Parameter count is not 1 or 2"); + return false; + } + int messageIndex = 0; + if( parms.length > 1 ) { + if( MessageConnection.class.isAssignableFrom(parms[0]) ) { + messageIndex++; + } else { + log.finest("First paramter is not a MessageConnection or subclass."); + return false; + } + } + + if( messageType == null && !Message.class.isAssignableFrom(parms[messageIndex]) ) { + log.finest("Second paramter is not a Message or subclass."); + return false; + } + if( messageType != null && !parms[messageIndex].isAssignableFrom(messageType) ) { + log.log(Level.FINEST, "Second paramter is not a {0}", messageType); + return false; + } + return true; + } + + /** + * Convenience method that returns the message type as + * reflecively determined for a particular method. This + * only works with methods that actually have arguments. + * This implementation returns the last element of the method's + * getParameterTypes() array, thus supporting both + * method(connection, messageType) as well as just method(messageType) + * calling forms. + */ + protected Class getMessageType( Method m ) { + Class[] parms = m.getParameterTypes(); + return parms[parms.length-1]; + } + + /** + * Goes through all of the delegate type's methods to find + * a method of the specified name that may take the specified + * message type. + */ + protected Method findDelegate( String name, Class messageType ) { + // We do an exhaustive search because it's easier to + // check for a variety of parameter types and it's all + // that Class would be doing in getMethod() anyway. + for( Method m : delegateType.getDeclaredMethods() ) { + + if( !m.getName().equals(name) ) { + continue; + } + + if( isValidMethod(m, messageType) ) { + return m; + } + } + + return null; + } + + /** + * Returns true if the specified method name is allowed. + * This is used by automapping to determine if a method + * should be rejected purely on name. Default implemention + * always returns true. + */ + protected boolean allowName( String name ) { + return true; + } + + /** + * Calls the map(Set) method with a null argument causing + * all available matching methods to mapped to message types. + */ + protected final void automap() { + map((Set)null); + if( methods.isEmpty() ) { + throw new RuntimeException("No message handling methods found for class:" + delegateType); + } + } + + /** + * Specifically maps the specified methods names, autowiring + * the parameters. + */ + public AbstractMessageDelegator map( String... methodNames ) { + Set names = new HashSet( Arrays.asList(methodNames) ); + map(names); + return this; + } + + /** + * Goes through all of the delegate type's declared methods + * mapping methods that match the current constraints. + * If the constraints set is null then allowName() is + * checked for names otherwise only names in the constraints + * set are allowed. + * For each candidate method that passes the above checks, + * isValidMethod() is called with a null message type argument. + * All methods are made accessible thus supporting non-public + * methods as well as public methods. + */ + protected void map( Set constraints ) { + + if( log.isLoggable(Level.FINEST) ) { + log.log(Level.FINEST, "map({0})", constraints); + } + for( Method m : delegateType.getDeclaredMethods() ) { + if( log.isLoggable(Level.FINEST) ) { + log.log(Level.FINEST, "Checking method:{0}", m); + } + + if( constraints == null && !allowName(m.getName()) ) { + log.finest("Name is not allowed."); + continue; + } + if( constraints != null && !constraints.contains(m.getName()) ) { + log.finest("Name is not in constraints set."); + continue; + } + + if( isValidMethod(m, null) ) { + if( log.isLoggable(Level.FINEST) ) { + log.log(Level.FINEST, "Adding method mapping:{0} = {1}", new Object[]{getMessageType(m), m}); + } + // Make sure we can access the method even if it's not public or + // is in a non-public inner class. + m.setAccessible(true); + methods.put(getMessageType(m), m); + } + } + + messageTypes = null; + } + + /** + * Manually maps a specified method to the specified message type. + */ + public AbstractMessageDelegator map( Class messageType, String methodName ) { + // Lookup the method + Method m = findDelegate( methodName, messageType ); + if( m == null ) { + throw new RuntimeException( "Method:" + methodName + + " not found matching signature (MessageConnection, " + + messageType.getName() + ")" ); + } + + if( log.isLoggable(Level.FINEST) ) { + log.log(Level.FINEST, "Adding method mapping:{0} = {1}", new Object[]{messageType, m}); + } + methods.put( messageType, m ); + messageTypes = null; + return this; + } + + /** + * Returns the mapped method for the specified message type. + */ + protected Method getMethod( Class c ) { + Method m = methods.get(c); + return m; + } + + /** + * Implemented by subclasses to provide the actual delegate object + * against which the mapped message type methods will be called. + */ + protected abstract Object getSourceDelegate( S source ); + + /** + * Implementation of the MessageListener's messageReceived() + * method that will use the current message type mapping to + * find an appropriate message handling method and call it + * on the delegate returned by getSourceDelegate(). + */ + @Override + public void messageReceived( S source, Message msg ) { + if( msg == null ) { + return; + } + + Object delegate = getSourceDelegate(source); + if( delegate == null ) { + // Means ignore this message/source + return; + } + + Method m = getMethod(msg.getClass()); + if( m == null ) { + throw new RuntimeException("Delegate method not found for message class:" + + msg.getClass()); + } + + try { + if( m.getParameterTypes().length > 1 ) { + m.invoke( delegate, source, msg ); + } else { + m.invoke( delegate, msg ); + } + } catch( IllegalAccessException e ) { + throw new RuntimeException("Error executing:" + m, e); + } catch( InvocationTargetException e ) { + throw new RuntimeException("Error executing:" + m, e.getCause()); + } + } +} + + diff --git a/jme3-networking/src/main/java/com/jme3/network/util/ObjectMessageDelegator.java b/jme3-networking/src/main/java/com/jme3/network/util/ObjectMessageDelegator.java new file mode 100644 index 000000000..b92ee09a8 --- /dev/null +++ b/jme3-networking/src/main/java/com/jme3/network/util/ObjectMessageDelegator.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jme3.network.util; + +import com.jme3.network.MessageConnection; + + +/** + * A MessageListener implementation that will forward messages to methods + * of a specified delegate object. These methods can be automapped or manually + * specified. + * + * @author Paul Speed + */ +public class ObjectMessageDelegator extends AbstractMessageDelegator { + + private Object delegate; + + /** + * Creates a MessageListener that will forward mapped message types + * to methods of the specified object. + * If automap is true then all methods with the proper signature will + * be mapped. + *

    Methods of the following signatures are allowed: + *

      + *
    • void someName(S conn, SomeMessage msg) + *
    • void someName(Message msg) + *
    + * Where S is the type of MessageConnection and SomeMessage is some + * specific concreate Message subclass. + */ + public ObjectMessageDelegator( Object delegate, boolean automap ) { + super(delegate.getClass(), automap); + this.delegate = delegate; + } + + @Override + protected Object getSourceDelegate( MessageConnection source ) { + return delegate; + } +} + diff --git a/jme3-networking/src/main/java/com/jme3/network/util/SessionDataDelegator.java b/jme3-networking/src/main/java/com/jme3/network/util/SessionDataDelegator.java new file mode 100644 index 000000000..f2bee3373 --- /dev/null +++ b/jme3-networking/src/main/java/com/jme3/network/util/SessionDataDelegator.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jme3.network.util; + +import com.jme3.network.HostedConnection; +import java.util.logging.Level; +import java.util.logging.Logger; + + +/** + * A MessageListener implementation that will forward messages to methods + * of a delegate specified as a HostedConnection session attribute. This is + * useful for handling connection-specific messages from clients that must + * delegate to client-specific data objects. + * The delegate methods can be automapped or manually specified. + * + * @author Paul Speed + */ +public class SessionDataDelegator extends AbstractMessageDelegator { + + static final Logger log = Logger.getLogger(SessionDataDelegator.class.getName()); + + private String attributeName; + + /** + * Creates a MessageListener that will forward mapped message types + * to methods of an object specified as a HostedConnection attribute. + * If automap is true then all methods with the proper signature will + * be mapped. + *

    Methods of the following signatures are allowed: + *

      + *
    • void someName(S conn, SomeMessage msg) + *
    • void someName(Message msg) + *
    + * Where S is the type of MessageConnection and SomeMessage is some + * specific concreate Message subclass. + */ + public SessionDataDelegator( Class delegateType, String attributeName, boolean automap ) { + super(delegateType, automap); + this.attributeName = attributeName; + } + + /** + * Returns the attribute name that will be used to look up the + * delegate object. + */ + public String getAttributeName() { + return attributeName; + } + + /** + * Called internally when there is no session object + * for the current attribute name attached to the passed source + * HostConnection. Default implementation logs a warning. + */ + protected void miss( HostedConnection source ) { + log.log(Level.WARNING, "Session data is null for:{0} on connection:{1}", new Object[]{attributeName, source}); + } + + /** + * Returns the attributeName attribute of the supplied source + * HostConnection. If there is no value at that attribute then + * the miss() method is called. + */ + protected Object getSourceDelegate( HostedConnection source ) { + Object result = source.getAttribute(attributeName); + if( result == null ) { + miss(source); + } + return result; + } +} + diff --git a/jme3-niftygui/src/main/java/com/jme3/cinematic/events/GuiEvent.java b/jme3-niftygui/src/main/java/com/jme3/cinematic/events/GuiEvent.java index 2f5d788b4..f832b4266 100644 --- a/jme3-niftygui/src/main/java/com/jme3/cinematic/events/GuiEvent.java +++ b/jme3-niftygui/src/main/java/com/jme3/cinematic/events/GuiEvent.java @@ -38,6 +38,8 @@ import com.jme3.export.JmeImporter; import com.jme3.export.OutputCapsule; import de.lessvoid.nifty.Nifty; import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; /** * @@ -45,6 +47,8 @@ import java.io.IOException; */ public class GuiEvent extends AbstractCinematicEvent { + static final Logger log = Logger.getLogger(GuiEvent.class.getName()); + protected String screen; protected Nifty nifty; @@ -76,7 +80,7 @@ public class GuiEvent extends AbstractCinematicEvent { @Override public void onPlay() { - System.out.println("screen should be " + screen); + log.log(Level.FINEST, "screen should be {0}", screen); nifty.gotoScreen(screen); } diff --git a/jme3-niftygui/src/main/java/com/jme3/niftygui/JmeBatchRenderBackend.java b/jme3-niftygui/src/main/java/com/jme3/niftygui/JmeBatchRenderBackend.java index 97f46120a..9dd831020 100644 --- a/jme3-niftygui/src/main/java/com/jme3/niftygui/JmeBatchRenderBackend.java +++ b/jme3-niftygui/src/main/java/com/jme3/niftygui/JmeBatchRenderBackend.java @@ -55,6 +55,7 @@ import com.jme3.texture.Image.Format; import com.jme3.texture.Texture.MagFilter; import com.jme3.texture.Texture.MinFilter; import com.jme3.texture.Texture2D; +import com.jme3.texture.image.ColorSpace; import com.jme3.util.BufferUtils; import de.lessvoid.nifty.render.batch.spi.BatchRenderBackend; @@ -302,7 +303,7 @@ public class JmeBatchRenderBackend implements BatchRenderBackend { initialData.rewind(); modifyTexture( getTextureAtlas(atlasTextureId), - new com.jme3.texture.Image(Format.RGBA8, image.getWidth(), image.getHeight(), initialData), + new com.jme3.texture.Image(Format.RGBA8, image.getWidth(), image.getHeight(), initialData, ColorSpace.sRGB), x, y); } @@ -338,7 +339,7 @@ public class JmeBatchRenderBackend implements BatchRenderBackend { } initialData.rewind(); - Texture2D texture = new Texture2D(new com.jme3.texture.Image(Format.RGBA8, width, height, initialData)); + Texture2D texture = new Texture2D(new com.jme3.texture.Image(Format.RGBA8, width, height, initialData, ColorSpace.sRGB)); texture.setMinFilter(MinFilter.NearestNoMipMaps); texture.setMagFilter(MagFilter.Nearest); return texture; diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/ContentTextureKey.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/ContentTextureKey.java index 06a4ec795..35375f9c5 100644 --- a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/ContentTextureKey.java +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/ContentTextureKey.java @@ -32,6 +32,8 @@ package com.jme3.scene.plugins.fbx; import com.jme3.asset.TextureKey; +import com.jme3.asset.cache.AssetCache; +import com.jme3.asset.cache.WeakRefCloneAssetCache; import com.jme3.export.InputCapsule; import com.jme3.export.JmeExporter; import com.jme3.export.JmeImporter; @@ -56,6 +58,13 @@ public class ContentTextureKey extends TextureKey { return content; } + @Override + public Class getCacheType(){ + // Need to override this so that textures embedded in FBX + // don't get cached by the asset manager. + return null; + } + @Override public String toString() { return super.toString() + " " + content.length + " bytes"; diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/FbxLoader.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/FbxLoader.java new file mode 100644 index 000000000..fd157cb48 --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/FbxLoader.java @@ -0,0 +1,413 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx; + +import com.jme3.animation.AnimControl; +import com.jme3.animation.Animation; +import com.jme3.animation.Bone; +import com.jme3.animation.BoneTrack; +import com.jme3.animation.Skeleton; +import com.jme3.animation.Track; +import com.jme3.asset.AssetInfo; +import com.jme3.asset.AssetKey; +import com.jme3.asset.AssetLoadException; +import com.jme3.asset.AssetLoader; +import com.jme3.asset.AssetManager; +import com.jme3.asset.ModelKey; +import com.jme3.math.Matrix4f; +import com.jme3.math.Transform; +import com.jme3.scene.Node; +import com.jme3.scene.Spatial; +import com.jme3.scene.plugins.fbx.anim.FbxToJmeTrack; +import com.jme3.scene.plugins.fbx.anim.FbxAnimCurveNode; +import com.jme3.scene.plugins.fbx.anim.FbxAnimLayer; +import com.jme3.scene.plugins.fbx.anim.FbxAnimStack; +import com.jme3.scene.plugins.fbx.anim.FbxBindPose; +import com.jme3.scene.plugins.fbx.anim.FbxLimbNode; +import com.jme3.scene.plugins.fbx.file.FbxDump; +import com.jme3.scene.plugins.fbx.file.FbxElement; +import com.jme3.scene.plugins.fbx.file.FbxFile; +import com.jme3.scene.plugins.fbx.file.FbxReader; +import com.jme3.scene.plugins.fbx.file.FbxId; +import com.jme3.scene.plugins.fbx.misc.FbxGlobalSettings; +import com.jme3.scene.plugins.fbx.node.FbxNode; +import com.jme3.scene.plugins.fbx.node.FbxRootNode; +import com.jme3.scene.plugins.fbx.obj.FbxObjectFactory; +import com.jme3.scene.plugins.fbx.obj.FbxObject; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class FbxLoader implements AssetLoader { + + private static final Logger logger = Logger.getLogger(FbxLoader.class.getName()); + + private AssetManager assetManager; + + private String sceneName; + private String sceneFilename; + private String sceneFolderName; + private FbxGlobalSettings globalSettings; + private final Map objectMap = new HashMap(); + + private final List animStacks = new ArrayList(); + private final List bindPoses = new ArrayList(); + + @Override + public Object load(AssetInfo assetInfo) throws IOException { + this.assetManager = assetInfo.getManager(); + AssetKey assetKey = assetInfo.getKey(); + if (!(assetKey instanceof ModelKey)) { + throw new AssetLoadException("Invalid asset key"); + } + + InputStream stream = assetInfo.openStream(); + try { + sceneFilename = assetKey.getName(); + sceneFolderName = assetKey.getFolder(); + String ext = assetKey.getExtension(); + + sceneName = sceneFilename.substring(0, sceneFilename.length() - ext.length() - 1); + if (sceneFolderName != null && sceneFolderName.length() > 0) { + sceneName = sceneName.substring(sceneFolderName.length()); + } + + reset(); + + // Load the data from the stream. + loadData(stream); + + // Bind poses are needed to compute world transforms. + applyBindPoses(); + + // Need world transforms for skeleton creation. + updateWorldTransforms(); + + // Need skeletons for meshs to be created in scene graph construction. + // Mesh bone indices require skeletons to determine bone index. + constructSkeletons(); + + // Create the jME3 scene graph from the FBX scene graph. + // Also creates SkeletonControls based on the constructed skeletons. + Spatial scene = constructSceneGraph(); + + // Load animations into AnimControls + constructAnimations(); + + return scene; + } finally { + releaseObjects(); + if (stream != null) { + stream.close(); + } + } + } + + private void reset() { + globalSettings = new FbxGlobalSettings(); + } + + private void releaseObjects() { + globalSettings = null; + objectMap.clear(); + animStacks.clear(); + } + + private void loadData(InputStream stream) throws IOException { + FbxFile scene = FbxReader.readFBX(stream); + + FbxDump.dumpFile(scene); + + // TODO: Load FBX object templates + + for (FbxElement e : scene.rootElements) { + if (e.id.equals("FBXHeaderExtension")) { + loadHeader(e); + } else if (e.id.equals("GlobalSettings")) { + loadGlobalSettings(e); + } else if (e.id.equals("Objects")) { + loadObjects(e); + } else if (e.id.equals("Connections")) { + connectObjects(e); + } + } + } + + private void loadHeader(FbxElement element) { + for (FbxElement e : element.children) { + if (e.id.equals("FBXVersion")) { + Integer version = (Integer) e.properties.get(0); + if (version < 7100) { + logger.log(Level.WARNING, "FBX file version is older than 7.1. " + + "Some features may not work."); + } + } + } + } + + private void loadGlobalSettings(FbxElement element) { + globalSettings = new FbxGlobalSettings(); + globalSettings.fromElement(element); + } + + private void loadObjects(FbxElement element) { + // Initialize the FBX root element. + objectMap.put(FbxId.ROOT, new FbxRootNode(assetManager, sceneFolderName)); + + for(FbxElement e : element.children) { + if (e.id.equals("GlobalSettings")) { + // Old FBX files seem to have the GlobalSettings element + // under Objects (??) + globalSettings.fromElement(e); + } else { + FbxObject object = FbxObjectFactory.createObject(e, assetManager, sceneFolderName); + if (object != null) { + if (objectMap.containsKey(object.getId())) { + logger.log(Level.WARNING, "An object with ID \"{0}\" has " + + "already been defined. " + + "Ignoring.", + object.getId()); + } + + objectMap.put(object.getId(), object); + + if (object instanceof FbxAnimStack) { + // NOTE: animation stacks are implicitly global. + // Capture them here. + animStacks.add((FbxAnimStack) object); + } else if (object instanceof FbxBindPose) { + bindPoses.add((FbxBindPose) object); + } + } else { + throw new UnsupportedOperationException("Failed to create FBX object of type: " + e.id); + } + } + } + } + + private void removeUnconnectedObjects() { + for (FbxObject object : new ArrayList(objectMap.values())) { + if (!object.isJmeObjectCreated()) { + logger.log(Level.WARNING, "Purging orphan FBX object: {0}", object); + objectMap.remove(object.getId()); + } + } + } + + private void connectObjects(FbxElement element) { + if (objectMap.isEmpty()) { + logger.log(Level.WARNING, "FBX file is missing object information"); + return; + } else if (objectMap.size() == 1) { + // Only root node (automatically added by jME3) + logger.log(Level.WARNING, "FBX file has no objects"); + return; + } + + for (FbxElement el : element.children) { + if (!el.id.equals("C") && !el.id.equals("Connect")) { + continue; + } + String type = (String) el.properties.get(0); + FbxId childId; + FbxId parentId; + if (type.equals("OO")) { + childId = FbxId.create(el.properties.get(1)); + parentId = FbxId.create(el.properties.get(2)); + FbxObject child = objectMap.get(childId); + FbxObject parent; + + if (parentId.isNull()) { + // TODO: maybe clean this up a bit.. + parent = objectMap.get(FbxId.ROOT); + } else { + parent = objectMap.get(parentId); + } + + if (parent == null) { + throw new UnsupportedOperationException("Cannot find parent object ID \"" + parentId + "\""); + } + + parent.connectObject(child); + } else if (type.equals("OP")) { + childId = FbxId.create(el.properties.get(1)); + parentId = FbxId.create(el.properties.get(2)); + String propName = (String) el.properties.get(3); + FbxObject child = objectMap.get(childId); + FbxObject parent = objectMap.get(parentId); + parent.connectObjectProperty(child, propName); + } else { + logger.log(Level.WARNING, "Unknown connection type: {0}. Ignoring.", type); + } + } + } + + /** + * Copies the bind poses from FBX BindPose objects to FBX nodes. + * Must be called prior to {@link #updateWorldTransforms()}. + */ + private void applyBindPoses() { + for (FbxBindPose bindPose : bindPoses) { + Map bindPoseData = bindPose.getJmeObject(); + logger.log(Level.INFO, "Applying {0} bind poses", bindPoseData.size()); + for (Map.Entry entry : bindPoseData.entrySet()) { + FbxObject obj = objectMap.get(entry.getKey()); + if (obj instanceof FbxNode) { + FbxNode node = (FbxNode) obj; + node.setWorldBindPose(entry.getValue()); + } else { + logger.log(Level.WARNING, "Bind pose can only be applied to FBX nodes. Ignoring."); + } + } + } + } + + /** + * Updates world transforms and bind poses for the FBX scene graph. + */ + private void updateWorldTransforms() { + FbxNode fbxRoot = (FbxNode) objectMap.get(FbxId.ROOT); + fbxRoot.updateWorldTransforms(null, null); + } + + private void constructAnimations() { + // In FBX, animation are not attached to any root. + // They are implicitly global. + // So, we need to use hueristics to find which node(s) + // an animation is associated with, so we can create the AnimControl + // in the appropriate location in the scene. + Map pairs = new HashMap(); + for (FbxAnimStack stack : animStacks) { + for (FbxAnimLayer layer : stack.getLayers()) { + for (FbxAnimCurveNode curveNode : layer.getAnimationCurveNodes()) { + for (Map.Entry nodePropertyEntry : curveNode.getInfluencedNodeProperties().entrySet()) { + FbxToJmeTrack lookupPair = new FbxToJmeTrack(); + lookupPair.animStack = stack; + lookupPair.animLayer = layer; + lookupPair.node = nodePropertyEntry.getKey(); + + // Find if this pair is already stored + FbxToJmeTrack storedPair = pairs.get(lookupPair); + if (storedPair == null) { + // If not, store it. + storedPair = lookupPair; + pairs.put(storedPair, storedPair); + } + + String property = nodePropertyEntry.getValue(); + storedPair.animCurves.put(property, curveNode); + } + } + } + } + + // At this point we can construct the animation for all pairs ... + for (FbxToJmeTrack pair : pairs.values()) { + String animName = pair.animStack.getName(); + float duration = pair.animStack.getDuration(); + + System.out.println("ANIMATION: " + animName + ", duration = " + duration); + System.out.println("NODE: " + pair.node.getName()); + + duration = pair.getDuration(); + + if (pair.node instanceof FbxLimbNode) { + // Find the spatial that has the skeleton for this limb. + FbxLimbNode limbNode = (FbxLimbNode) pair.node; + Bone bone = limbNode.getJmeBone(); + Spatial jmeSpatial = limbNode.getSkeletonHolder().getJmeObject(); + Skeleton skeleton = limbNode.getSkeletonHolder().getJmeSkeleton(); + + // Get the animation control (create if missing). + AnimControl animControl = jmeSpatial.getControl(AnimControl.class); + if (animControl.getSkeleton() != skeleton) { + throw new UnsupportedOperationException(); + } + + // Get the animation (create if missing). + Animation anim = animControl.getAnim(animName); + if (anim == null) { + anim = new Animation(animName, duration); + animControl.addAnim(anim); + } + + // Find the bone index from the spatial's skeleton. + int boneIndex = skeleton.getBoneIndex(bone); + + // Generate the bone track. + BoneTrack bt = pair.toJmeBoneTrack(boneIndex, bone.getBindInverseTransform()); + + // Add the bone track to the animation. + anim.addTrack(bt); + } else { + // Create the spatial animation + Animation anim = new Animation(animName, duration); + anim.setTracks(new Track[]{ pair.toJmeSpatialTrack() }); + + // Get the animation control (create if missing). + Spatial jmeSpatial = pair.node.getJmeObject(); + AnimControl animControl = jmeSpatial.getControl(AnimControl.class); + + if (animControl == null) { + animControl = new AnimControl(null); + jmeSpatial.addControl(animControl); + } + + // Add the spatial animation + animControl.addAnim(anim); + } + } + } + + private void constructSkeletons() { + FbxNode fbxRoot = (FbxNode) objectMap.get(FbxId.ROOT); + FbxNode.createSkeletons(fbxRoot); + } + + private Spatial constructSceneGraph() { + // Acquire the implicit root object. + FbxNode fbxRoot = (FbxNode) objectMap.get(FbxId.ROOT); + + // Convert it into a jME3 scene + Node jmeRoot = (Node) FbxNode.createScene(fbxRoot); + + // Fix the name (will probably be set to something like "-node") + jmeRoot.setName(sceneName + "-scene"); + + return jmeRoot; + } +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/SceneLoader.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/SceneLoader.java index e767763e1..491301c22 100644 --- a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/SceneLoader.java +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/SceneLoader.java @@ -73,9 +73,9 @@ import com.jme3.scene.Mesh.Mode; import com.jme3.scene.VertexBuffer.Type; import com.jme3.scene.VertexBuffer.Usage; import com.jme3.scene.plugins.fbx.AnimationList.AnimInverval; -import com.jme3.scene.plugins.fbx.file.FBXElement; -import com.jme3.scene.plugins.fbx.file.FBXFile; -import com.jme3.scene.plugins.fbx.file.FBXReader; +import com.jme3.scene.plugins.fbx.file.FbxElement; +import com.jme3.scene.plugins.fbx.file.FbxFile; +import com.jme3.scene.plugins.fbx.file.FbxReader; import com.jme3.texture.Image; import com.jme3.texture.Texture; import com.jme3.texture.Texture2D; @@ -165,8 +165,8 @@ public class SceneLoader implements AssetLoader { private void loadScene(InputStream stream) throws IOException { logger.log(Level.FINE, "Loading scene {0}", sceneFilename); long startTime = System.currentTimeMillis(); - FBXFile scene = FBXReader.readFBX(stream); - for(FBXElement e : scene.rootElements) { + FbxFile scene = FbxReader.readFBX(stream); + for(FbxElement e : scene.rootElements) { if(e.id.equals("GlobalSettings")) loadGlobalSettings(e); else if(e.id.equals("Objects")) @@ -178,10 +178,10 @@ public class SceneLoader implements AssetLoader { logger.log(Level.FINE, "Loading done in {0} ms", estimatedTime); } - private void loadGlobalSettings(FBXElement element) { - for(FBXElement e : element.children) { + private void loadGlobalSettings(FbxElement element) { + for(FbxElement e : element.children) { if(e.id.equals("Properties70")) { - for(FBXElement e2 : e.children) { + for(FbxElement e2 : e.children) { if(e2.id.equals("P")) { String propName = (String) e2.properties.get(0); if(propName.equals("UnitScaleFactor")) @@ -197,8 +197,8 @@ public class SceneLoader implements AssetLoader { } } - private void loadObjects(FBXElement element) { - for(FBXElement e : element.children) { + private void loadObjects(FbxElement element) { + for(FbxElement e : element.children) { if(e.id.equals("Geometry")) loadGeometry(e); else if(e.id.equals("Material")) @@ -222,12 +222,12 @@ public class SceneLoader implements AssetLoader { } } - private void loadGeometry(FBXElement element) { + private void loadGeometry(FbxElement element) { long id = (Long) element.properties.get(0); String type = (String) element.properties.get(2); if(type.equals("Mesh")) { MeshData data = new MeshData(); - for(FBXElement e : element.children) { + for(FbxElement e : element.children) { if(e.id.equals("Vertices")) data.vertices = (double[]) e.properties.get(0); else if(e.id.equals("PolygonVertexIndex")) @@ -236,7 +236,7 @@ public class SceneLoader implements AssetLoader { //else if(e.id.equals("Edges")) // data.edges = (int[]) e.properties.get(0); else if(e.id.equals("LayerElementNormal")) - for(FBXElement e2 : e.children) { + for(FbxElement e2 : e.children) { if(e2.id.equals("MappingInformationType")) { data.normalsMapping = (String) e2.properties.get(0); if(!data.normalsMapping.equals("ByVertice") && !data.normalsMapping.equals("ByPolygonVertex")) @@ -249,7 +249,7 @@ public class SceneLoader implements AssetLoader { data.normals = (double[]) e2.properties.get(0); } else if(e.id.equals("LayerElementTangent")) - for(FBXElement e2 : e.children) { + for(FbxElement e2 : e.children) { if(e2.id.equals("MappingInformationType")) { data.tangentsMapping = (String) e2.properties.get(0); if(!data.tangentsMapping.equals("ByVertice") && !data.tangentsMapping.equals("ByPolygonVertex")) @@ -262,7 +262,7 @@ public class SceneLoader implements AssetLoader { data.tangents = (double[]) e2.properties.get(0); } else if(e.id.equals("LayerElementBinormal")) - for(FBXElement e2 : e.children) { + for(FbxElement e2 : e.children) { if(e2.id.equals("MappingInformationType")) { data.binormalsMapping = (String) e2.properties.get(0); if(!data.binormalsMapping.equals("ByVertice") && !data.binormalsMapping.equals("ByPolygonVertex")) @@ -275,7 +275,7 @@ public class SceneLoader implements AssetLoader { data.binormals = (double[]) e2.properties.get(0); } else if(e.id.equals("LayerElementUV")) - for(FBXElement e2 : e.children) { + for(FbxElement e2 : e.children) { if(e2.id.equals("MappingInformationType")) { data.uvMapping = (String) e2.properties.get(0); if(!data.uvMapping.equals("ByPolygonVertex")) @@ -291,7 +291,7 @@ public class SceneLoader implements AssetLoader { } // TODO smoothing is not used now //else if(e.id.equals("LayerElementSmoothing")) - // for(FBXElement e2 : e.children) { + // for(FbxElement e2 : e.children) { // if(e2.id.equals("MappingInformationType")) { // data.smoothingMapping = (String) e2.properties.get(0); // if(!data.smoothingMapping.equals("ByEdge")) @@ -304,7 +304,7 @@ public class SceneLoader implements AssetLoader { // data.smoothing = (int[]) e2.properties.get(0); // } else if(e.id.equals("LayerElementMaterial")) - for(FBXElement e2 : e.children) { + for(FbxElement e2 : e.children) { if(e2.id.equals("MappingInformationType")) { data.materialsMapping = (String) e2.properties.get(0); if(!data.materialsMapping.equals("AllSame")) @@ -321,18 +321,18 @@ public class SceneLoader implements AssetLoader { } } - private void loadMaterial(FBXElement element) { + private void loadMaterial(FbxElement element) { long id = (Long) element.properties.get(0); String path = (String) element.properties.get(1); String type = (String) element.properties.get(2); if(type.equals("")) { MaterialData data = new MaterialData(); data.name = path.substring(0, path.indexOf(0)); - for(FBXElement e : element.children) { + for(FbxElement e : element.children) { if(e.id.equals("ShadingModel")) { data.shadingModel = (String) e.properties.get(0); } else if(e.id.equals("Properties70")) { - for(FBXElement e2 : e.children) { + for(FbxElement e2 : e.children) { if(e2.id.equals("P")) { String propName = (String) e2.properties.get(0); if(propName.equals("AmbientColor")) { @@ -368,16 +368,16 @@ public class SceneLoader implements AssetLoader { } } - private void loadModel(FBXElement element) { + private void loadModel(FbxElement element) { long id = (Long) element.properties.get(0); String path = (String) element.properties.get(1); String type = (String) element.properties.get(2); ModelData data = new ModelData(); data.name = path.substring(0, path.indexOf(0)); data.type = type; - for(FBXElement e : element.children) { + for(FbxElement e : element.children) { if(e.id.equals("Properties70")) { - for(FBXElement e2 : e.children) { + for(FbxElement e2 : e.children) { if(e2.id.equals("P")) { String propName = (String) e2.properties.get(0); if(propName.equals("Lcl Translation")) { @@ -408,17 +408,17 @@ public class SceneLoader implements AssetLoader { modelDataMap.put(id, data); } - private void loadPose(FBXElement element) { + private void loadPose(FbxElement element) { long id = (Long) element.properties.get(0); String path = (String) element.properties.get(1); String type = (String) element.properties.get(2); if(type.equals("BindPose")) { BindPoseData data = new BindPoseData(); data.name = path.substring(0, path.indexOf(0)); - for(FBXElement e : element.children) { + for(FbxElement e : element.children) { if(e.id.equals("PoseNode")) { NodeTransformData item = new NodeTransformData(); - for(FBXElement e2 : e.children) { + for(FbxElement e2 : e.children) { if(e2.id.equals("Node")) item.nodeId = (Long) e2.properties.get(0); else if(e2.id.equals("Matrix")) @@ -431,14 +431,14 @@ public class SceneLoader implements AssetLoader { } } - private void loadTexture(FBXElement element) { + private void loadTexture(FbxElement element) { long id = (Long) element.properties.get(0); String path = (String) element.properties.get(1); String type = (String) element.properties.get(2); if(type.equals("")) { TextureData data = new TextureData(); data.name = path.substring(0, path.indexOf(0)); - for(FBXElement e : element.children) { + for(FbxElement e : element.children) { if(e.id.equals("Type")) data.bindType = (String) e.properties.get(0); else if(e.id.equals("FileName")) @@ -448,14 +448,14 @@ public class SceneLoader implements AssetLoader { } } - private void loadImage(FBXElement element) { + private void loadImage(FbxElement element) { long id = (Long) element.properties.get(0); String path = (String) element.properties.get(1); String type = (String) element.properties.get(2); if(type.equals("Clip")) { ImageData data = new ImageData(); data.name = path.substring(0, path.indexOf(0)); - for(FBXElement e : element.children) { + for(FbxElement e : element.children) { if(e.id.equals("Type")) data.type = (String) e.properties.get(0); else if(e.id.equals("FileName")) @@ -471,19 +471,19 @@ public class SceneLoader implements AssetLoader { } } - private void loadDeformer(FBXElement element) { + private void loadDeformer(FbxElement element) { long id = (Long) element.properties.get(0); String type = (String) element.properties.get(2); if(type.equals("Skin")) { SkinData skinData = new SkinData(); - for(FBXElement e : element.children) { + for(FbxElement e : element.children) { if(e.id.equals("SkinningType")) skinData.type = (String) e.properties.get(0); } skinMap.put(id, skinData); } else if(type.equals("Cluster")) { ClusterData clusterData = new ClusterData(); - for(FBXElement e : element.children) { + for(FbxElement e : element.children) { if(e.id.equals("Indexes")) clusterData.indexes = (int[]) e.properties.get(0); else if(e.id.equals("Weights")) @@ -497,7 +497,7 @@ public class SceneLoader implements AssetLoader { } } - private void loadAnimLayer(FBXElement element) { + private void loadAnimLayer(FbxElement element) { long id = (Long) element.properties.get(0); String path = (String) element.properties.get(1); String type = (String) element.properties.get(2); @@ -508,12 +508,12 @@ public class SceneLoader implements AssetLoader { } } - private void loadAnimCurve(FBXElement element) { + private void loadAnimCurve(FbxElement element) { long id = (Long) element.properties.get(0); String type = (String) element.properties.get(2); if(type.equals("")) { AnimCurveData data = new AnimCurveData(); - for(FBXElement e : element.children) { + for(FbxElement e : element.children) { if(e.id.equals("KeyTime")) data.keyTimes = (long[]) e.properties.get(0); else if(e.id.equals("KeyValueFloat")) @@ -523,15 +523,15 @@ public class SceneLoader implements AssetLoader { } } - private void loadAnimNode(FBXElement element) { + private void loadAnimNode(FbxElement element) { long id = (Long) element.properties.get(0); String path = (String) element.properties.get(1); String type = (String) element.properties.get(2); if(type.equals("")) { Double x = null, y = null, z = null; - for(FBXElement e : element.children) { + for(FbxElement e : element.children) { if(e.id.equals("Properties70")) { - for(FBXElement e2 : e.children) { + for(FbxElement e2 : e.children) { if(e2.id.equals("P")) { String propName = (String) e2.properties.get(0); if(propName.equals("d|X")) @@ -554,8 +554,8 @@ public class SceneLoader implements AssetLoader { } } - private void loadConnections(FBXElement element) { - for(FBXElement e : element.children) { + private void loadConnections(FbxElement element) { + for(FbxElement e : element.children) { if(e.id.equals("C")) { String type = (String) e.properties.get(0); long objId, refId; diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxAnimCurve.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxAnimCurve.java new file mode 100644 index 000000000..d266dcf95 --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxAnimCurve.java @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.anim; + +import com.jme3.asset.AssetManager; +import com.jme3.math.FastMath; +import com.jme3.scene.plugins.fbx.file.FbxElement; +import com.jme3.scene.plugins.fbx.obj.FbxObject; + +public class FbxAnimCurve extends FbxObject { + + private long[] keyTimes; + private float[] keyValues; + + public FbxAnimCurve(AssetManager assetManager, String sceneFolderName) { + super(assetManager, sceneFolderName); + } + + @Override + public void fromElement(FbxElement element) { + super.fromElement(element); + + for (FbxElement e : element.children) { + if (e.id.equals("KeyTime")) { + keyTimes = (long[]) e.properties.get(0); + } else if (e.id.equals("KeyValueFloat")) { + keyValues = (float[]) e.properties.get(0); + } + } + + long time = -1; + for (int i = 0; i < keyTimes.length; i++) { + if (time >= keyTimes[i]) { + throw new UnsupportedOperationException("Keyframe times must be sequential, but they are not."); + } + time = keyTimes[i]; + } + } + + /** + * Get the times for the keyframes. + * @return Keyframe times. + */ + public long[] getKeyTimes() { + return keyTimes; + } + + /** + * Retrieve the curve value at the given time. + * If the curve has no data, 0 is returned. + * If the time is outside the curve, then the closest value is returned. + * If the time isn't on an exact keyframe, linear interpolation is used + * to determine the value between the keyframes at the given time. + * @param time The time to get the curve value at (in FBX time units). + * @return The value at the given time. + */ + public float getValueAtTime(long time) { + if (keyTimes.length == 0) { + return 0; + } + + // If the time is outside the range, + // we just return the closest value. (No extrapolation) + if (time <= keyTimes[0]) { + return keyValues[0]; + } else if (time >= keyTimes[keyTimes.length - 1]) { + return keyValues[keyValues.length - 1]; + } + + + + int startFrame = 0; + int endFrame = 1; + int lastFrame = keyTimes.length - 1; + + for (int i = 0; i < lastFrame && keyTimes[i] < time; ++i) { + startFrame = i; + endFrame = i + 1; + } + + long keyTime1 = keyTimes[startFrame]; + float keyValue1 = keyValues[startFrame]; + long keyTime2 = keyTimes[endFrame]; + float keyValue2 = keyValues[endFrame]; + + if (keyTime2 == time) { + return keyValue2; + } + + long prevToNextDelta = keyTime2 - keyTime1; + long prevToCurrentDelta = time - keyTime1; + float lerpAmount = (float)prevToCurrentDelta / prevToNextDelta; + + return FastMath.interpolateLinear(lerpAmount, keyValue1, keyValue2); + } + + @Override + protected Object toJmeObject() { + // An AnimCurve has no jME3 representation. + // The parent AnimCurveNode is responsible to create the jME3 + // representation. + throw new UnsupportedOperationException("No jME3 object conversion available"); + } + + @Override + public void connectObject(FbxObject object) { + unsupportedConnectObject(object); + } + + @Override + public void connectObjectProperty(FbxObject object, String property) { + unsupportedConnectObjectProperty(object, property); + } + +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxAnimCurveNode.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxAnimCurveNode.java new file mode 100644 index 000000000..e8dbe7fc0 --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxAnimCurveNode.java @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.anim; + +import com.jme3.asset.AssetManager; +import com.jme3.math.FastMath; +import com.jme3.math.Quaternion; +import com.jme3.math.Vector3f; +import com.jme3.scene.plugins.fbx.file.FbxElement; +import com.jme3.scene.plugins.fbx.node.FbxNode; +import com.jme3.scene.plugins.fbx.obj.FbxObject; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class FbxAnimCurveNode extends FbxObject { + + private static final Logger logger = Logger.getLogger(FbxAnimCurveNode.class.getName()); + + private final Map influencedNodePropertiesMap = new HashMap(); + private final Map propertyToCurveMap = new HashMap(); + private final Map propertyToDefaultMap = new HashMap(); + + public FbxAnimCurveNode(AssetManager assetManager, String sceneFolderName) { + super(assetManager, sceneFolderName); + } + + @Override + public void fromElement(FbxElement element) { + super.fromElement(element); + for (FbxElement prop : element.getFbxProperties()) { + String propName = (String) prop.properties.get(0); + String propType = (String) prop.properties.get(1); + if (propType.equals("Number")) { + float propValue = ((Double) prop.properties.get(4)).floatValue(); + propertyToDefaultMap.put(propName, propValue); + } + } + } + + public void addInfluencedNode(FbxNode node, String property) { + influencedNodePropertiesMap.put(node, property); + } + + public Map getInfluencedNodeProperties() { + return influencedNodePropertiesMap; + } + + public Collection getCurves() { + return propertyToCurveMap.values(); + } + + public Vector3f getVector3Value(long time) { + Vector3f value = new Vector3f(); + FbxAnimCurve xCurve = propertyToCurveMap.get(FbxAnimUtil.CURVE_NODE_PROPERTY_X); + FbxAnimCurve yCurve = propertyToCurveMap.get(FbxAnimUtil.CURVE_NODE_PROPERTY_Y); + FbxAnimCurve zCurve = propertyToCurveMap.get(FbxAnimUtil.CURVE_NODE_PROPERTY_Z); + Float xDefault = propertyToDefaultMap.get(FbxAnimUtil.CURVE_NODE_PROPERTY_X); + Float yDefault = propertyToDefaultMap.get(FbxAnimUtil.CURVE_NODE_PROPERTY_Y); + Float zDefault = propertyToDefaultMap.get(FbxAnimUtil.CURVE_NODE_PROPERTY_Z); + value.x = xCurve != null ? xCurve.getValueAtTime(time) : xDefault; + value.y = yCurve != null ? yCurve.getValueAtTime(time) : yDefault; + value.z = zCurve != null ? zCurve.getValueAtTime(time) : zDefault; + return value; + } + + /** + * Converts the euler angles from {@link #getVector3Value(long)} to + * a quaternion rotation. + * @param time Time at which to get the euler angles. + * @return The rotation at time + */ + public Quaternion getQuaternionValue(long time) { + Vector3f eulerAngles = getVector3Value(time); + System.out.println("\tT: " + time + ". Rotation: " + + eulerAngles.x + ", " + + eulerAngles.y + ", " + eulerAngles.z); + Quaternion q = new Quaternion(); + q.fromAngles(eulerAngles.x * FastMath.DEG_TO_RAD, + eulerAngles.y * FastMath.DEG_TO_RAD, + eulerAngles.z * FastMath.DEG_TO_RAD); + return q; + } + + @Override + protected Object toJmeObject() { + throw new UnsupportedOperationException(); + } + + @Override + public void connectObject(FbxObject object) { + unsupportedConnectObject(object); + } + + @Override + public void connectObjectProperty(FbxObject object, String property) { + if (!(object instanceof FbxAnimCurve)) { + unsupportedConnectObjectProperty(object, property); + } + if (!property.equals(FbxAnimUtil.CURVE_NODE_PROPERTY_X) && + !property.equals(FbxAnimUtil.CURVE_NODE_PROPERTY_Y) && + !property.equals(FbxAnimUtil.CURVE_NODE_PROPERTY_Z) && + !property.equals(FbxAnimUtil.CURVE_NODE_PROPERTY_VISIBILITY)) { + logger.log(Level.WARNING, "Animating the dimension ''{0}'' is not " + + "supported yet. Ignoring.", property); + return; + } + + if (propertyToCurveMap.containsKey(property)) { + throw new UnsupportedOperationException("!"); + } + + propertyToCurveMap.put(property, (FbxAnimCurve) object); + } + +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxAnimLayer.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxAnimLayer.java new file mode 100644 index 000000000..872626615 --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxAnimLayer.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.anim; + +import com.jme3.asset.AssetManager; +import com.jme3.scene.plugins.fbx.file.FbxElement; +import com.jme3.scene.plugins.fbx.obj.FbxObject; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.logging.Logger; + +public class FbxAnimLayer extends FbxObject { + + private static final Logger logger = Logger.getLogger(FbxAnimLayer.class.getName()); + + private final List animCurves = new ArrayList(); + + public FbxAnimLayer(AssetManager assetManager, String sceneFolderName) { + super(assetManager, sceneFolderName); + } + + @Override + public void fromElement(FbxElement element) { + super.fromElement(element); + // No known properties for layers.. + // Also jME3 doesn't support multiple layers anyway. + } + + public List getAnimationCurveNodes() { + return Collections.unmodifiableList(animCurves); + } + + @Override + protected Object toJmeObject() { + throw new UnsupportedOperationException(); + } + + @Override + public void connectObject(FbxObject object) { + if (!(object instanceof FbxAnimCurveNode)) { + unsupportedConnectObject(object); + } + + animCurves.add((FbxAnimCurveNode) object); + } + + @Override + public void connectObjectProperty(FbxObject object, String property) { + unsupportedConnectObjectProperty(object, property); + } +} + \ No newline at end of file diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxAnimStack.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxAnimStack.java new file mode 100644 index 000000000..ea7dbb814 --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxAnimStack.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.anim; + +import com.jme3.asset.AssetManager; +import com.jme3.scene.plugins.fbx.file.FbxElement; +import com.jme3.scene.plugins.fbx.obj.FbxObject; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class FbxAnimStack extends FbxObject { + + private static final Logger logger = Logger.getLogger(FbxAnimStack.class.getName()); + + private float duration; + private FbxAnimLayer layer0; + + public FbxAnimStack(AssetManager assetManager, String sceneFolderName) { + super(assetManager, sceneFolderName); + } + + @Override + public void fromElement(FbxElement element) { + super.fromElement(element); + for (FbxElement child : element.getFbxProperties()) { + String propName = (String) child.properties.get(0); + if (propName.equals("LocalStop")) { + long durationLong = (Long)child.properties.get(4); + duration = (float) (durationLong * FbxAnimUtil.SECONDS_PER_UNIT); + } + } + } + +// /** +// * Finds out which FBX nodes this animation is going to influence. +// * +// * @return A list of FBX nodes that the stack's curves are influencing. +// */ +// public Set getInfluencedNodes() { +// HashSet influencedNodes = new HashSet(); +// if (layer0 == null) { +// return influencedNodes; +// } +// for (FbxAnimCurveNode curveNode : layer0.getAnimationCurveNodes()) { +// influencedNodes.addAll(curveNode.getInfluencedNodes()); +// } +// return influencedNodes; +// } + + public float getDuration() { + return duration; + } + + public FbxAnimLayer[] getLayers() { + return new FbxAnimLayer[]{ layer0 }; + } + + @Override + protected Object toJmeObject() { + throw new UnsupportedOperationException(); + } + + @Override + public void connectObject(FbxObject object) { + if (!(object instanceof FbxAnimLayer)) { + unsupportedConnectObject(object); + } + + if (layer0 != null) { + logger.log(Level.WARNING, "jME3 does not support layered animation. " + + "Only first layer has been loaded."); + return; + } + + layer0 = (FbxAnimLayer) object; + } + + @Override + public void connectObjectProperty(FbxObject object, String property) { + unsupportedConnectObjectProperty(object, property); + } +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxAnimUtil.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxAnimUtil.java new file mode 100644 index 000000000..c376757de --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxAnimUtil.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.anim; + +public class FbxAnimUtil { + /** + * Conversion factor from FBX animation time unit to seconds. + */ + public static final double SECONDS_PER_UNIT = 1 / 46186158000d; + + public static final String CURVE_NODE_PROPERTY_X = "d|X"; + public static final String CURVE_NODE_PROPERTY_Y = "d|Y"; + public static final String CURVE_NODE_PROPERTY_Z = "d|Z"; + public static final String CURVE_NODE_PROPERTY_VISIBILITY = "d|Visibility"; +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxBindPose.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxBindPose.java new file mode 100644 index 000000000..78d37c74e --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxBindPose.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.anim; + +import com.jme3.asset.AssetManager; +import com.jme3.math.Matrix4f; +import com.jme3.scene.plugins.fbx.file.FbxElement; +import com.jme3.scene.plugins.fbx.file.FbxId; +import com.jme3.scene.plugins.fbx.obj.FbxObject; +import java.util.HashMap; +import java.util.Map; + +public class FbxBindPose extends FbxObject> { + + private final Map bindPose = new HashMap(); + + public FbxBindPose(AssetManager assetManager, String sceneFolderName) { + super(assetManager, sceneFolderName); + } + + @Override + public void fromElement(FbxElement element) { + super.fromElement(element); + for (FbxElement child : element.children) { + if (!child.id.equals("PoseNode")) { + continue; + } + + FbxId node = null; + float[] matData = null; + + for (FbxElement e : child.children) { + if (e.id.equals("Node")) { + node = FbxId.create(e.properties.get(0)); + } else if (e.id.equals("Matrix")) { + double[] matDataDoubles = (double[]) e.properties.get(0); + + if (matDataDoubles.length != 16) { + // corrupt + throw new UnsupportedOperationException("Bind pose matrix " + + "must have 16 doubles, but it has " + + matDataDoubles.length + ". Data is corrupt"); + } + + matData = new float[16]; + for (int i = 0; i < matDataDoubles.length; i++) { + matData[i] = (float) matDataDoubles[i]; + } + } + } + + if (node != null && matData != null) { + Matrix4f matrix = new Matrix4f(matData); + bindPose.put(node, matrix); + } + } + } + + @Override + protected Map toJmeObject() { + return bindPose; + } + + @Override + public void connectObject(FbxObject object) { + unsupportedConnectObject(object); + } + + @Override + public void connectObjectProperty(FbxObject object, String property) { + unsupportedConnectObjectProperty(object, property); + } + +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxCluster.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxCluster.java new file mode 100644 index 000000000..3065ce88c --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxCluster.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.anim; + +import com.jme3.asset.AssetManager; +import com.jme3.scene.plugins.fbx.file.FbxElement; +import com.jme3.scene.plugins.fbx.obj.FbxObject; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class FbxCluster extends FbxObject { + + private static final Logger logger = Logger.getLogger(FbxCluster.class.getName()); + + private int[] indexes; + private double[] weights; + private FbxLimbNode limb; + + public FbxCluster(AssetManager assetManager, String sceneFolderName) { + super(assetManager, sceneFolderName); + } + + @Override + public void fromElement(FbxElement element) { + super.fromElement(element); + for (FbxElement e : element.children) { + if (e.id.equals("Indexes")) { + indexes = (int[]) e.properties.get(0); + } else if (e.id.equals("Weights")) { + weights = (double[]) e.properties.get(0); + } + } + } + + public int[] getVertexIndices() { + return indexes; + } + + public double[] getWeights() { + return weights; + } + + public FbxLimbNode getLimb() { + return limb; + } + + @Override + protected Object toJmeObject() { + throw new UnsupportedOperationException(); + } + + @Override + public void connectObject(FbxObject object) { + if (object instanceof FbxLimbNode) { + if (limb != null) { + logger.log(Level.WARNING, "This cluster already has a limb attached. Ignoring."); + return; + } + limb = (FbxLimbNode) object; + } else { + unsupportedConnectObject(object); + } + } + + @Override + public void connectObjectProperty(FbxObject object, String property) { + unsupportedConnectObjectProperty(object, property); + } +} \ No newline at end of file diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxLimbNode.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxLimbNode.java new file mode 100644 index 000000000..4b41b4f47 --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxLimbNode.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.anim; + +import com.jme3.animation.Bone; +import com.jme3.animation.Skeleton; +import com.jme3.asset.AssetManager; +import com.jme3.scene.plugins.fbx.node.FbxNode; +import java.util.ArrayList; +import java.util.List; + +public class FbxLimbNode extends FbxNode { + + protected FbxNode skeletonHolder; + protected Bone bone; + + public FbxLimbNode(AssetManager assetManager, String sceneFolderName) { + super(assetManager, sceneFolderName); + } + + private static void createBones(FbxNode skeletonHolderNode, FbxLimbNode limb, List bones) { + limb.skeletonHolder = skeletonHolderNode; + + Bone parentBone = limb.getJmeBone(); + bones.add(parentBone); + + for (FbxNode child : limb.children) { + if (child instanceof FbxLimbNode) { + FbxLimbNode childLimb = (FbxLimbNode) child; + createBones(skeletonHolderNode, childLimb, bones); + parentBone.addChild(childLimb.getJmeBone()); + } + } + } + + public static Skeleton createSkeleton(FbxNode skeletonHolderNode) { + if (skeletonHolderNode instanceof FbxLimbNode) { + throw new UnsupportedOperationException("Limb nodes cannot be skeleton holders"); + } + + List bones = new ArrayList(); + + for (FbxNode child : skeletonHolderNode.getChildren()) { + if (child instanceof FbxLimbNode) { + createBones(skeletonHolderNode, (FbxLimbNode) child, bones); + } + } + + return new Skeleton(bones.toArray(new Bone[0])); + } + + public FbxNode getSkeletonHolder() { + return skeletonHolder; + } + + public Bone getJmeBone() { + if (bone == null) { + bone = new Bone(name); + bone.setBindTransforms(jmeLocalBindPose.getTranslation(), + jmeLocalBindPose.getRotation(), + jmeLocalBindPose.getScale()); + } + return bone; + } +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxSkinDeformer.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxSkinDeformer.java new file mode 100644 index 000000000..7a831cf7f --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxSkinDeformer.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.anim; + +import com.jme3.asset.AssetManager; +import com.jme3.scene.plugins.fbx.obj.FbxObject; +import java.util.ArrayList; +import java.util.List; + +public class FbxSkinDeformer extends FbxObject> { + + private final List clusters = new ArrayList(); + + public FbxSkinDeformer(AssetManager assetManager, String sceneFolderName) { + super(assetManager, sceneFolderName); + } + + @Override + protected List toJmeObject() { + return clusters; + } + + @Override + public void connectObject(FbxObject object) { + if (object instanceof FbxCluster) { + clusters.add((FbxCluster) object); + } else { + unsupportedConnectObject(object); + } + } + + @Override + public void connectObjectProperty(FbxObject object, String property) { + unsupportedConnectObjectProperty(object, property); + } + +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxToJmeTrack.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxToJmeTrack.java new file mode 100644 index 000000000..7b7b5ee5b --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/anim/FbxToJmeTrack.java @@ -0,0 +1,202 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.anim; + +import com.jme3.animation.BoneTrack; +import com.jme3.animation.SpatialTrack; +import com.jme3.animation.Track; +import com.jme3.math.Quaternion; +import com.jme3.math.Transform; +import com.jme3.math.Vector3f; +import com.jme3.scene.plugins.fbx.node.FbxNode; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** + * Maps animation stacks to influenced nodes. + * Will be used later to create jME3 tracks. + */ +public final class FbxToJmeTrack { + + public FbxAnimStack animStack; + public FbxAnimLayer animLayer; + public FbxNode node; + + // These are not used in map lookups. + public transient final Map animCurves = new HashMap(); + + public long[] getKeyTimes() { + Set keyFrameTimesSet = new HashSet(); + for (FbxAnimCurveNode curveNode : animCurves.values()) { + for (FbxAnimCurve curve : curveNode.getCurves()) { + for (long keyTime : curve.getKeyTimes()) { + keyFrameTimesSet.add(keyTime); + } + } + } + long[] keyFrameTimes = new long[keyFrameTimesSet.size()]; + int i = 0; + for (Long keyFrameTime : keyFrameTimesSet) { + keyFrameTimes[i++] = keyFrameTime; + } + Arrays.sort(keyFrameTimes); + return keyFrameTimes; + } + + /** + * Generate a {@link BoneTrack} from the animation data, for the given + * boneIndex. + * + * @param boneIndex The bone index for which track data is generated for. + * @param inverseBindPose Inverse bind pose of the bone (in world space). + * @return A BoneTrack containing the animation data, for the specified + * boneIndex. + */ + public BoneTrack toJmeBoneTrack(int boneIndex, Transform inverseBindPose) { + return (BoneTrack) toJmeTrackInternal(boneIndex, inverseBindPose); + } + + public SpatialTrack toJmeSpatialTrack() { + return (SpatialTrack) toJmeTrackInternal(-1, null); + } + + public float getDuration() { + long[] keyframes = getKeyTimes(); + return (float) (keyframes[keyframes.length - 1] * FbxAnimUtil.SECONDS_PER_UNIT); + } + + private static void applyInverse(Vector3f translation, Quaternion rotation, Vector3f scale, Transform inverseBindPose) { + Transform t = new Transform(); + t.setTranslation(translation); + t.setRotation(rotation); + if (scale != null) { + t.setScale(scale); + } + t.combineWithParent(inverseBindPose); + + t.getTranslation(translation); + t.getRotation(rotation); + if (scale != null) { + t.getScale(scale); + } + } + + private Track toJmeTrackInternal(int boneIndex, Transform inverseBindPose) { + float duration = animStack.getDuration(); + + FbxAnimCurveNode translationCurve = animCurves.get("Lcl Translation"); + FbxAnimCurveNode rotationCurve = animCurves.get("Lcl Rotation"); + FbxAnimCurveNode scalingCurve = animCurves.get("Lcl Scaling"); + + long[] fbxTimes = getKeyTimes(); + float[] times = new float[fbxTimes.length]; + + // Translations / Rotations must be set on all tracks. + // (Required for jME3) + Vector3f[] translations = new Vector3f[fbxTimes.length]; + Quaternion[] rotations = new Quaternion[fbxTimes.length]; + + Vector3f[] scales = null; + if (scalingCurve != null) { + scales = new Vector3f[fbxTimes.length]; + } + + for (int i = 0; i < fbxTimes.length; i++) { + long fbxTime = fbxTimes[i]; + float time = (float) (fbxTime * FbxAnimUtil.SECONDS_PER_UNIT); + + if (time > duration) { + // Expand animation duration to fit the curve. + duration = time; + System.out.println("actual duration: " + duration); + } + + times[i] = time; + if (translationCurve != null) { + translations[i] = translationCurve.getVector3Value(fbxTime); + } else { + translations[i] = new Vector3f(); + } + if (rotationCurve != null) { + rotations[i] = rotationCurve.getQuaternionValue(fbxTime); + if (i > 0) { + if (rotations[i - 1].dot(rotations[i]) < 0) { + System.out.println("rotation will go the long way, oh noes"); + rotations[i - 1].negate(); + } + } + } else { + rotations[i] = new Quaternion(); + } + if (scalingCurve != null) { + scales[i] = scalingCurve.getVector3Value(fbxTime); + } + + if (inverseBindPose != null) { + applyInverse(translations[i], rotations[i], scales != null ? scales[i] : null, inverseBindPose); + } + } + + if (boneIndex == -1) { + return new SpatialTrack(times, translations, rotations, scales); + } else { + if (scales != null) { + return new BoneTrack(boneIndex, times, translations, rotations, scales); + } else { + return new BoneTrack(boneIndex, times, translations, rotations); + } + } + } + + @Override + public int hashCode() { + int hash = 3; + hash = 79 * hash + this.animStack.hashCode(); + hash = 79 * hash + this.animLayer.hashCode(); + hash = 79 * hash + this.node.hashCode(); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + final FbxToJmeTrack other = (FbxToJmeTrack) obj; + return this.node == other.node + && this.animStack == other.animStack + && this.animLayer == other.animLayer; + } +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FBXDump.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FbxDump.java similarity index 73% rename from jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FBXDump.java rename to jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FbxDump.java index f309a5052..00619dce7 100644 --- a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FBXDump.java +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FbxDump.java @@ -37,7 +37,8 @@ import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.HashMap; import java.util.Map; -import static org.omg.IOP.IORHelper.id; +import java.util.logging.Level; +import java.util.logging.Logger; /** * Quick n' dirty dumper of FBX binary files. @@ -46,12 +47,14 @@ import static org.omg.IOP.IORHelper.id; * * @author Kirill Vainer */ -public final class FBXDump { +public final class FbxDump { + + private static final Logger logger = Logger.getLogger(FbxDump.class.getName()); private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.0000000000"); - private FBXDump() { } + private FbxDump() { } /** * Creates a map between object UIDs and the objects themselves. @@ -59,16 +62,17 @@ public final class FBXDump { * @param file The file to create the mappings for. * @return The UID to object map. */ - private static Map createUidToObjectMap(FBXFile file) { - Map uidToObjectMap = new HashMap(); - for (FBXElement rootElement : file.rootElements) { + private static Map createUidToObjectMap(FbxFile file) { + Map uidToObjectMap = new HashMap(); + for (FbxElement rootElement : file.rootElements) { if (rootElement.id.equals("Objects")) { - for (FBXElement fbxObj : rootElement.children) { - if (fbxObj.propertiesTypes[0] != 'L') { - continue; // error + for (FbxElement fbxObj : rootElement.children) { + FbxId uid = FbxId.getObjectId(fbxObj); + if (uid != null) { + uidToObjectMap.put(uid, fbxObj); + } else { + logger.log(Level.WARNING, "Cannot determine ID for object: {0}", fbxObj); } - Long uid = (Long) fbxObj.properties.get(0); - uidToObjectMap.put(uid, fbxObj); } } } @@ -80,8 +84,8 @@ public final class FBXDump { * * @param file the file to dump. */ - public static void dumpFBX(FBXFile file) { - dumpFBX(file, System.out); + public static void dumpFile(FbxFile file) { + dumpFile(file, System.out); } /** @@ -90,11 +94,11 @@ public final class FBXDump { * @param file the file to dump. * @param out the output stream where to output. */ - public static void dumpFBX(FBXFile file, OutputStream out) { - Map uidToObjectMap = createUidToObjectMap(file); + public static void dumpFile(FbxFile file, OutputStream out) { + Map uidToObjectMap = createUidToObjectMap(file); PrintStream ps = new PrintStream(out); - for (FBXElement rootElement : file.rootElements) { - dumpFBXElement(rootElement, ps, 0, uidToObjectMap); + for (FbxElement rootElement : file.rootElements) { + dumpElement(rootElement, ps, 0, uidToObjectMap); } } @@ -113,9 +117,9 @@ public final class FBXDump { return string.replaceAll("\u0000\u0001", "::"); } - protected static void dumpFBXProperty(String id, char propertyType, + protected static void dumpProperty(String id, char propertyType, Object property, PrintStream ps, - Map uidToObjectMap) { + Map uidToObjectMap) { switch (propertyType) { case 'S': // String @@ -125,13 +129,19 @@ public final class FBXDump { case 'R': // RAW data. byte[] bytes = (byte[]) property; - ps.print("["); - for (int j = 0; j < bytes.length; j++) { + int numToPrint = Math.min(10 * 1024, bytes.length); + ps.print("(size = "); + ps.print(bytes.length); + ps.print(") ["); + for (int j = 0; j < numToPrint; j++) { ps.print(String.format("%02X", bytes[j] & 0xff)); if (j != bytes.length - 1) { ps.print(" "); } } + if (numToPrint < bytes.length) { + ps.print(" ..."); + } ps.print("]"); break; case 'D': @@ -159,7 +169,7 @@ public final class FBXDump { // If this is a connection, decode UID into object name. if (id.equals("C")) { Long uid = (Long) property; - FBXElement element = uidToObjectMap.get(uid); + FbxElement element = uidToObjectMap.get(FbxId.create(uid)); if (element != null) { String name = (String) element.properties.get(1); ps.print("\"" + convertFBXString(name) + "\""); @@ -178,7 +188,7 @@ public final class FBXDump { int length = Array.getLength(property); for (int j = 0; j < length; j++) { Object arrayEntry = Array.get(property, j); - dumpFBXProperty(id, Character.toUpperCase(propertyType), arrayEntry, ps, uidToObjectMap); + dumpProperty(id, Character.toUpperCase(propertyType), arrayEntry, ps, uidToObjectMap); if (j != length - 1) { ps.print(","); } @@ -189,24 +199,24 @@ public final class FBXDump { } } - protected static void dumpFBXElement(FBXElement el, PrintStream ps, - int indent, Map uidToObjectMap) { + protected static void dumpElement(FbxElement el, PrintStream ps, + int indent, Map uidToObjectMap) { // 4 spaces per tab should be OK. String indentStr = indent(indent * 4); String textId = el.id; // Properties are called 'P' and connections are called 'C'. - if (el.id.equals("P")) { - textId = "Property"; - } else if (el.id.equals("C")) { - textId = "Connect"; - } +// if (el.id.equals("P")) { +// textId = "Property"; +// } else if (el.id.equals("C")) { +// textId = "Connect"; +// } ps.print(indentStr + textId + ": "); for (int i = 0; i < el.properties.size(); i++) { Object property = el.properties.get(i); char propertyType = el.propertiesTypes[i]; - dumpFBXProperty(el.id, propertyType, property, ps, uidToObjectMap); + dumpProperty(el.id, propertyType, property, ps, uidToObjectMap); if (i != el.properties.size() - 1) { ps.print(", "); } @@ -215,8 +225,8 @@ public final class FBXDump { ps.println(); } else { ps.println(" {"); - for (FBXElement childElement : el.children) { - dumpFBXElement(childElement, ps, indent + 1, uidToObjectMap); + for (FbxElement childElement : el.children) { + dumpElement(childElement, ps, indent + 1, uidToObjectMap); } ps.println(indentStr + "}"); } diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FbxElement.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FbxElement.java new file mode 100644 index 000000000..1a4d09d53 --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FbxElement.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2009-2014 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.file; + +import java.util.ArrayList; +import java.util.List; + +public class FbxElement { + + public String id; + public List properties; + /* + * Y - signed short + * C - boolean + * I - signed integer + * F - float + * D - double + * L - long + * R - byte array + * S - string + * f - array of floats + * i - array of ints + * d - array of doubles + * l - array of longs + * b - array of boleans + * c - array of unsigned bytes (represented as array of ints) + */ + public char[] propertiesTypes; + public List children = new ArrayList(); + + public FbxElement(int propsCount) { + this.properties = new ArrayList(propsCount); + this.propertiesTypes = new char[propsCount]; + } + + public FbxElement getChildById(String name) { + for (FbxElement element : children) { + if (element.id.equals(name)) { + return element; + } + } + return null; + } + + public List getFbxProperties() { + List props = new ArrayList(); + FbxElement propsElement = null; + boolean legacy = false; + + for (FbxElement element : children) { + if (element.id.equals("Properties70")) { + propsElement = element; + break; + } else if (element.id.equals("Properties60")) { + legacy = true; + propsElement = element; + break; + } + } + + if (propsElement == null) { + return props; + } + + for (FbxElement prop : propsElement.children) { + if (prop.id.equals("P") || prop.id.equals("Property")) { + if (legacy) { + char[] types = new char[prop.propertiesTypes.length + 1]; + types[0] = prop.propertiesTypes[0]; + types[1] = prop.propertiesTypes[0]; + System.arraycopy(prop.propertiesTypes, 1, types, 2, types.length - 2); + + List values = new ArrayList(prop.properties); + values.add(1, values.get(0)); + + FbxElement dummyProp = new FbxElement(types.length); + dummyProp.children = prop.children; + dummyProp.id = prop.id; + dummyProp.propertiesTypes = types; + dummyProp.properties = values; + props.add(dummyProp); + } else { + props.add(prop); + } + } + } + + return props; + } + + @Override + public String toString() { + return "FBXElement[id=" + id + ", numProps=" + properties.size() + ", numChildren=" + children.size() + "]"; + } +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FBXFile.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FbxFile.java similarity index 87% rename from jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FBXFile.java rename to jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FbxFile.java index ba81f1a74..9435b4c4e 100644 --- a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FBXFile.java +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FbxFile.java @@ -34,9 +34,13 @@ package com.jme3.scene.plugins.fbx.file; import java.util.ArrayList; import java.util.List; -public class FBXFile { +public class FbxFile { - public List rootElements = new ArrayList(); + public List rootElements = new ArrayList(); public long version; + @Override + public String toString() { + return "FBXFile[version=" + version + ",numElements=" + rootElements.size() + "]"; + } } diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FbxId.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FbxId.java new file mode 100644 index 000000000..e3c753052 --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FbxId.java @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.file; + +public abstract class FbxId { + + public static final FbxId ROOT = new LongFbxId(0); + + protected FbxId() { } + + private static final class StringFbxId extends FbxId { + + private final String id; + + public StringFbxId(String id) { + this.id = id; + } + + @Override + public int hashCode() { + return id.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (obj == null || obj.getClass() != StringFbxId.class) { + return false; + } + return this.id.equals(((StringFbxId) obj).id); + } + + @Override + public String toString() { + return id; + } + + @Override + public boolean isNull() { + return id.equals("Scene\u0000\u0001Model"); + } + } + + private static final class LongFbxId extends FbxId { + + private final long id; + + public LongFbxId(long id) { + this.id = id; + } + + @Override + public int hashCode() { + return (int) (this.id ^ (this.id >>> 32)); + } + + @Override + public boolean equals(Object obj) { + if (obj == null || obj.getClass() != LongFbxId.class) { + return false; + } + return this.id == ((LongFbxId) obj).id; + } + + @Override + public boolean isNull() { + return id == 0; + } + + @Override + public String toString() { + return Long.toString(id); + } + } + + public abstract boolean isNull(); + + public static FbxId create(Object obj) { + if (obj instanceof Long) { + return new LongFbxId((Long)obj); + } else if (obj instanceof String) { + return new StringFbxId((String)obj); + } else { + throw new UnsupportedOperationException("Unsupported ID object type: " + obj.getClass()); + } + } + + public static FbxId getObjectId(FbxElement el) { + if (el.propertiesTypes.length == 2 + && el.propertiesTypes[0] == 'S' + && el.propertiesTypes[1] == 'S') { + return new StringFbxId((String) el.properties.get(0)); + } else if (el.propertiesTypes.length == 3 + && el.propertiesTypes[0] == 'L' + && el.propertiesTypes[1] == 'S' + && el.propertiesTypes[2] == 'S') { + return new LongFbxId((Long) el.properties.get(0)); + } else { + return null; + } + } +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FBXReader.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FbxReader.java similarity index 94% rename from jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FBXReader.java rename to jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FbxReader.java index b39dfef1c..22e93d8db 100644 --- a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FBXReader.java +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FbxReader.java @@ -40,8 +40,8 @@ import java.nio.ByteOrder; import java.util.Arrays; import java.util.zip.InflaterInputStream; -public class FBXReader { - +public class FbxReader { + public static final int BLOCK_SENTINEL_LENGTH = 13; public static final byte[] BLOCK_SENTINEL_DATA = new byte[BLOCK_SENTINEL_LENGTH]; /** @@ -49,9 +49,9 @@ public class FBXReader { * "Kaydara FBX Binary\x20\x20\x00\x1a\x00" */ public static final byte[] HEAD_MAGIC = new byte[]{0x4b, 0x61, 0x79, 0x64, 0x61, 0x72, 0x61, 0x20, 0x46, 0x42, 0x58, 0x20, 0x42, 0x69, 0x6e, 0x61, 0x72, 0x79, 0x20, 0x20, 0x00, 0x1a, 0x00}; - - public static FBXFile readFBX(InputStream stream) throws IOException { - FBXFile fbxFile = new FBXFile(); + + public static FbxFile readFBX(InputStream stream) throws IOException { + FbxFile fbxFile = new FbxFile(); // Read file to byte buffer so we can know current position in file ByteBuffer byteBuffer = readToByteBuffer(stream); try { @@ -61,27 +61,29 @@ public class FBXReader { // Check majic header byte[] majic = getBytes(byteBuffer, HEAD_MAGIC.length); if(!Arrays.equals(HEAD_MAGIC, majic)) - throw new IOException("Not FBX file"); + throw new IOException("Either ASCII FBX or corrupt file. " + + "Only binary FBX files are supported"); + // Read version fbxFile.version = getUInt(byteBuffer); // Read root elements while(true) { - FBXElement e = readFBXElement(byteBuffer); + FbxElement e = readFBXElement(byteBuffer); if(e == null) break; fbxFile.rootElements.add(e); } return fbxFile; } - - private static FBXElement readFBXElement(ByteBuffer byteBuffer) throws IOException { + + private static FbxElement readFBXElement(ByteBuffer byteBuffer) throws IOException { long endOffset = getUInt(byteBuffer); if(endOffset == 0) return null; long propCount = getUInt(byteBuffer); getUInt(byteBuffer); // Properties length unused - FBXElement element = new FBXElement((int) propCount); + FbxElement element = new FbxElement((int) propCount); element.id = new String(getBytes(byteBuffer, getUByte(byteBuffer))); for(int i = 0; i < propCount; ++i) { diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/material/FbxImage.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/material/FbxImage.java new file mode 100644 index 000000000..518dd4134 --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/material/FbxImage.java @@ -0,0 +1,190 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.material; + +import com.jme3.asset.AssetLoadException; +import com.jme3.asset.AssetManager; +import com.jme3.asset.AssetNotFoundException; +import com.jme3.asset.TextureKey; +import com.jme3.scene.plugins.fbx.file.FbxElement; +import com.jme3.scene.plugins.fbx.obj.FbxObject; +import com.jme3.texture.Image; +import com.jme3.util.PlaceholderAssets; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.logging.Level; +import java.util.logging.Logger; + +public final class FbxImage extends FbxObject { + + private static final Logger logger = Logger.getLogger(FbxImage.class.getName()); + + protected TextureKey key; + protected String type; // = "Clip" + protected String filePath; // = "C:\Whatever\Blah\Texture.png" + protected String relativeFilePath; // = "..\Blah\Texture.png" + protected byte[] content; // = null, byte[0] OR embedded image data (unknown format?) + + public FbxImage(AssetManager assetManager, String sceneFolderName) { + super(assetManager, sceneFolderName); + } + + @Override + public void fromElement(FbxElement element) { + super.fromElement(element); + if (element.propertiesTypes.length == 3) { + type = (String) element.properties.get(2); + } else { + type = (String) element.properties.get(1); + } + if (type.equals("Clip")) { + for (FbxElement e : element.children) { + if (e.id.equals("Type")) { + type = (String) e.properties.get(0); + } else if (e.id.equals("FileName")) { + filePath = (String) e.properties.get(0); + } else if (e.id.equals("RelativeFilename")) { + relativeFilePath = (String) e.properties.get(0); + } else if (e.id.equals("Content")) { + if (e.properties.size() > 0) { + byte[] storedContent = (byte[]) e.properties.get(0); + if (storedContent.length > 0) { + this.content = storedContent; + } + } + } + } + } + } + + private Image loadImageSafe(AssetManager assetManager, TextureKey texKey) { + try { + return assetManager.loadTexture(texKey).getImage(); + } catch (AssetNotFoundException ex) { + return null; + } catch (AssetLoadException ex) { + logger.log(Level.WARNING, "Error when loading image: " + texKey, ex); + return null; + } + } + + private static String getFileName(String filePath) { + // NOTE: Gotta do it this way because new File().getParent() + // will not strip forward slashes on Linux / Mac OS X. + int fwdSlashIdx = filePath.lastIndexOf("\\"); + int bkSlashIdx = filePath.lastIndexOf("/"); + + if (fwdSlashIdx != -1) { + filePath = filePath.substring(fwdSlashIdx + 1); + } else if (bkSlashIdx != -1) { + filePath = filePath.substring(bkSlashIdx + 1); + } + + return filePath; + } + + /** + * The texture key that was used to load the image. + * Only valid after {@link #getJmeObject()} has been called. + * @return the key that was used to load the image. + */ + public TextureKey getTextureKey() { + return key; + } + + @Override + protected Object toJmeObject() { + Image image = null; + String fileName = null; + String relativeFilePathJme; + + if (filePath != null) { + fileName = getFileName(filePath); + } else if (relativeFilePath != null) { + fileName = getFileName(relativeFilePath); + + } + + if (fileName != null) { + try { + // Try to load filename relative to FBX folder + key = new TextureKey(sceneFolderName + fileName); + key.setGenerateMips(true); + image = loadImageSafe(assetManager, key); + + // Try to load relative filepath relative to FBX folder + if (image == null && relativeFilePath != null) { + // Convert Windows paths to jME3 paths + relativeFilePathJme = relativeFilePath.replace('\\', '/'); + key = new TextureKey(sceneFolderName + relativeFilePathJme); + key.setGenerateMips(true); + image = loadImageSafe(assetManager, key); + } + + // Try to load embedded image + if (image == null && content != null && content.length > 0) { + key = new TextureKey(fileName); + key.setGenerateMips(true); + InputStream is = new ByteArrayInputStream(content); + image = assetManager.loadAssetFromStream(key, is).getImage(); + + // NOTE: embedded texture doesn't exist in the asset manager, + // so the texture key must not be saved. + key = null; + } + } catch (AssetLoadException ex) { + logger.log(Level.WARNING, "Error while attempting to load texture {0}:\n{1}", + new Object[]{name, ex.toString()}); + } + } + + if (image == null) { + logger.log(Level.WARNING, "Cannot locate {0} for texture {1}", new Object[]{fileName, name}); + image = PlaceholderAssets.getPlaceholderImage(assetManager); + } + + // NOTE: At this point, key will be set to the last + // attempted texture key that we attempted to load. + + return image; + } + + @Override + public void connectObject(FbxObject object) { + unsupportedConnectObject(object); + } + + @Override + public void connectObjectProperty(FbxObject object, String property) { + unsupportedConnectObjectProperty(object, property); + } +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/material/FbxMaterial.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/material/FbxMaterial.java new file mode 100644 index 000000000..9be5bf70c --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/material/FbxMaterial.java @@ -0,0 +1,363 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.material; + +import com.jme3.asset.AssetManager; +import com.jme3.material.Material; +import com.jme3.material.RenderState.BlendMode; +import com.jme3.material.RenderState.FaceCullMode; +import com.jme3.math.ColorRGBA; +import com.jme3.scene.plugins.fbx.file.FbxElement; +import com.jme3.scene.plugins.fbx.obj.FbxObject; +import com.jme3.texture.Texture; +import com.jme3.texture.image.ColorSpace; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class FbxMaterial extends FbxObject { + + private static final Logger logger = Logger.getLogger(FbxMaterial.class.getName()); + + private String shadingModel; // TODO: do we care about this? lambert just has no specular? + private final FbxMaterialProperties properties = new FbxMaterialProperties(); + + public FbxMaterial(AssetManager assetManager, String sceneFolderName) { + super(assetManager, sceneFolderName); + } + + @Override + public void fromElement(FbxElement element) { + super.fromElement(element); + if(!getSubclassName().equals("")) { + return; + } + + FbxElement shadingModelEl = element.getChildById("ShadingModel"); + if (shadingModelEl != null) { + shadingModel = (String) shadingModelEl.properties.get(0); + if (!shadingModel.equals("")) { + if (!shadingModel.equalsIgnoreCase("phong") && + !shadingModel.equalsIgnoreCase("lambert")) { + logger.log(Level.WARNING, "FBX material uses unknown shading model: {0}. " + + "Material may display incorrectly.", shadingModel); + } + } + } + + for (FbxElement child : element.getFbxProperties()) { + properties.setPropertyFromElement(child); + } + } + + @Override + public void connectObject(FbxObject object) { + unsupportedConnectObject(object); + } + + @Override + public void connectObjectProperty(FbxObject object, String property) { + if (!(object instanceof FbxTexture)) { + unsupportedConnectObjectProperty(object, property); + } + + properties.setPropertyTexture(property, (FbxTexture) object); + } + + private static void multRGB(ColorRGBA color, float factor) { + color.r *= factor; + color.g *= factor; + color.b *= factor; + } + + @Override + protected Material toJmeObject() { + ColorRGBA ambient = null; + ColorRGBA diffuse = null; + ColorRGBA specular = null; + ColorRGBA transp = null; + ColorRGBA emissive = null; + float shininess = 1f; + boolean separateTexCoord = false; + + Texture diffuseMap = null; + Texture specularMap = null; + Texture normalMap = null; + Texture transpMap = null; + Texture emitMap = null; + Texture aoMap = null; + + FbxTexture fbxDiffuseMap = null; + + Object diffuseColor = properties.getProperty("DiffuseColor"); + if (diffuseColor != null) { + if (diffuseColor instanceof ColorRGBA) { + diffuse = ((ColorRGBA) diffuseColor).clone(); + } else if (diffuseColor instanceof FbxTexture) { + FbxTexture tex = (FbxTexture) diffuseColor; + fbxDiffuseMap = tex; + diffuseMap = tex.getJmeObject(); + diffuseMap.getImage().setColorSpace(ColorSpace.sRGB); + } + } + + Object diffuseFactor = properties.getProperty("DiffuseFactor"); + if (diffuseFactor != null && diffuseFactor instanceof Float) { + float factor = (Float)diffuseFactor; + if (diffuse != null) { + multRGB(diffuse, factor); + } else { + diffuse = new ColorRGBA(factor, factor, factor, 1f); + } + } + + Object specularColor = properties.getProperty("SpecularColor"); + if (specularColor != null) { + if (specularColor instanceof ColorRGBA) { + specular = ((ColorRGBA) specularColor).clone(); + } else if (specularColor instanceof FbxTexture) { + FbxTexture tex = (FbxTexture) specularColor; + specularMap = tex.getJmeObject(); + specularMap.getImage().setColorSpace(ColorSpace.sRGB); + } + } + + Object specularFactor = properties.getProperty("SpecularFactor"); + if (specularFactor != null && specularFactor instanceof Float) { + float factor = (Float)specularFactor; + if (specular != null) { + multRGB(specular, factor); + } else { + specular = new ColorRGBA(factor, factor, factor, 1f); + } + } + + Object transparentColor = properties.getProperty("TransparentColor"); + if (transparentColor != null) { + if (transparentColor instanceof ColorRGBA) { + transp = ((ColorRGBA) transparentColor).clone(); + } else if (transparentColor instanceof FbxTexture) { + FbxTexture tex = (FbxTexture) transparentColor; + transpMap = tex.getJmeObject(); + transpMap.getImage().setColorSpace(ColorSpace.sRGB); + } + } + + Object transparencyFactor = properties.getProperty("TransparencyFactor"); + if (transparencyFactor != null && transparencyFactor instanceof Float) { + float factor = (Float)transparencyFactor; + if (transp != null) { + transp.a *= factor; + } else { + transp = new ColorRGBA(1f, 1f, 1f, factor); + } + } + + Object emissiveColor = properties.getProperty("EmissiveColor"); + if (emissiveColor != null) { + if (emissiveColor instanceof ColorRGBA) { + emissive = ((ColorRGBA)emissiveColor).clone(); + } else if (emissiveColor instanceof FbxTexture) { + FbxTexture tex = (FbxTexture) emissiveColor; + emitMap = tex.getJmeObject(); + emitMap.getImage().setColorSpace(ColorSpace.sRGB); + } + } + + Object emissiveFactor = properties.getProperty("EmissiveFactor"); + if (emissiveFactor != null && emissiveFactor instanceof Float) { + float factor = (Float)emissiveFactor; + if (emissive != null) { + multRGB(emissive, factor); + } else { + emissive = new ColorRGBA(factor, factor, factor, 1f); + } + } + + Object ambientColor = properties.getProperty("AmbientColor"); + if (ambientColor != null && ambientColor instanceof ColorRGBA) { + ambient = ((ColorRGBA)ambientColor).clone(); + } + + Object ambientFactor = properties.getProperty("AmbientFactor"); + if (ambientFactor != null && ambientFactor instanceof Float) { + float factor = (Float)ambientFactor; + if (ambient != null) { + multRGB(ambient, factor); + } else { + ambient = new ColorRGBA(factor, factor, factor, 1f); + } + } + + Object shininessFactor = properties.getProperty("Shininess"); + if (shininessFactor != null) { + if (shininessFactor instanceof Float) { + shininess = (Float) shininessFactor; + } else if (shininessFactor instanceof FbxTexture) { + // TODO: support shininess textures + } + } + + Object bumpNormal = properties.getProperty("NormalMap"); + if (bumpNormal != null) { + if (bumpNormal instanceof FbxTexture) { + // TODO: check all meshes that use this material have tangents + // otherwise shading errors occur + FbxTexture tex = (FbxTexture) bumpNormal; + normalMap = tex.getJmeObject(); + normalMap.getImage().setColorSpace(ColorSpace.Linear); + } + } + + Object aoColor = properties.getProperty("DiffuseColor2"); + if (aoColor != null) { + if (aoColor instanceof FbxTexture) { + FbxTexture tex = (FbxTexture) aoColor; + if (tex.getUvSet() != null && fbxDiffuseMap != null) { + if (!tex.getUvSet().equals(fbxDiffuseMap.getUvSet())) { + separateTexCoord = true; + } + } + aoMap = tex.getJmeObject(); + aoMap.getImage().setColorSpace(ColorSpace.sRGB); + } + } + + // TODO: how to disable transparency from diffuse map?? Need "UseAlpha" again.. + + assert ambient == null || ambient.a == 1f; + assert diffuse == null || diffuse.a == 1f; + assert specular == null || specular.a == 1f; + assert emissive == null || emissive.a == 1f; + assert transp == null || (transp.r == 1f && transp.g == 1f && transp.b == 1f); + + // If shininess is less than 1.0, the lighting shader won't be able + // to handle it. Gotta disable specularity then. + if (shininess < 1f) { + shininess = 1f; + specular = ColorRGBA.Black; + } + + // Try to guess if we need to enable alpha blending. + // FBX does not specify this explicitly. + boolean useAlphaBlend = false; + + if (diffuseMap != null && diffuseMap == transpMap) { + // jME3 already uses alpha from diffuseMap + // (if alpha blend is enabled) + useAlphaBlend = true; + transpMap = null; + } else if (diffuseMap != null && transpMap != null && diffuseMap != transpMap) { + // TODO: potential bug here. Alpha from diffuse may + // leak unintentionally. + useAlphaBlend = true; + } else if (transpMap != null) { + // We have alpha map but no diffuse map, OK. + useAlphaBlend = true; + } + + if (transp != null && transp.a != 1f) { + // Consolidate transp into diffuse + // (jME3 doesn't use a separate alpha color) + + // TODO: potential bug here. Alpha from diffuse may + // leak unintentionally. + useAlphaBlend = true; + if (diffuse != null) { + diffuse.a = transp.a; + } else { + diffuse = transp; + } + } + + Material mat = new Material(assetManager, "Common/MatDefs/Light/Lighting.j3md"); + mat.setName(name); + + // TODO: load this from FBX material. + mat.setReceivesShadows(true); + + if (useAlphaBlend) { + // No idea if this is a transparent or translucent model, gotta guess.. + mat.setTransparent(true); + mat.setFloat("AlphaDiscardThreshold", 0.01f); + mat.getAdditionalRenderState().setBlendMode(BlendMode.Alpha); + } + + mat.getAdditionalRenderState().setFaceCullMode(FaceCullMode.Off); + + // Set colors. + if (ambient != null || diffuse != null || specular != null) { + // If either of those is set, we have to set them all. + // NOTE: default specular is black, unless it is set explicitly. + mat.setBoolean("UseMaterialColors", true); + mat.setColor("Ambient", /*ambient != null ? ambient :*/ ColorRGBA.White); + mat.setColor("Diffuse", diffuse != null ? diffuse : ColorRGBA.White); + mat.setColor("Specular", specular != null ? specular : ColorRGBA.Black); + } + + if (emissive != null) { + mat.setColor("GlowColor", emissive); + } + + // Set shininess. + if (shininess > 1f) { + // Convert shininess from + // Phong (FBX shading model) to Blinn (jME3 shading model). + float blinnShininess = (shininess * 5.1f) + 1f; + mat.setFloat("Shininess", blinnShininess); + } + + // Set textures. + if (diffuseMap != null) { + mat.setTexture("DiffuseMap", diffuseMap); + } + if (specularMap != null) { + mat.setTexture("SpecularMap", specularMap); + } + if (normalMap != null) { + mat.setTexture("NormalMap", normalMap); + } + if (transpMap != null) { +// mat.setTexture("AlphaMap", transpMap); + } + if (emitMap != null) { + mat.setTexture("GlowMap", emitMap); + } + if (aoMap != null) { + mat.setTexture("LightMap", aoMap); + if (separateTexCoord) { + mat.setBoolean("SeparateTexCoord", true); + } + } + + return mat; + } +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/material/FbxMaterialProperties.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/material/FbxMaterialProperties.java new file mode 100644 index 000000000..14d23900d --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/material/FbxMaterialProperties.java @@ -0,0 +1,234 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.material; + +import com.jme3.math.ColorRGBA; +import com.jme3.scene.plugins.fbx.file.FbxElement; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class FbxMaterialProperties { + + private static final Logger logger = Logger.getLogger(FbxMaterialProperties.class.getName()); + + private static final Map propertyMetaMap = new HashMap(); + + private final Map propertyValueMap = new HashMap(); + + private static enum Type { + Color, + Alpha, + Factor, + Texture2DOrColor, + Texture2DOrAlpha, + Texture2DOrFactor, + Texture2D, + TextureCubeMap, + Ignore; + } + + private static class FBXMaterialProperty { + private final String name; + private final Type type; + + public FBXMaterialProperty(String name, Type type) { + this.name = name; + this.type = type; + } + } + + private static boolean isValueAcceptable(Type type, Object value) { + if (type == Type.Ignore) { + return true; + } + if (value instanceof FbxTexture) { + switch (type) { + case Texture2D: + case Texture2DOrAlpha: + case Texture2DOrColor: + case Texture2DOrFactor: + return true; + } + } else if (value instanceof ColorRGBA) { + switch (type) { + case Color: + case Texture2DOrColor: + return true; + } + } else if (value instanceof Float) { + switch (type) { + case Alpha: + case Factor: + case Texture2DOrAlpha: + case Texture2DOrFactor: + return true; + } + } + + return false; + } + + private static void defineProp(String name, Type type) { + propertyMetaMap.put(name, new FBXMaterialProperty(name, type)); + } + + private static void defineAlias(String alias, String name) { + propertyMetaMap.put(alias, propertyMetaMap.get(name)); + } + + static { + // Lighting->Ambient + // TODO: Add support for AmbientMap?? + defineProp("AmbientColor", Type.Color); + defineProp("AmbientFactor", Type.Factor); + defineAlias("Ambient", "AmbientColor"); + + // Lighting->DiffuseMap/Diffuse + defineProp("DiffuseColor", Type.Texture2DOrColor); + defineProp("DiffuseFactor", Type.Factor); + defineAlias("Diffuse", "DiffuseColor"); + + // Lighting->SpecularMap/Specular + defineProp("SpecularColor", Type.Texture2DOrColor); + defineProp("SpecularFactor", Type.Factor); + defineAlias("Specular", "SpecularColor"); + + // Lighting->AlphaMap/Diffuse + defineProp("TransparentColor", Type.Texture2DOrAlpha); + + // Lighting->Diffuse + defineProp("TransparencyFactor", Type.Alpha); + defineAlias("Opacity", "TransparencyFactor"); + + // Lighting->GlowMap/GlowColor + defineProp("EmissiveColor", Type.Texture2DOrColor); + defineProp("EmissiveFactor", Type.Factor); + defineAlias("Emissive", "EmissiveColor"); + + // Lighting->Shininess + defineProp("Shininess", Type.Factor); + defineAlias("ShininessExponent", "Shininess"); + + // Lighting->NormalMap + defineProp("NormalMap", Type.Texture2D); + defineAlias("Normal", "NormalMap"); + + // Lighting->EnvMap + defineProp("ReflectionColor", Type.Texture2DOrColor); + + // Lighting->FresnelParams + defineProp("Reflectivity", Type.Factor); + defineAlias("ReflectionFactor", "Reflectivity"); + + // ShadingModel is no longer specified under Properties element. + defineProp("ShadingModel", Type.Ignore); + + // MultiLayer materials aren't supported anyway.. + defineProp("MultiLayer", Type.Ignore); + + // Not sure what this is.. NormalMap again?? + defineProp("Bump", Type.Texture2DOrColor); + + defineProp("BumpFactor", Type.Factor); + defineProp("DisplacementColor", Type.Color); + defineProp("DisplacementFactor", Type.Factor); + } + + public void setPropertyTexture(String name, FbxTexture texture) { + FBXMaterialProperty prop = propertyMetaMap.get(name); + + if (prop == null) { + logger.log(Level.WARNING, "Unknown FBX material property '{0}'", name); + return; + } + + if (propertyValueMap.get(name) instanceof FbxTexture) { + // Multiple / layered textures .. + // Just write into 2nd slot for now (maybe will use for lightmaps). + name = name + "2"; + } + + propertyValueMap.put(name, texture); + } + + public void setPropertyFromElement(FbxElement propertyElement) { + String name = (String) propertyElement.properties.get(0); + FBXMaterialProperty prop = propertyMetaMap.get(name); + + if (prop == null) { + logger.log(Level.WARNING, "Unknown FBX material property ''{0}''", name); + return; + } + + // It is either a color, alpha, or factor. + // Textures can only be set via setPropertyTexture. + + // If it is an alias, get the real name of the property. + String realName = prop.name; + + switch (prop.type) { + case Alpha: + case Factor: + case Texture2DOrFactor: + case Texture2DOrAlpha: + double value = (Double) propertyElement.properties.get(4); + propertyValueMap.put(realName, (float)value); + break; + case Color: + case Texture2DOrColor: + double x = (Double) propertyElement.properties.get(4); + double y = (Double) propertyElement.properties.get(5); + double z = (Double) propertyElement.properties.get(6); + ColorRGBA color = new ColorRGBA((float)x, (float)y, (float)z, 1f); + propertyValueMap.put(realName, color); + break; + default: + logger.log(Level.WARNING, "FBX material property ''{0}'' requires a texture.", name); + break; + } + } + + public Object getProperty(String name) { + return propertyValueMap.get(name); + } + + public static Type getPropertyType(String name) { + FBXMaterialProperty prop = propertyMetaMap.get(name); + if (prop == null) { + return null; + } else { + return prop.type; + } + } +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/material/FbxTexture.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/material/FbxTexture.java new file mode 100644 index 000000000..4569dad33 --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/material/FbxTexture.java @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.material; + +import com.jme3.asset.AssetManager; +import com.jme3.asset.TextureKey; +import com.jme3.math.Vector2f; +import com.jme3.scene.plugins.fbx.file.FbxElement; +import com.jme3.scene.plugins.fbx.obj.FbxObject; +import com.jme3.texture.Image; +import com.jme3.texture.Texture; +import com.jme3.texture.Texture.MagFilter; +import com.jme3.texture.Texture.MinFilter; +import com.jme3.texture.Texture.WrapAxis; +import com.jme3.texture.Texture.WrapMode; +import com.jme3.texture.Texture2D; +import com.jme3.util.PlaceholderAssets; + +public class FbxTexture extends FbxObject { + + private static enum AlphaSource { + None, + FromTextureAlpha, + FromTextureIntensity; + } + + private String type; + private FbxImage media; + + // TODO: not currently used. + private AlphaSource alphaSource = AlphaSource.FromTextureAlpha; + private String uvSet; + private int wrapModeU = 0, wrapModeV = 0; + private final Vector2f uvTranslation = new Vector2f(0, 0); + private final Vector2f uvScaling = new Vector2f(1, 1); + + public FbxTexture(AssetManager assetManager, String sceneFolderName) { + super(assetManager, sceneFolderName); + } + + public String getUvSet() { + return uvSet; + } + + @Override + protected Texture toJmeObject() { + Image image = null; + TextureKey key = null; + if (media != null) { + image = (Image) media.getJmeObject(); + key = media.getTextureKey(); + } + if (image == null) { + image = PlaceholderAssets.getPlaceholderImage(assetManager); + } + Texture2D tex = new Texture2D(image); + if (key != null) { + tex.setKey(key); + tex.setName(key.getName()); + tex.setAnisotropicFilter(key.getAnisotropy()); + } + tex.setMinFilter(MinFilter.Trilinear); + tex.setMagFilter(MagFilter.Bilinear); + if (wrapModeU == 0) { + tex.setWrap(WrapAxis.S, WrapMode.Repeat); + } + if (wrapModeV == 0) { + tex.setWrap(WrapAxis.T, WrapMode.Repeat); + } + return tex; + } + + @Override + public void fromElement(FbxElement element) { + super.fromElement(element); + if (getSubclassName().equals("")) { + for (FbxElement e : element.children) { + if (e.id.equals("Type")) { + type = (String) e.properties.get(0); + } + /*else if (e.id.equals("FileName")) { + filename = (String) e.properties.get(0); + }*/ + } + + for (FbxElement prop : element.getFbxProperties()) { + String propName = (String) prop.properties.get(0); + if (propName.equals("AlphaSource")) { + // ??? + } else if (propName.equals("UVSet")) { + uvSet = (String) prop.properties.get(4); + } else if (propName.equals("WrapModeU")) { + wrapModeU = (Integer) prop.properties.get(4); + } else if (propName.equals("WrapModeV")) { + wrapModeV = (Integer) prop.properties.get(4); + } + } + } + } + + @Override + public void connectObject(FbxObject object) { + if (!(object instanceof FbxImage)) { + unsupportedConnectObject(object); +// } else if (media != null) { +// throw new UnsupportedOperationException("An image is already attached to this texture."); + } + + this.media = (FbxImage) object; + } + + @Override + public void connectObjectProperty(FbxObject object, String property) { + unsupportedConnectObjectProperty(object, property); + } + +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/mesh/FbxLayer.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/mesh/FbxLayer.java new file mode 100644 index 000000000..d1b9d3860 --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/mesh/FbxLayer.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.mesh; + +import com.jme3.scene.plugins.fbx.file.FbxElement; +import java.util.Collection; +import java.util.EnumMap; +import java.util.logging.Level; +import java.util.logging.Logger; + +public final class FbxLayer { + + private static final Logger logger = Logger.getLogger(FbxLayer.class.getName()); + + public static class FbxLayerElementRef { + FbxLayerElement.Type layerElementType; + int layerElementIndex; + FbxLayerElement layerElement; + } + + int layer; + final EnumMap references = + new EnumMap(FbxLayerElement.Type.class); + + private FbxLayer() { } + + public Object getVertexData(FbxLayerElement.Type type, int polygonIndex, + int polygonVertexIndex, int positionIndex, int edgeIndex) { + FbxLayerElementRef reference = references.get(type); + if (reference == null) { + return null; + } else { + return reference.layerElement.getVertexData(polygonIndex, polygonVertexIndex, positionIndex, edgeIndex); + } + } + + public FbxLayerElement.Type[] getLayerElementTypes() { + FbxLayerElement.Type[] types = new FbxLayerElement.Type[references.size()]; + references.keySet().toArray(types); + return types; + } + + public void setLayerElements(Collection layerElements) { + for (FbxLayerElement layerElement : layerElements) { + FbxLayerElementRef reference = references.get(layerElement.type); + if (reference != null && reference.layerElementIndex == layerElement.index) { + reference.layerElement = layerElement; + } + } + } + + public static FbxLayer fromElement(FbxElement element) { + FbxLayer layer = new FbxLayer(); + layer.layer = (Integer)element.properties.get(0); + next_element: for (FbxElement child : element.children) { + if (!child.id.equals("LayerElement")) { + continue; + } + FbxLayerElementRef ref = new FbxLayerElementRef(); + for (FbxElement child2 : child.children) { + if (child2.id.equals("Type")) { + String layerElementTypeStr = (String) child2.properties.get(0); + layerElementTypeStr = layerElementTypeStr.substring("LayerElement".length()); + try { + ref.layerElementType = FbxLayerElement.Type.valueOf(layerElementTypeStr); + } catch (IllegalArgumentException ex) { + logger.log(Level.WARNING, "Unsupported layer type: {0}. Ignoring.", layerElementTypeStr); + continue next_element; + } + } else if (child2.id.equals("TypedIndex")) { + ref.layerElementIndex = (Integer) child2.properties.get(0); + } + } + layer.references.put(ref.layerElementType, ref); + } + return layer; + } +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/mesh/FbxLayerElement.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/mesh/FbxLayerElement.java new file mode 100644 index 000000000..bffd94c65 --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/mesh/FbxLayerElement.java @@ -0,0 +1,243 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.mesh; + +import com.jme3.math.ColorRGBA; +import com.jme3.math.Vector2f; +import com.jme3.math.Vector3f; +import com.jme3.scene.plugins.fbx.file.FbxElement; +import java.util.HashSet; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class FbxLayerElement { + + private static final Logger logger = Logger.getLogger(FbxLayerElement.class.getName()); + + public enum Type { + Position, // Vector3f (isn't actually defined in FBX) + BoneIndex, // List (isn't actually defined in FBX) + BoneWeight, // List isn't actually defined in FBX) + Normal, // Vector3f + Binormal, // Vector3f + Tangent, // Vector3f + UV, // Vector2f + TransparentUV, // Vector2f + Color, // ColorRGBA + Material, // Integer + Smoothing, // Integer + Visibility, // Integer + Texture, // ??? (FBX 6.x) + PolygonGroup, // ??? (FBX 6.x) + NormalMapTextures, // ??? (FBX 6.x) + SpecularFactorUV, // ??? (FBX 6.x) + NormalMapUV, // ??? (FBX 6.x) + SpecularFactorTextures, // ??? (FBX 6.x) + + } + + public enum MappingInformationType { + NoMappingInformation, + AllSame, + ByPolygonVertex, + ByVertex, + ByPolygon, + ByEdge; + } + + public enum ReferenceInformationType { + Direct, + IndexToDirect; + } + + public enum TextureBlendMode { + Translucent; + } + + private static final Set indexTypes = new HashSet(); + + static { + indexTypes.add("UVIndex"); + indexTypes.add("NormalsIndex"); + indexTypes.add("TangentsIndex"); + indexTypes.add("BinormalsIndex"); + indexTypes.add("Smoothing"); + indexTypes.add("Materials"); + indexTypes.add("TextureId"); + indexTypes.add("ColorIndex"); + indexTypes.add("PolygonGroup"); + } + + int index; + Type type; + ReferenceInformationType refInfoType; + MappingInformationType mapInfoType; + String name = ""; + Object[] data; + int[] dataIndices; + + private FbxLayerElement() { } + + public String toString() { + return "LayerElement[type=" + type + ", layer=" + index + + ", mapInfoType=" + mapInfoType + ", refInfoType=" + refInfoType + "]"; + } + + private Object getVertexDataIndexToDirect(int polygonIndex, int polygonVertexIndex, + int positionIndex, int edgeIndex) { + switch (mapInfoType) { + case AllSame: return data[dataIndices[0]]; + case ByPolygon: return data[dataIndices[polygonIndex]]; + case ByPolygonVertex: return data[dataIndices[polygonVertexIndex]]; + case ByVertex: return data[dataIndices[positionIndex]]; + case ByEdge: return data[dataIndices[edgeIndex]]; + default: throw new UnsupportedOperationException(); + } + } + + private Object getVertexDataDirect(int polygonIndex, int polygonVertexIndex, + int positionIndex, int edgeIndex) { + switch (mapInfoType) { + case AllSame: return data[0]; + case ByPolygon: return data[polygonIndex]; + case ByPolygonVertex: return data[polygonVertexIndex]; + case ByVertex: return data[positionIndex]; + case ByEdge: return data[edgeIndex]; + default: throw new UnsupportedOperationException(); + } + } + + public Object getVertexData(int polygonIndex, int polygonVertexIndex, int positionIndex, int edgeIndex) { + switch (refInfoType) { + case Direct: return getVertexDataDirect(polygonIndex, polygonVertexIndex, positionIndex, edgeIndex); + case IndexToDirect: return getVertexDataIndexToDirect(polygonIndex, polygonVertexIndex, positionIndex, edgeIndex); + default: return null; + } + } + + public static FbxLayerElement fromPositions(double[] positionData) { + FbxLayerElement layerElement = new FbxLayerElement(); + layerElement.index = -1; + layerElement.name = ""; + layerElement.type = Type.Position; + layerElement.mapInfoType = MappingInformationType.ByVertex; + layerElement.refInfoType = ReferenceInformationType.Direct; + layerElement.data = toVector3(positionData); + layerElement.dataIndices = null; + return layerElement; + } + + public static FbxLayerElement fromElement(FbxElement element) { + FbxLayerElement layerElement = new FbxLayerElement(); + if (!element.id.startsWith("LayerElement")) { + throw new IllegalArgumentException("Not a layer element"); + } + layerElement.index = (Integer)element.properties.get(0); + + String elementType = element.id.substring("LayerElement".length()); + try { + layerElement.type = Type.valueOf(elementType); + } catch (IllegalArgumentException ex) { + logger.log(Level.WARNING, "Unsupported layer element: {0}. Ignoring.", elementType); + } + for (FbxElement child : element.children) { + if (child.id.equals("MappingInformationType")) { + String mapInfoTypeVal = (String) child.properties.get(0); + if (mapInfoTypeVal.equals("ByVertice")) { + mapInfoTypeVal = "ByVertex"; + } + layerElement.mapInfoType = MappingInformationType.valueOf(mapInfoTypeVal); + } else if (child.id.equals("ReferenceInformationType")) { + String refInfoTypeVal = (String) child.properties.get(0); + if (refInfoTypeVal.equals("Index")) { + refInfoTypeVal = "IndexToDirect"; + } + layerElement.refInfoType = ReferenceInformationType.valueOf(refInfoTypeVal); + } else if (child.id.equals("Normals") || child.id.equals("Tangents") || child.id.equals("Binormals")) { + layerElement.data = toVector3(FbxMeshUtil.getDoubleArray(child)); + } else if (child.id.equals("Colors")) { + layerElement.data = toColorRGBA(FbxMeshUtil.getDoubleArray(child)); + } else if (child.id.equals("UV")) { + layerElement.data = toVector2(FbxMeshUtil.getDoubleArray(child)); + } else if (indexTypes.contains(child.id)) { + layerElement.dataIndices = FbxMeshUtil.getIntArray(child); + } else if (child.id.equals("Name")) { + layerElement.name = (String) child.properties.get(0); + } + } + if (layerElement.data == null) { + // For Smoothing / Materials, data = dataIndices + layerElement.refInfoType = ReferenceInformationType.Direct; + layerElement.data = new Integer[layerElement.dataIndices.length]; + for (int i = 0; i < layerElement.data.length; i++) { + layerElement.data[i] = layerElement.dataIndices[i]; + } + layerElement.dataIndices = null; + } + return layerElement; + } + + static Vector3f[] toVector3(double[] data) { + Vector3f[] vectors = new Vector3f[data.length / 3]; + for (int i = 0; i < vectors.length; i++) { + float x = (float) data[i * 3]; + float y = (float) data[i * 3 + 1]; + float z = (float) data[i * 3 + 2]; + vectors[i] = new Vector3f(x, y, z); + } + return vectors; + } + + static Vector2f[] toVector2(double[] data) { + Vector2f[] vectors = new Vector2f[data.length / 2]; + for (int i = 0; i < vectors.length; i++) { + float x = (float) data[i * 2]; + float y = (float) data[i * 2 + 1]; + vectors[i] = new Vector2f(x, y); + } + return vectors; + } + + static ColorRGBA[] toColorRGBA(double[] data) { + ColorRGBA[] colors = new ColorRGBA[data.length / 4]; + for (int i = 0; i < colors.length; i++) { + float r = (float) data[i * 4]; + float g = (float) data[i * 4 + 1]; + float b = (float) data[i * 4 + 2]; + float a = (float) data[i * 4 + 3]; + colors[i] = new ColorRGBA(r, g, b, a); + } + return colors; + } +} + diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/mesh/FbxMesh.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/mesh/FbxMesh.java new file mode 100644 index 000000000..5dd911bed --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/mesh/FbxMesh.java @@ -0,0 +1,316 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.mesh; + +import com.jme3.animation.Bone; +import com.jme3.animation.Skeleton; +import com.jme3.asset.AssetManager; +import com.jme3.math.ColorRGBA; +import com.jme3.math.Vector2f; +import com.jme3.math.Vector3f; +import com.jme3.scene.Mesh; +import com.jme3.scene.plugins.IrUtils; +import com.jme3.scene.plugins.IrBoneWeightIndex; +import com.jme3.scene.plugins.IrMesh; +import com.jme3.scene.plugins.IrPolygon; +import com.jme3.scene.plugins.IrVertex; +import com.jme3.scene.plugins.fbx.anim.FbxCluster; +import com.jme3.scene.plugins.fbx.anim.FbxLimbNode; +import com.jme3.scene.plugins.fbx.anim.FbxSkinDeformer; +import com.jme3.scene.plugins.fbx.file.FbxElement; +import com.jme3.scene.plugins.fbx.obj.FbxObject; +import com.jme3.scene.plugins.fbx.node.FbxNodeAttribute; +import com.jme3.util.IntMap; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +public final class FbxMesh extends FbxNodeAttribute> { + + private static final Logger logger = Logger.getLogger(FbxMesh.class.getName()); + + private FbxPolygon[] polygons; + private int[] edges; + private FbxLayerElement[] layerElements; + private Vector3f[] positions; + private FbxLayer[] layers; + + private ArrayList[] boneIndices; + private ArrayList[] boneWeights; + + private FbxSkinDeformer skinDeformer; + + public FbxMesh(AssetManager assetManager, String sceneFolderName) { + super(assetManager, sceneFolderName); + } + + @Override + public void fromElement(FbxElement element) { + super.fromElement(element); + + List layerElementsList = new ArrayList(); + List layersList = new ArrayList(); + + for (FbxElement e : element.children) { + if (e.id.equals("Vertices")) { + setPositions(FbxMeshUtil.getDoubleArray(e)); + } else if (e.id.equals("PolygonVertexIndex")) { + setPolygonVertexIndices(FbxMeshUtil.getIntArray(e)); + } else if (e.id.equals("Edges")) { + setEdges(FbxMeshUtil.getIntArray(e)); + } else if (e.id.startsWith("LayerElement")) { + layerElementsList.add(FbxLayerElement.fromElement(e)); + } else if (e.id.equals("Layer")) { + layersList.add(FbxLayer.fromElement(e)); + } + } + + for (FbxLayer layer : layersList) { + layer.setLayerElements(layerElementsList); + } + + layerElements = new FbxLayerElement[layerElementsList.size()]; + layerElementsList.toArray(layerElements); + + layers = new FbxLayer[layersList.size()]; + layersList.toArray(layers); + } + + public FbxSkinDeformer getSkinDeformer() { + return skinDeformer; + } + + public void applyCluster(FbxCluster cluster) { + if (boneIndices == null) { + boneIndices = new ArrayList[positions.length]; + boneWeights = new ArrayList[positions.length]; + } + + FbxLimbNode limb = cluster.getLimb(); + Bone bone = limb.getJmeBone(); + Skeleton skeleton = limb.getSkeletonHolder().getJmeSkeleton(); + int boneIndex = skeleton.getBoneIndex(bone); + + int[] positionIndices = cluster.getVertexIndices(); + double[] weights = cluster.getWeights(); + + for (int i = 0; i < positionIndices.length; i++) { + int positionIndex = positionIndices[i]; + float boneWeight = (float)weights[i]; + + ArrayList boneIndicesForVertex = boneIndices[positionIndex]; + ArrayList boneWeightsForVertex = boneWeights[positionIndex]; + + if (boneIndicesForVertex == null) { + boneIndicesForVertex = new ArrayList(); + boneWeightsForVertex = new ArrayList(); + boneIndices[positionIndex] = boneIndicesForVertex; + boneWeights[positionIndex] = boneWeightsForVertex; + } + + boneIndicesForVertex.add(boneIndex); + boneWeightsForVertex.add(boneWeight); + } + } + + @Override + public void connectObject(FbxObject object) { + if (object instanceof FbxSkinDeformer) { + if (skinDeformer != null) { + logger.log(Level.WARNING, "This mesh already has a skin deformer attached. Ignoring."); + return; + } + skinDeformer = (FbxSkinDeformer) object; + } else { + unsupportedConnectObject(object); + } + } + + @Override + public void connectObjectProperty(FbxObject object, String property) { + unsupportedConnectObjectProperty(object, property); + } + + private void setPositions(double[] positions) { + this.positions = FbxLayerElement.toVector3(positions); + } + + private void setEdges(int[] edges) { + this.edges = edges; + // TODO: ... + } + + private void setPolygonVertexIndices(int[] polygonVertexIndices) { + List polygonList = new ArrayList(); + + boolean finishPolygon = false; + List vertexIndices = new ArrayList(); + + for (int i = 0; i < polygonVertexIndices.length; i++) { + int vertexIndex = polygonVertexIndices[i]; + + if (vertexIndex < 0) { + vertexIndex ^= -1; + finishPolygon = true; + } + + vertexIndices.add(vertexIndex); + + if (finishPolygon) { + finishPolygon = false; + polygonList.add(FbxPolygon.fromIndices(vertexIndices)); + vertexIndices.clear(); + } + } + + polygons = new FbxPolygon[polygonList.size()]; + polygonList.toArray(polygons); + } + + private static IrBoneWeightIndex[] toBoneWeightIndices(List boneIndices, List boneWeights) { + IrBoneWeightIndex[] boneWeightIndices = new IrBoneWeightIndex[boneIndices.size()]; + for (int i = 0; i < boneIndices.size(); i++) { + boneWeightIndices[i] = new IrBoneWeightIndex(boneIndices.get(i), boneWeights.get(i)); + } + return boneWeightIndices; + } + + @Override + protected IntMap toJmeObject() { + // Load clusters from SkinDeformer + if (skinDeformer != null) { + for (FbxCluster cluster : skinDeformer.getJmeObject()) { + applyCluster(cluster); + } + } + + IrMesh irMesh = toIRMesh(); + + // Trim bone weights to 4 weights per vertex. + IrUtils.trimBoneWeights(irMesh); + + // Convert tangents / binormals to tangents with parity. + IrUtils.toTangentsWithParity(irMesh); + + // Triangulate quads. + IrUtils.triangulate(irMesh); + + // Split meshes by material indices. + IntMap irMeshes = IrUtils.splitByMaterial(irMesh); + + // Create a jME3 Mesh for each material index. + IntMap jmeMeshes = new IntMap(); + for (IntMap.Entry irMeshEntry : irMeshes) { + Mesh jmeMesh = IrUtils.convertIrMeshToJmeMesh(irMeshEntry.getValue()); + jmeMeshes.put(irMeshEntry.getKey(), jmeMesh); + } + + if (jmeMeshes.size() == 0) { + // When will this actually happen? Not sure. + logger.log(Level.WARNING, "Empty FBX mesh found (unusual)."); + } + + // IMPORTANT: If we have a -1 entry, those are triangles + // with no material indices. + // It makes sense only if the mesh uses a single material! + if (jmeMeshes.containsKey(-1) && jmeMeshes.size() > 1) { + logger.log(Level.WARNING, "Mesh has polygons with no material " + + "indices (unusual) - they will use material index 0."); + } + + return jmeMeshes; + } + + /** + * Convert FBXMesh to IRMesh. + */ + public IrMesh toIRMesh() { + IrMesh newMesh = new IrMesh(); + newMesh.polygons = new IrPolygon[polygons.length]; + + int polygonVertexIndex = 0; + int positionIndex = 0; + + FbxLayer layer0 = layers[0]; + FbxLayer layer1 = layers.length > 1 ? layers[1] : null; + + for (int i = 0; i < polygons.length; i++) { + FbxPolygon polygon = polygons[i]; + IrPolygon irPolygon = new IrPolygon(); + irPolygon.vertices = new IrVertex[polygon.indices.length]; + + for (int j = 0; j < polygon.indices.length; j++) { + positionIndex = polygon.indices[j]; + + IrVertex irVertex = new IrVertex(); + irVertex.pos = positions[positionIndex]; + + if (layer0 != null) { + irVertex.norm = (Vector3f) layer0.getVertexData(FbxLayerElement.Type.Normal, i, polygonVertexIndex, positionIndex, 0); + irVertex.tang = (Vector3f) layer0.getVertexData(FbxLayerElement.Type.Tangent, i, polygonVertexIndex, positionIndex, 0); + irVertex.bitang = (Vector3f) layer0.getVertexData(FbxLayerElement.Type.Binormal, i, polygonVertexIndex, positionIndex, 0); + irVertex.uv0 = (Vector2f) layer0.getVertexData(FbxLayerElement.Type.UV, i, polygonVertexIndex, positionIndex, 0); + irVertex.color = (ColorRGBA) layer0.getVertexData(FbxLayerElement.Type.Color, i, polygonVertexIndex, positionIndex, 0); + irVertex.material = (Integer) layer0.getVertexData(FbxLayerElement.Type.Material, i, polygonVertexIndex, positionIndex, 0); + irVertex.smoothing = (Integer) layer0.getVertexData(FbxLayerElement.Type.Smoothing, i, polygonVertexIndex, positionIndex, 0); + } + + if (layer1 != null) { + irVertex.uv1 = (Vector2f) layer1.getVertexData(FbxLayerElement.Type.UV, i, + polygonVertexIndex, positionIndex, 0); + } + + if (boneIndices != null) { + ArrayList boneIndicesForVertex = boneIndices[positionIndex]; + ArrayList boneWeightsForVertex = boneWeights[positionIndex]; + if (boneIndicesForVertex != null) { + irVertex.boneWeightsIndices = toBoneWeightIndices(boneIndicesForVertex, boneWeightsForVertex); + } + } + + irPolygon.vertices[j] = irVertex; + + polygonVertexIndex++; + } + + newMesh.polygons[i] = irPolygon; + } + + // Ensure "inspection vertex" specifies that mesh has bone indices / weights + if (boneIndices != null && newMesh.polygons[0].vertices[0] == null) { + newMesh.polygons[0].vertices[0].boneWeightsIndices = new IrBoneWeightIndex[0]; + } + + return newMesh; + } +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/mesh/FbxMeshUtil.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/mesh/FbxMeshUtil.java new file mode 100644 index 000000000..61fb001dd --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/mesh/FbxMeshUtil.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.mesh; + +import com.jme3.scene.plugins.fbx.file.FbxElement; + +public class FbxMeshUtil { + + public static double[] getDoubleArray(FbxElement el) { + if (el.propertiesTypes[0] == 'd') { + // FBX 7.x + return (double[]) el.properties.get(0); + } else if (el.propertiesTypes[0] == 'D') { + // FBX 6.x + double[] doubles = new double[el.propertiesTypes.length]; + for (int i = 0; i < doubles.length; i++) { + doubles[i] = (Double) el.properties.get(i); + } + return doubles; + } else { + return null; + } + } + + public static int[] getIntArray(FbxElement el) { + if (el.propertiesTypes[0] == 'i') { + // FBX 7.x + return (int[]) el.properties.get(0); + } else if (el.propertiesTypes[0] == 'I') { + // FBX 6.x + int[] ints = new int[el.propertiesTypes.length]; + for (int i = 0; i < ints.length; i++) { + ints[i] = (Integer) el.properties.get(i); + } + return ints; + } else { + return null; + } + } +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FBXElement.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/mesh/FbxPolygon.java similarity index 67% rename from jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FBXElement.java rename to jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/mesh/FbxPolygon.java index eeeee872c..bb7773785 100644 --- a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FBXElement.java +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/mesh/FbxPolygon.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009-2014 jMonkeyEngine + * Copyright (c) 2009-2015 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -29,36 +29,31 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package com.jme3.scene.plugins.fbx.file; +package com.jme3.scene.plugins.fbx.mesh; -import java.util.ArrayList; +import java.util.Arrays; import java.util.List; -public class FBXElement { - - public String id; - public List properties; - /* - * Y - signed short - * C - boolean - * I - signed integer - * F - float - * D - double - * L - long - * R - byte array - * S - string - * f - array of floats - * i - array of ints - * d - array of doubles - * l - array of longs - * b - array of boleans - * c - array of unsigned bytes (represented as array of ints) - */ - public char[] propertiesTypes; - public List children = new ArrayList(); - - public FBXElement(int propsCount) { - properties = new ArrayList(propsCount); - propertiesTypes = new char[propsCount]; - } +public final class FbxPolygon { + + int[] indices; + + @Override + public String toString() { + return Arrays.toString(indices); + } + + private static int[] listToArray(List indices) { + int[] indicesArray = new int[indices.size()]; + for (int i = 0; i < indices.size(); i++) { + indicesArray[i] = indices.get(i); + } + return indicesArray; + } + + public static FbxPolygon fromIndices(List indices) { + FbxPolygon poly = new FbxPolygon(); + poly.indices = listToArray(indices); + return poly; + } } diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/misc/FbxGlobalSettings.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/misc/FbxGlobalSettings.java new file mode 100644 index 000000000..3a815df6a --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/misc/FbxGlobalSettings.java @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.misc; + +import com.jme3.math.ColorRGBA; +import com.jme3.math.Quaternion; +import com.jme3.math.Transform; +import com.jme3.math.Vector3f; +import com.jme3.scene.plugins.fbx.file.FbxElement; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class FbxGlobalSettings { + + private static final Logger logger = Logger.getLogger(FbxGlobalSettings.class.getName()); + + private static final Map timeModeToFps = new HashMap(); + + static { + timeModeToFps.put(1, 120f); + timeModeToFps.put(2, 100f); + timeModeToFps.put(3, 60f); + timeModeToFps.put(4, 50f); + timeModeToFps.put(5, 48f); + timeModeToFps.put(6, 30f); + timeModeToFps.put(9, 30f / 1.001f); + timeModeToFps.put(10, 25f); + timeModeToFps.put(11, 24f); + timeModeToFps.put(13, 24f / 1.001f); + timeModeToFps.put(14, -1f); + timeModeToFps.put(15, 96f); + timeModeToFps.put(16, 72f); + timeModeToFps.put(17, 60f / 1.001f); + } + + public float unitScaleFactor = 1.0f; + public ColorRGBA ambientColor = ColorRGBA.Black; + public float frameRate = 25.0f; + + /** + * @return A {@link Transform} that converts from the FBX file coordinate + * system to jME3 coordinate system. + * jME3's coordinate system is: + *
      + *
    • Units are specified in meters.
    • + *
    • Orientation is right-handed with Y-up.
    • + *
    + */ + public Transform getGlobalTransform() { + // Default unit scale factor is 1 (centimeters), + // convert to meters. + float scale = unitScaleFactor / 100.0f; + + // TODO: handle rotation + + return new Transform(Vector3f.ZERO, Quaternion.IDENTITY, new Vector3f(scale, scale, scale)); + } + + public void fromElement(FbxElement element) { + // jME3 uses a +Y up, -Z forward coordinate system (same as OpenGL) + // Luckily enough, this is also the default for FBX models. + + int timeMode = -1; + float customFrameRate = 30.0f; + + for (FbxElement e2 : element.getFbxProperties()) { + String propName = (String) e2.properties.get(0); + if (propName.equals("UnitScaleFactor")) { + unitScaleFactor = ((Double) e2.properties.get(4)).floatValue(); + if (unitScaleFactor != 100.0f) { + logger.log(Level.WARNING, "FBX model isn't using meters for world units. Scale could be incorrect."); + } + } else if (propName.equals("TimeMode")) { + timeMode = (Integer) e2.properties.get(4); + } else if (propName.equals("CustomFrameRate")) { + float framerate = ((Double) e2.properties.get(4)).floatValue(); + if (framerate != -1) { + customFrameRate = framerate; + } + } else if (propName.equals("UpAxis")) { + Integer upAxis = (Integer) e2.properties.get(4); + if (upAxis != 1) { + logger.log(Level.WARNING, "FBX model isn't using Y as up axis. Orientation could be incorrect"); + } + } else if (propName.equals("UpAxisSign")) { + Integer upAxisSign = (Integer) e2.properties.get(4); + if (upAxisSign != 1) { + logger.log(Level.WARNING, "FBX model isn't using correct up axis sign. Orientation could be incorrect"); + } + } else if (propName.equals("FrontAxis")) { + Integer frontAxis = (Integer) e2.properties.get(4); + if (frontAxis != 2) { + logger.log(Level.WARNING, "FBX model isn't using Z as forward axis. Orientation could be incorrect"); + } + } else if (propName.equals("FrontAxisSign")) { + Integer frontAxisSign = (Integer) e2.properties.get(4); + if (frontAxisSign != -1) { + logger.log(Level.WARNING, "FBX model isn't using correct forward axis sign. Orientation could be incorrect"); + } + } + } + + Float fps = timeModeToFps.get(timeMode); + if (fps != null) { + if (fps == -1f) { + // Using custom framerate + frameRate = customFrameRate; + } else { + // Use FPS from time mode. + frameRate = fps; + } + } + } +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/node/FbxNode.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/node/FbxNode.java new file mode 100644 index 000000000..c0ce06d4b --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/node/FbxNode.java @@ -0,0 +1,617 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.node; + +import com.jme3.animation.AnimControl; +import com.jme3.animation.Skeleton; +import com.jme3.animation.SkeletonControl; +import com.jme3.asset.AssetManager; +import com.jme3.material.Material; +import com.jme3.math.ColorRGBA; +import com.jme3.math.FastMath; +import com.jme3.math.Matrix4f; +import com.jme3.math.Quaternion; +import com.jme3.math.Transform; +import com.jme3.math.Vector3f; +import com.jme3.renderer.queue.RenderQueue.Bucket; +import com.jme3.renderer.queue.RenderQueue.ShadowMode; +import com.jme3.scene.Geometry; +import com.jme3.scene.Mesh; +import com.jme3.scene.Node; +import com.jme3.scene.Spatial; +import com.jme3.scene.Spatial.CullHint; +import com.jme3.scene.debug.SkeletonDebugger; +import com.jme3.scene.plugins.fbx.anim.FbxAnimCurveNode; +import com.jme3.scene.plugins.fbx.anim.FbxCluster; +import com.jme3.scene.plugins.fbx.anim.FbxLimbNode; +import com.jme3.scene.plugins.fbx.anim.FbxSkinDeformer; +import com.jme3.scene.plugins.fbx.file.FbxElement; +import com.jme3.scene.plugins.fbx.material.FbxImage; +import com.jme3.scene.plugins.fbx.material.FbxMaterial; +import com.jme3.scene.plugins.fbx.material.FbxTexture; +import com.jme3.scene.plugins.fbx.mesh.FbxMesh; +import com.jme3.scene.plugins.fbx.obj.FbxObject; +import com.jme3.util.IntMap; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class FbxNode extends FbxObject { + + private static final Logger logger = Logger.getLogger(FbxNode.class.getName()); + + private static enum InheritMode { + /** + * Apply parent scale after child rotation. + * This is the only mode correctly supported by jME3. + */ + ScaleAfterChildRotation, + + /** + * Apply parent scale before child rotation. + * Not supported by jME3, will cause distortion with + * non-uniform scale. No way around it. + */ + ScaleBeforeChildRotation, + + /** + * Do not apply parent scale at all. + * Not supported by jME3, will cause distortion. + * Could be worked around by via: + * jmeChildScale = jmeParentScale / fbxChildScale + */ + NoParentScale + } + + private InheritMode inheritMode = InheritMode.ScaleAfterChildRotation; + + protected FbxNode parent; + protected List children = new ArrayList(); + protected List materials = new ArrayList(); + protected Map userData = new HashMap(); + protected Map> propertyToAnimCurveMap = new HashMap>(); + protected FbxNodeAttribute nodeAttribute; + protected double visibility = 1.0; + + /** + * For FBX nodes that contain a skeleton (i.e. FBX limbs). + */ + protected Skeleton skeleton; + + protected final Transform jmeWorldNodeTransform = new Transform(); + protected final Transform jmeLocalNodeTransform = new Transform(); + + // optional - used for limbs / bones / skeletons + protected Transform jmeWorldBindPose; + protected Transform jmeLocalBindPose; + + // used for debugging only + protected Matrix4f cachedWorldBindPose; + + public FbxNode(AssetManager assetManager, String sceneFolderName) { + super(assetManager, sceneFolderName); + } + + public Transform computeFbxLocalTransform() { + // TODO: implement the actual algorithm, which is this: + // Render Local Translation = + // Inv Scale Pivot * Lcl Scale * Scale Pivot * Scale Offset * Inv Rota Pivot * Post Rotation * Rotation * Pre Rotation * Rotation Pivot * Rotation Offset * Translation + + // LclTranslation, + // LclRotation, + // PreRotation, + // PostRotation, + // RotationPivot, + // RotationOffset, + // LclScaling, + // ScalingPivot, + // ScalingOffset + + Matrix4f scaleMat = new Matrix4f(); + scaleMat.setScale(jmeLocalNodeTransform.getScale()); + + Matrix4f rotationMat = new Matrix4f(); + rotationMat.setRotationQuaternion(jmeLocalNodeTransform.getRotation()); + + Matrix4f translationMat = new Matrix4f(); + translationMat.setTranslation(jmeLocalNodeTransform.getTranslation()); + + Matrix4f result = new Matrix4f(); + result.multLocal(scaleMat).multLocal(rotationMat).multLocal(translationMat); + + Transform t = new Transform(); + t.fromTransformMatrix(result); + + return t; + } + + public void setWorldBindPose(Matrix4f worldBindPose) { + if (cachedWorldBindPose != null) { + if (!cachedWorldBindPose.equals(worldBindPose)) { + throw new UnsupportedOperationException("Bind poses don't match"); + } + } + + cachedWorldBindPose = worldBindPose; + + this.jmeWorldBindPose = new Transform(); + this.jmeWorldBindPose.setTranslation(worldBindPose.toTranslationVector()); + this.jmeWorldBindPose.setRotation(worldBindPose.toRotationQuat()); + this.jmeWorldBindPose.setScale(worldBindPose.toScaleVector()); + + System.out.println("\tBind Pose for " + getName()); + System.out.println(jmeWorldBindPose); + + float[] angles = new float[3]; + jmeWorldBindPose.getRotation().toAngles(angles); + System.out.println("Angles: " + angles[0] * FastMath.RAD_TO_DEG + ", " + + angles[1] * FastMath.RAD_TO_DEG + ", " + + angles[2] * FastMath.RAD_TO_DEG); + } + + public void updateWorldTransforms(Transform jmeParentNodeTransform, Transform parentBindPose) { + Transform fbxLocalTransform = computeFbxLocalTransform(); + jmeLocalNodeTransform.set(fbxLocalTransform); + + if (jmeParentNodeTransform != null) { + jmeParentNodeTransform = jmeParentNodeTransform.clone(); + switch (inheritMode) { + case NoParentScale: + case ScaleAfterChildRotation: + case ScaleBeforeChildRotation: + jmeWorldNodeTransform.set(jmeLocalNodeTransform); + jmeWorldNodeTransform.combineWithParent(jmeParentNodeTransform); + break; + } + } else { + jmeWorldNodeTransform.set(jmeLocalNodeTransform); + } + + if (jmeWorldBindPose != null) { + jmeLocalBindPose = new Transform(); + + // Need to derive local bind pose from world bind pose + // (this is to be expected for FBX limbs) + jmeLocalBindPose.set(jmeWorldBindPose); + jmeLocalBindPose.combineWithParent(parentBindPose.invert()); + + // Its somewhat odd for the transforms to differ ... + System.out.println("Bind Pose for: " + getName()); + if (!jmeLocalBindPose.equals(jmeLocalNodeTransform)) { + System.out.println("Local Bind: " + jmeLocalBindPose); + System.out.println("Local Trans: " + jmeLocalNodeTransform); + } + if (!jmeWorldBindPose.equals(jmeWorldNodeTransform)) { + System.out.println("World Bind: " + jmeWorldBindPose); + System.out.println("World Trans: " + jmeWorldNodeTransform); + } + } else { + // World pose derived from local transforms + // (this is to be expected for FBX nodes) + jmeLocalBindPose = new Transform(); + jmeWorldBindPose = new Transform(); + + jmeLocalBindPose.set(jmeLocalNodeTransform); + if (parentBindPose != null) { + jmeWorldBindPose.set(jmeLocalNodeTransform); + jmeWorldBindPose.combineWithParent(parentBindPose); + } else { + jmeWorldBindPose.set(jmeWorldNodeTransform); + } + } + + for (FbxNode child : children) { + child.updateWorldTransforms(jmeWorldNodeTransform, jmeWorldBindPose); + } + } + + @Override + public void fromElement(FbxElement element) { + super.fromElement(element); + + Vector3f localTranslation = new Vector3f(); + Quaternion localRotation = new Quaternion(); + Vector3f localScale = new Vector3f(Vector3f.UNIT_XYZ); + Quaternion preRotation = new Quaternion(); + + for (FbxElement e2 : element.getFbxProperties()) { + String propName = (String) e2.properties.get(0); + String type = (String) e2.properties.get(3); + if (propName.equals("Lcl Translation")) { + double x = (Double) e2.properties.get(4); + double y = (Double) e2.properties.get(5); + double z = (Double) e2.properties.get(6); + localTranslation.set((float) x, (float) y, (float) z); //.divideLocal(unitSize); + } else if (propName.equals("Lcl Rotation")) { + double x = (Double) e2.properties.get(4); + double y = (Double) e2.properties.get(5); + double z = (Double) e2.properties.get(6); + localRotation.fromAngles((float) x * FastMath.DEG_TO_RAD, (float) y * FastMath.DEG_TO_RAD, (float) z * FastMath.DEG_TO_RAD); + } else if (propName.equals("Lcl Scaling")) { + double x = (Double) e2.properties.get(4); + double y = (Double) e2.properties.get(5); + double z = (Double) e2.properties.get(6); + localScale.set((float) x, (float) y, (float) z); //.multLocal(unitSize); + } else if (propName.equals("PreRotation")) { + double x = (Double) e2.properties.get(4); + double y = (Double) e2.properties.get(5); + double z = (Double) e2.properties.get(6); + preRotation.set(FbxNodeUtil.quatFromBoneAngles((float) x * FastMath.DEG_TO_RAD, (float) y * FastMath.DEG_TO_RAD, (float) z * FastMath.DEG_TO_RAD)); + } else if (propName.equals("InheritType")) { + int inheritType = (Integer) e2.properties.get(4); + inheritMode = InheritMode.values()[inheritType]; + } else if (propName.equals("Visibility")) { + visibility = (Double) e2.properties.get(4); + } else if (type.contains("U")) { + String userDataKey = (String) e2.properties.get(0); + String userDataType = (String) e2.properties.get(1); + Object userDataValue; + + if (userDataType.equals("KString")) { + userDataValue = (String) e2.properties.get(4); + } else if (userDataType.equals("int")) { + userDataValue = (Integer) e2.properties.get(4); + } else if (userDataType.equals("double")) { + // NOTE: jME3 does not support doubles in UserData. + // Need to convert to float. + userDataValue = ((Double) e2.properties.get(4)).floatValue(); + } else if (userDataType.equals("Vector")) { + float x = ((Double) e2.properties.get(4)).floatValue(); + float y = ((Double) e2.properties.get(5)).floatValue(); + float z = ((Double) e2.properties.get(6)).floatValue(); + userDataValue = new Vector3f(x, y, z); + } else { + logger.log(Level.WARNING, "Unsupported user data type: {0}. Ignoring.", userDataType); + continue; + } + + userData.put(userDataKey, userDataValue); + } + } + + // Create local transform + // TODO: take into account Maya-style transforms (pre / post rotation ..) + jmeLocalNodeTransform.setTranslation(localTranslation); + jmeLocalNodeTransform.setRotation(localRotation); + jmeLocalNodeTransform.setScale(localScale); + + if (element.getChildById("Vertices") != null) { + // This is an old-style FBX 6.1 + // Meshes could be embedded inside the node.. + + // Inject the mesh into ourselves.. + FbxMesh mesh = new FbxMesh(assetManager, sceneFolderName); + mesh.fromElement(element); + connectObject(mesh); + } + } + + private Spatial tryCreateGeometry(int materialIndex, Mesh jmeMesh, boolean single) { + // Map meshes without material indices to material 0. + if (materialIndex == -1) { + materialIndex = 0; + } + + Material jmeMat; + if (materialIndex >= materials.size()) { + // Material index does not exist. Create default material. + jmeMat = new Material(assetManager, "Common/MatDefs/Light/Lighting.j3md"); + jmeMat.setReceivesShadows(true); + } else { + FbxMaterial fbxMat = materials.get(materialIndex); + jmeMat = fbxMat.getJmeObject(); + } + + String geomName = getName(); + if (single) { + geomName += "-submesh"; + } else { + geomName += "-mat-" + materialIndex + "-submesh"; + } + Spatial spatial = new Geometry(geomName, jmeMesh); + spatial.setMaterial(jmeMat); + if (jmeMat.isTransparent()) { + spatial.setQueueBucket(Bucket.Transparent); + } + if (jmeMat.isReceivesShadows()) { + spatial.setShadowMode(ShadowMode.Receive); + } + spatial.updateModelBound(); + return spatial; + } + + /** + * If this geometry node is deformed by a skeleton, this + * returns the node containing the skeleton. + * + * In jME3, a mesh can be deformed by a skeleton only if it is + * a child of the node containing the skeleton. However, this + * is not a requirement in FBX, so we have to modify the scene graph + * of the loaded model to adjust for this. + * This happens automatically in + * {@link #createScene(com.jme3.scene.plugins.fbx.node.FbxNode)}. + * + * @return The model this node would like to be a child of, or null + * if no preferred parent. + */ + public FbxNode getPreferredParent() { + if (!(nodeAttribute instanceof FbxMesh)) { + return null; + } + + FbxMesh fbxMesh = (FbxMesh) nodeAttribute; + FbxSkinDeformer deformer = fbxMesh.getSkinDeformer(); + FbxNode preferredParent = null; + + if (deformer != null) { + for (FbxCluster cluster : deformer.getJmeObject()) { + FbxLimbNode limb = cluster.getLimb(); + if (preferredParent == null) { + preferredParent = limb.getSkeletonHolder(); + } else if (preferredParent != limb.getSkeletonHolder()) { + logger.log(Level.WARNING, "A mesh is being deformed by multiple skeletons. " + + "Only one skeleton will work, ignoring other skeletons."); + } + } + } + + return preferredParent; + } + + @Override + public Spatial toJmeObject() { + Spatial spatial; + + if (nodeAttribute instanceof FbxMesh) { + FbxMesh fbxMesh = (FbxMesh) nodeAttribute; + IntMap jmeMeshes = fbxMesh.getJmeObject(); + + if (jmeMeshes == null || jmeMeshes.size() == 0) { + // No meshes found on FBXMesh (??) + logger.log(Level.WARNING, "No meshes could be loaded. Creating empty node."); + spatial = new Node(getName() + "-node"); + } else { + // Multiple jME3 geometries required for a single FBXMesh. + String nodeName; + if (children.isEmpty()) { + nodeName = getName() + "-mesh"; + } else { + nodeName = getName() + "-node"; + } + Node node = new Node(nodeName); + boolean singleMesh = jmeMeshes.size() == 1; + for (IntMap.Entry meshInfo : jmeMeshes) { + node.attachChild(tryCreateGeometry(meshInfo.getKey(), meshInfo.getValue(), singleMesh)); + } + spatial = node; + } + } else { + if (nodeAttribute != null) { + // Just specifies that this is a "null" node. + nodeAttribute.getJmeObject(); + } + + // TODO: handle other node attribute types. + // right now everything we don't know about gets converted + // to jME3 Node. + spatial = new Node(getName() + "-node"); + } + + if (!children.isEmpty()) { + // Check uniform scale. + // Although, if inheritType is 0 (eInheritRrSs) + // it might not be a problem. + Vector3f localScale = jmeLocalNodeTransform.getScale(); + if (!FastMath.approximateEquals(localScale.x, localScale.y) || + !FastMath.approximateEquals(localScale.x, localScale.z)) { + logger.log(Level.WARNING, "Non-uniform scale detected on parent node. " + + "The model may appear distorted."); + } + } + + spatial.setLocalTransform(jmeLocalNodeTransform); + + if (visibility == 0.0) { + spatial.setCullHint(CullHint.Always); + } + + for (Map.Entry userDataEntry : userData.entrySet()) { + spatial.setUserData(userDataEntry.getKey(), userDataEntry.getValue()); + } + + return spatial; + } + + /** + * Create jME3 Skeleton objects on the scene. + * + * Goes through the scene graph and finds limbs that are + * attached to FBX nodes, then creates a Skeleton on the node + * based on the child limbs. + * + * Must be called prior to calling + * {@link #createScene(com.jme3.scene.plugins.fbx.node.FbxNode)}. + * + * @param fbxNode The root FBX node. + */ + public static void createSkeletons(FbxNode fbxNode) { + boolean createSkeleton = false; + for (FbxNode fbxChild : fbxNode.children) { + if (fbxChild instanceof FbxLimbNode) { + createSkeleton = true; + } else { + createSkeletons(fbxChild); + } + } + if (createSkeleton) { + if (fbxNode.skeleton != null) { + throw new UnsupportedOperationException(); + } + fbxNode.skeleton = FbxLimbNode.createSkeleton(fbxNode); + System.out.println("created skeleton: " + fbxNode.skeleton); + } + } + + private static void relocateSpatial(Spatial spatial, + Transform originalWorldTransform, Transform newWorldTransform) { + Transform localTransform = new Transform(); + localTransform.set(originalWorldTransform); + localTransform.combineWithParent(newWorldTransform.invert()); + spatial.setLocalTransform(localTransform); + } + + public static Spatial createScene(FbxNode fbxNode) { + Spatial jmeSpatial = fbxNode.getJmeObject(); + + if (jmeSpatial instanceof Node) { + // Attach children to Node + Node jmeNode = (Node) jmeSpatial; + for (FbxNode fbxChild : fbxNode.children) { + if (!(fbxChild instanceof FbxLimbNode)) { + createScene(fbxChild); + + FbxNode preferredParent = fbxChild.getPreferredParent(); + Spatial jmeChild = fbxChild.getJmeObject(); + if (preferredParent != null) { + System.out.println("Preferred parent for " + fbxChild + " is " + preferredParent); + + Node jmePreferredParent = (Node) preferredParent.getJmeObject(); + relocateSpatial(jmeChild, fbxChild.jmeWorldNodeTransform, + preferredParent.jmeWorldNodeTransform); + jmePreferredParent.attachChild(jmeChild); + } else { + jmeNode.attachChild(jmeChild); + } + } + } + } + + if (fbxNode.skeleton != null) { + jmeSpatial.addControl(new AnimControl(fbxNode.skeleton)); + jmeSpatial.addControl(new SkeletonControl(fbxNode.skeleton)); + + SkeletonDebugger sd = new SkeletonDebugger("debug", fbxNode.skeleton); + Material mat = new Material(fbxNode.assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); + mat.getAdditionalRenderState().setWireframe(true); + mat.getAdditionalRenderState().setDepthTest(false); + mat.setColor("Color", ColorRGBA.Green); + sd.setMaterial(mat); + + ((Node)jmeSpatial).attachChild(sd); + } + + return jmeSpatial; + } + +// public SceneLoader.Limb toLimb() { +// SceneLoader.Limb limb = new SceneLoader.Limb(); +// limb.name = getName(); +// Quaternion rotation = preRotation.mult(localRotation); +// limb.bindTransform = new Transform(localTranslation, rotation, localScale); +// return limb; +// } + + public Skeleton getJmeSkeleton() { + return skeleton; + } + + public List getChildren() { + return children; + } + + @Override + public void connectObject(FbxObject object) { + if (object instanceof FbxNode) { + // Scene Graph Object + FbxNode childNode = (FbxNode) object; + if (childNode.parent != null) { + throw new IllegalStateException("Cannot attach " + childNode + + " to " + this + ". It is already " + + "attached to " + childNode.parent); + } + childNode.parent = this; + children.add(childNode); + } else if (object instanceof FbxNodeAttribute) { + // Node Attribute + if (nodeAttribute != null) { + throw new IllegalStateException("An FBXNodeAttribute (" + nodeAttribute + ")" + + " is already attached to " + this + ". " + + "Only one attribute allowed per node."); + } + + nodeAttribute = (FbxNodeAttribute) object; + if (nodeAttribute instanceof FbxNullAttribute) { + nodeAttribute.getJmeObject(); + } + } else if (object instanceof FbxMaterial) { + materials.add((FbxMaterial) object); + } else if (object instanceof FbxImage || object instanceof FbxTexture) { + // Ignore - attaching textures to nodes is legacy feature. + } else { + unsupportedConnectObject(object); + } + } + + @Override + public void connectObjectProperty(FbxObject object, String property) { + // Only allowed to connect local transform properties to object + // (FbxAnimCurveNode) + if (object instanceof FbxAnimCurveNode) { + FbxAnimCurveNode curveNode = (FbxAnimCurveNode) object; + if (property.equals("Lcl Translation") + || property.equals("Lcl Rotation") + || property.equals("Lcl Scaling")) { + + List curveNodes = propertyToAnimCurveMap.get(property); + if (curveNodes == null) { + curveNodes = new ArrayList(); + curveNodes.add(curveNode); + propertyToAnimCurveMap.put(property, curveNodes); + } + curveNodes.add(curveNode); + + // Make sure the curve knows about it animating + // this node as well. + curveNode.addInfluencedNode(this, property); + } else { + logger.log(Level.WARNING, "Animating the property ''{0}'' is not " + + "supported. Ignoring.", property); + } + } else { + unsupportedConnectObjectProperty(object, property); + } + } + +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/node/FbxNodeAttribute.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/node/FbxNodeAttribute.java new file mode 100644 index 000000000..b63e4bc08 --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/node/FbxNodeAttribute.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.node; + +import com.jme3.asset.AssetManager; +import com.jme3.scene.plugins.fbx.obj.FbxObject; + +public abstract class FbxNodeAttribute extends FbxObject { + public FbxNodeAttribute(AssetManager assetManager, String sceneFolderName) { + super(assetManager, sceneFolderName); + } +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/node/FbxNodeUtil.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/node/FbxNodeUtil.java new file mode 100644 index 000000000..8c35e45e9 --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/node/FbxNodeUtil.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.node; + +import com.jme3.math.FastMath; +import com.jme3.math.Quaternion; + +public class FbxNodeUtil { + public static Quaternion quatFromBoneAngles(float xAngle, float yAngle, float zAngle) { + float angle; + float sinY, sinZ, sinX, cosY, cosZ, cosX; + angle = zAngle * 0.5f; + sinZ = FastMath.sin(angle); + cosZ = FastMath.cos(angle); + angle = yAngle * 0.5f; + sinY = FastMath.sin(angle); + cosY = FastMath.cos(angle); + angle = xAngle * 0.5f; + sinX = FastMath.sin(angle); + cosX = FastMath.cos(angle); + float cosYXcosZ = cosY * cosZ; + float sinYXsinZ = sinY * sinZ; + float cosYXsinZ = cosY * sinZ; + float sinYXcosZ = sinY * cosZ; + // For some reason bone space is differ, this is modified formulas + float w = (cosYXcosZ * cosX + sinYXsinZ * sinX); + float x = (cosYXcosZ * sinX - sinYXsinZ * cosX); + float y = (sinYXcosZ * cosX + cosYXsinZ * sinX); + float z = (cosYXsinZ * cosX - sinYXcosZ * sinX); + return new Quaternion(x, y, z, w).normalizeLocal(); + } +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/node/FbxNullAttribute.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/node/FbxNullAttribute.java new file mode 100644 index 000000000..ce95546d8 --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/node/FbxNullAttribute.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.node; + +import com.jme3.asset.AssetManager; +import com.jme3.scene.plugins.fbx.obj.FbxObject; + +public class FbxNullAttribute extends FbxNodeAttribute { + + public FbxNullAttribute(AssetManager assetManager, String sceneFolderName) { + super(assetManager, sceneFolderName); + } + + @Override + protected Object toJmeObject() { + // No data in a "Null" attribute. + return new Object(); + } + + @Override + public void connectObject(FbxObject object) { + throw new UnsupportedOperationException(); + } + + @Override + public void connectObjectProperty(FbxObject object, String property) { + throw new UnsupportedOperationException(); + } + +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/node/FbxRootNode.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/node/FbxRootNode.java new file mode 100644 index 000000000..83db50283 --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/node/FbxRootNode.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.node; + +import com.jme3.asset.AssetManager; +import com.jme3.scene.plugins.fbx.file.FbxId; + +public class FbxRootNode extends FbxNode { + public FbxRootNode(AssetManager assetManager, String sceneFolderName) { + super(assetManager, sceneFolderName); + this.id = FbxId.ROOT; + this.className = "Model"; + this.name = "Scene"; + this.subclassName = ""; + } +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/obj/FbxObject.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/obj/FbxObject.java new file mode 100644 index 000000000..d9439a2d4 --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/obj/FbxObject.java @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.obj; + +import com.jme3.asset.AssetManager; +import com.jme3.scene.plugins.fbx.file.FbxElement; +import com.jme3.scene.plugins.fbx.file.FbxId; +import java.util.logging.Logger; + +public abstract class FbxObject { + + private static final Logger logger = Logger.getLogger(FbxObject.class.getName()); + + protected AssetManager assetManager; + protected String sceneFolderName; + + protected FbxId id; + protected String name; + protected String className; + protected String subclassName; + + protected JT jmeObject; // lazily initialized + + protected FbxObject(AssetManager assetManager, String sceneFolderName) { + this.assetManager = assetManager; + this.sceneFolderName = sceneFolderName; + } + + public FbxId getId() { + return id; + } + + public String getName() { + return name; + } + + public String getClassName() { + return className; + } + + public String getSubclassName() { + return subclassName; + } + + public String getFullClassName() { + if (subclassName.equals("")) { + return className; + } else { + return subclassName + " : " + className; + } + } + + @Override + public String toString() { + return name + " (" + id + ")"; + } + + protected void fromElement(FbxElement element) { + id = FbxId.getObjectId(element); + String nameAndClass; + if (element.propertiesTypes.length == 3) { + nameAndClass = (String) element.properties.get(1); + subclassName = (String) element.properties.get(2); + } else if (element.propertiesTypes.length == 2) { + nameAndClass = (String) element.properties.get(0); + subclassName = (String) element.properties.get(1); + } else { + throw new UnsupportedOperationException("This is not an FBX object: " + element.id); + } + + int splitter = nameAndClass.indexOf("\u0000\u0001"); + + if (splitter != -1) { + name = nameAndClass.substring(0, splitter); + className = nameAndClass.substring(splitter + 2); + } else { + name = nameAndClass; + className = null; + } + } + + public final JT getJmeObject() { + if (jmeObject == null) { + jmeObject = toJmeObject(); + if (jmeObject == null) { + throw new UnsupportedOperationException("FBX object subclass " + + "failed to resolve to a jME3 object"); + } + } + return jmeObject; + } + + public final boolean isJmeObjectCreated() { + return jmeObject != null; + } + + protected final void unsupportedConnectObject(FbxObject object) { + throw new IllegalArgumentException("Cannot attach objects of this class (" + + object.getFullClassName() + + ") to " + getClass().getSimpleName()); + } + + protected final void unsupportedConnectObjectProperty(FbxObject object, String property) { + throw new IllegalArgumentException("Cannot attach objects of this class (" + + object.getFullClassName() + + ") to property " + getClass().getSimpleName() + + "[\"" + property + "\"]"); + } + + protected abstract JT toJmeObject(); + + public abstract void connectObject(FbxObject object); + + public abstract void connectObjectProperty(FbxObject object, String property); +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/obj/FbxObjectFactory.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/obj/FbxObjectFactory.java new file mode 100644 index 000000000..ec8c1fd67 --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/obj/FbxObjectFactory.java @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.obj; + +import com.jme3.asset.AssetManager; +import com.jme3.scene.plugins.fbx.anim.FbxAnimCurve; +import com.jme3.scene.plugins.fbx.anim.FbxAnimCurveNode; +import com.jme3.scene.plugins.fbx.anim.FbxAnimLayer; +import com.jme3.scene.plugins.fbx.anim.FbxAnimStack; +import com.jme3.scene.plugins.fbx.anim.FbxBindPose; +import com.jme3.scene.plugins.fbx.anim.FbxCluster; +import com.jme3.scene.plugins.fbx.anim.FbxLimbNode; +import com.jme3.scene.plugins.fbx.anim.FbxSkinDeformer; +import com.jme3.scene.plugins.fbx.file.FbxElement; +import com.jme3.scene.plugins.fbx.material.FbxImage; +import com.jme3.scene.plugins.fbx.material.FbxMaterial; +import com.jme3.scene.plugins.fbx.material.FbxTexture; +import com.jme3.scene.plugins.fbx.mesh.FbxMesh; +import com.jme3.scene.plugins.fbx.node.FbxNode; +import com.jme3.scene.plugins.fbx.node.FbxNullAttribute; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Responsible for producing FBX objects given an FBXElement. + */ +public final class FbxObjectFactory { + + private static final Logger logger = Logger.getLogger(FbxObjectFactory.class.getName()); + + private static Class getImplementingClass(String elementName, String subclassName) { + if (elementName.equals("NodeAttribute")) { + if (subclassName.equals("Root")) { + // Root of skeleton, may not actually be set. + return FbxNullAttribute.class; + } else if (subclassName.equals("LimbNode")) { + // Specifies some limb attributes, optional. + return FbxNullAttribute.class; + } else if (subclassName.equals("Null")) { + // An "Empty" or "Node" without any specific behavior. + return FbxNullAttribute.class; + } else if (subclassName.equals("IKEffector") || + subclassName.equals("FKEffector")) { + // jME3 does not support IK. + return FbxNullAttribute.class; + } else { + // NodeAttribute - Unknown + logger.log(Level.WARNING, "Unknown object subclass: {0}. Ignoring.", subclassName); + return FbxUnknownObject.class; + } + } else if (elementName.equals("Geometry") && subclassName.equals("Mesh")) { + // NodeAttribute - Mesh Data + return FbxMesh.class; + } else if (elementName.equals("Model")) { + // Scene Graph Node + // Determine specific subclass (e.g. Mesh, Null, or LimbNode?) + if (subclassName.equals("LimbNode")) { + return FbxLimbNode.class; // Child Bone of Skeleton? + } else { + return FbxNode.class; + } + } else if (elementName.equals("Pose")) { + if (subclassName.equals("BindPose")) { + // Bind Pose Information + return FbxBindPose.class; + } else { + // Rest Pose Information + // OR + // Other Data (???) + logger.log(Level.WARNING, "Unknown object subclass: {0}. Ignoring.", subclassName); + return FbxUnknownObject.class; + } + } else if (elementName.equals("Material")) { + return FbxMaterial.class; + } else if (elementName.equals("Deformer")) { + // Deformer + if (subclassName.equals("Skin")) { + // FBXSkinDeformer (mapping between FBXMesh & FBXClusters) + return FbxSkinDeformer.class; + } else if (subclassName.equals("Cluster")) { + // Cluster (aka mapping between FBXMesh vertices & weights for bone) + return FbxCluster.class; + } else { + logger.log(Level.WARNING, "Unknown deformer subclass: {0}. Ignoring.", subclassName); + return FbxUnknownObject.class; + } + } else if (elementName.equals("Video")) { + if (subclassName.equals("Clip")) { + return FbxImage.class; + } else { + logger.log(Level.WARNING, "Unknown object subclass: {0}. Ignoring.", subclassName); + return FbxUnknownObject.class; + } + } else if (elementName.equals("Texture")) { + return FbxTexture.class; + } else if (elementName.equals("AnimationStack")) { + // AnimationStack (jME Animation) + return FbxAnimStack.class; + } else if (elementName.equals("AnimationLayer")) { + // AnimationLayer (for blended animation - not supported) + return FbxAnimLayer.class; + } else if (elementName.equals("AnimationCurveNode")) { + // AnimationCurveNode + return FbxAnimCurveNode.class; + } else if (elementName.equals("AnimationCurve")) { + // AnimationCurve (Data) + return FbxAnimCurve.class; + } else if (elementName.equals("SceneInfo")) { + // Old-style FBX 6.1 uses this. Nothing useful here. + return FbxUnknownObject.class; + } else { + logger.log(Level.WARNING, "Unknown object class: {0}. Ignoring.", elementName); + return FbxUnknownObject.class; + } + } + + /** + * Automatically create an FBXObject by inspecting its class / subclass + * properties. + * + * @param element The element from which to create an object. + * @param assetManager AssetManager to load dependent resources + * @param sceneFolderName Folder relative to which resources shall be loaded + * @return The object, or null if not supported (?) + */ + public static FbxObject createObject(FbxElement element, AssetManager assetManager, String sceneFolderName) { + String elementName = element.id; + String subclassName; + + if (element.propertiesTypes.length == 3) { + // FBX 7.x (all objects start with Long ID) + subclassName = (String) element.properties.get(2); + } else if (element.propertiesTypes.length == 2) { + // FBX 6.x (objects only have name and subclass) + subclassName = (String) element.properties.get(1); + } else { + // Not an object or invalid data. + return null; + } + + Class javaFbxClass = getImplementingClass(elementName, subclassName); + + if (javaFbxClass != null) { + try { + // This object is supported by FBX importer, create new instance. + // Import the data into the object from the element, then return it. + Constructor ctor = javaFbxClass.getConstructor(AssetManager.class, String.class); + FbxObject obj = ctor.newInstance(assetManager, sceneFolderName); + obj.fromElement(element); + + String subClassName = elementName + ", " + subclassName; + if (obj.assetManager == null) { + throw new IllegalStateException("FBXObject subclass (" + subClassName + + ") forgot to call super() in their constructor"); + } else if (obj.className == null) { + throw new IllegalStateException("FBXObject subclass (" + subClassName + + ") forgot to call super.fromElement() in their fromElement() implementation"); + } + return obj; + } catch (InvocationTargetException ex) { + // Programmer error. + throw new IllegalStateException(ex); + } catch (NoSuchMethodException ex) { + // Programmer error. + throw new IllegalStateException(ex); + } catch (InstantiationException ex) { + // Programmer error. + throw new IllegalStateException(ex); + } catch (IllegalAccessException ex) { + // Programmer error. + throw new IllegalStateException(ex); + } + } + + // Not supported object. + return null; + } +} diff --git a/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/obj/FbxUnknownObject.java b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/obj/FbxUnknownObject.java new file mode 100644 index 000000000..9a1eaa910 --- /dev/null +++ b/jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/obj/FbxUnknownObject.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins.fbx.obj; + +import com.jme3.asset.AssetManager; + +public class FbxUnknownObject extends FbxObject { + + public FbxUnknownObject(AssetManager assetManager, String sceneFolderName) { + super(assetManager, sceneFolderName); + } + + @Override + protected Void toJmeObject() { + throw new UnsupportedOperationException(); + } + + @Override + public void connectObject(FbxObject object) { + } + + @Override + public void connectObjectProperty(FbxObject object, String property) { + } +} diff --git a/jme3-plugins/src/main/java/com/jme3/scene/plugins/IrBoneWeightIndex.java b/jme3-plugins/src/main/java/com/jme3/scene/plugins/IrBoneWeightIndex.java new file mode 100644 index 000000000..523993f51 --- /dev/null +++ b/jme3-plugins/src/main/java/com/jme3/scene/plugins/IrBoneWeightIndex.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins; + +public class IrBoneWeightIndex implements Cloneable, Comparable { + + int boneIndex; + float boneWeight; + + public IrBoneWeightIndex(int boneIndex, float boneWeight) { + this.boneIndex = boneIndex; + this.boneWeight = boneWeight; + } + + @Override + public Object clone() { + try { + return super.clone(); + } catch (CloneNotSupportedException ex) { + throw new AssertionError(ex); + } + } + + @Override + public int hashCode() { + int hash = 7; + hash = 23 * hash + this.boneIndex; + hash = 23 * hash + Float.floatToIntBits(this.boneWeight); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final IrBoneWeightIndex other = (IrBoneWeightIndex) obj; + if (this.boneIndex != other.boneIndex) { + return false; + } + if (Float.floatToIntBits(this.boneWeight) != Float.floatToIntBits(other.boneWeight)) { + return false; + } + return true; + } + + @Override + public int compareTo(IrBoneWeightIndex o) { + if (boneWeight < o.boneWeight) { + return 1; + } else if (boneWeight > o.boneWeight) { + return -1; + } else { + return 0; + } + } +} diff --git a/jme3-plugins/src/main/java/com/jme3/scene/plugins/IrMesh.java b/jme3-plugins/src/main/java/com/jme3/scene/plugins/IrMesh.java new file mode 100644 index 000000000..8bb5a6881 --- /dev/null +++ b/jme3-plugins/src/main/java/com/jme3/scene/plugins/IrMesh.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins; + +public class IrMesh { + + public IrPolygon[] polygons; + + public IrMesh deepClone() { + IrMesh m = new IrMesh(); + m.polygons = new IrPolygon[polygons.length]; + for (int i = 0; i < polygons.length; i++) { + m.polygons[i] = polygons[i].deepClone(); + } + return m; + } +} diff --git a/jme3-plugins/src/main/java/com/jme3/scene/plugins/IrPolygon.java b/jme3-plugins/src/main/java/com/jme3/scene/plugins/IrPolygon.java new file mode 100644 index 000000000..7bb47cb54 --- /dev/null +++ b/jme3-plugins/src/main/java/com/jme3/scene/plugins/IrPolygon.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins; + +public class IrPolygon { + + public IrVertex[] vertices; + + public IrPolygon deepClone() { + IrPolygon p = new IrPolygon(); + p.vertices = new IrVertex[vertices.length]; + for (int i = 0; i < vertices.length; i++) { + p.vertices[i] = vertices[i].deepClone(); + } + return p; + } +} diff --git a/jme3-plugins/src/main/java/com/jme3/scene/plugins/IrUtils.java b/jme3-plugins/src/main/java/com/jme3/scene/plugins/IrUtils.java new file mode 100644 index 000000000..7b20e1670 --- /dev/null +++ b/jme3-plugins/src/main/java/com/jme3/scene/plugins/IrUtils.java @@ -0,0 +1,400 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins; + +import com.jme3.math.Vector4f; +import com.jme3.scene.Mesh; +import com.jme3.scene.VertexBuffer; +import com.jme3.scene.mesh.IndexBuffer; +import com.jme3.scene.mesh.IndexIntBuffer; +import com.jme3.scene.mesh.IndexShortBuffer; +import com.jme3.util.BufferUtils; +import com.jme3.util.IntMap; +import java.nio.ByteBuffer; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; +import java.nio.ShortBuffer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +public final class IrUtils { + + private static final Logger logger = Logger.getLogger(IrUtils.class.getName()); + + private IrUtils() { } + + private static IrPolygon[] quadToTri(IrPolygon quad) { + if (quad.vertices.length == 3) { + throw new IllegalStateException("Already a triangle"); + } + + IrPolygon[] t = new IrPolygon[]{ new IrPolygon(), new IrPolygon() }; + t[0].vertices = new IrVertex[3]; + t[1].vertices = new IrVertex[3]; + + IrVertex v0 = quad.vertices[0]; + IrVertex v1 = quad.vertices[1]; + IrVertex v2 = quad.vertices[2]; + IrVertex v3 = quad.vertices[3]; + + // find the pair of verticies that is closest to each over + // v0 and v2 + // OR + // v1 and v3 + float d1 = v0.pos.distanceSquared(v2.pos); + float d2 = v1.pos.distanceSquared(v3.pos); + if (d1 < d2) { + // v0 is close to v2 + // put an edge in v0, v2 + t[0].vertices[0] = v0; + t[0].vertices[1] = v1; + t[0].vertices[2] = v3; + + t[1].vertices[0] = v1; + t[1].vertices[1] = v2; + t[1].vertices[2] = v3; + } else { + // put an edge in v1, v3 + t[0].vertices[0] = v0; + t[0].vertices[1] = v1; + t[0].vertices[2] = v2; + + t[1].vertices[0] = v0; + t[1].vertices[1] = v2; + t[1].vertices[2] = v3; + } + + return t; + } + + /** + * Applies smoothing groups to vertex normals. + */ + public static IrMesh applySmoothingGroups(IrMesh mesh) { + return null; + } + + private static void toTangentsWithParity(IrVertex vertex) { + if (vertex.tang != null && vertex.bitang != null) { + float wCoord = vertex.norm.cross(vertex.tang).dot(vertex.bitang) < 0f ? -1f : 1f; + vertex.tang4d = new Vector4f(vertex.tang.x, vertex.tang.y, vertex.tang.z, wCoord); + vertex.tang = null; + vertex.bitang = null; + } + } + + public static void toTangentsWithParity(IrMesh mesh) { + for (IrPolygon polygon : mesh.polygons) { + for (IrVertex vertex : polygon.vertices) { + toTangentsWithParity(vertex); + } + } + } + + private static void trimBoneWeights(IrVertex vertex) { + if (vertex.boneWeightsIndices == null) { + return; + } + + IrBoneWeightIndex[] boneWeightsIndices = vertex.boneWeightsIndices; + + if (boneWeightsIndices.length <= 4) { + return; + } + + // Sort by weight + boneWeightsIndices = Arrays.copyOf(boneWeightsIndices, boneWeightsIndices.length); + Arrays.sort(boneWeightsIndices); + + // Trim to four weights at most + boneWeightsIndices = Arrays.copyOf(boneWeightsIndices, 4); + + // Renormalize weights + float sum = 0; + + for (int i = 0; i < boneWeightsIndices.length; i++) { + sum += boneWeightsIndices[i].boneWeight; + } + + if (sum != 1f) { + float sumToB = sum == 0 ? 0 : 1f / sum; + for (int i = 0; i < boneWeightsIndices.length; i++) { + IrBoneWeightIndex original = boneWeightsIndices[i]; + boneWeightsIndices[i] = new IrBoneWeightIndex(original.boneIndex, original.boneWeight * sumToB); + } + } + + vertex.boneWeightsIndices = boneWeightsIndices; + } + + /** + * Removes low bone weights from mesh, leaving only 4 bone weights at max. + */ + public static void trimBoneWeights(IrMesh mesh) { + for (IrPolygon polygon : mesh.polygons) { + for (IrVertex vertex : polygon.vertices) { + trimBoneWeights(vertex); + } + } + } + + /** + * Convert mesh from quads / triangles to triangles only. + */ + public static void triangulate(IrMesh mesh) { + List newPolygons = new ArrayList(mesh.polygons.length); + for (IrPolygon inputPoly : mesh.polygons) { + if (inputPoly.vertices.length == 4) { + IrPolygon[] tris = quadToTri(inputPoly); + newPolygons.add(tris[0]); + newPolygons.add(tris[1]); + } else if (inputPoly.vertices.length == 3) { + newPolygons.add(inputPoly); + } else { + // N-gon. We have to ignore it.. + logger.log(Level.WARNING, "N-gon encountered, ignoring. " + + "The mesh may not appear correctly. " + + "Triangulate your model prior to export."); + } + } + mesh.polygons = new IrPolygon[newPolygons.size()]; + newPolygons.toArray(mesh.polygons); + } + + /** + * Separate mesh with multiple materials into multiple meshes each with + * one material each. + * + * Polygons without a material will be added to key = -1. + */ + public static IntMap splitByMaterial(IrMesh mesh) { + IntMap> materialToPolyList = new IntMap>(); + for (IrPolygon polygon : mesh.polygons) { + int materialIndex = -1; + for (IrVertex vertex : polygon.vertices) { + if (vertex.material == null) { + continue; + } + if (materialIndex == -1) { + materialIndex = vertex.material; + } else if (materialIndex != vertex.material) { + throw new UnsupportedOperationException("Multiple materials " + + "assigned to the same polygon"); + } + } + List polyList = materialToPolyList.get(materialIndex); + if (polyList == null) { + polyList = new ArrayList(); + materialToPolyList.put(materialIndex, polyList); + } + polyList.add(polygon); + } + IntMap materialToMesh = new IntMap(); + for (IntMap.Entry> entry : materialToPolyList) { + int key = entry.getKey(); + List polygons = entry.getValue(); + if (polygons.size() > 0) { + IrMesh newMesh = new IrMesh(); + newMesh.polygons = new IrPolygon[polygons.size()]; + polygons.toArray(newMesh.polygons); + materialToMesh.put(key, newMesh); + } + } + return materialToMesh; + } + + /** + * Convert IrMesh to jME3 mesh. + */ + public static Mesh convertIrMeshToJmeMesh(IrMesh mesh) { + Map vertexToVertexIndex = new HashMap(); + List vertices = new ArrayList(); + List indexes = new ArrayList(); + + int vertexIndex = 0; + for (IrPolygon polygon : mesh.polygons) { + if (polygon.vertices.length != 3) { + throw new UnsupportedOperationException("IrMesh must be triangulated first"); + } + for (IrVertex vertex : polygon.vertices) { + // Is this vertex already indexed? + Integer existingIndex = vertexToVertexIndex.get(vertex); + if (existingIndex == null) { + // Not indexed yet, allocate index. + indexes.add(vertexIndex); + vertexToVertexIndex.put(vertex, vertexIndex); + vertices.add(vertex); + vertexIndex++; + } else { + // Index already allocated for this vertex, reuse it. + indexes.add(existingIndex); + } + } + } + + Mesh jmeMesh = new Mesh(); + jmeMesh.setMode(Mesh.Mode.Triangles); + + FloatBuffer posBuf = null; + FloatBuffer normBuf = null; + FloatBuffer tangBuf = null; + FloatBuffer uv0Buf = null; + FloatBuffer uv1Buf = null; + ByteBuffer colorBuf = null; + ByteBuffer boneIndices = null; + FloatBuffer boneWeights = null; + IndexBuffer indexBuf = null; + + IrVertex inspectionVertex = vertices.get(0); + if (inspectionVertex.pos != null) { + posBuf = BufferUtils.createVector3Buffer(vertices.size()); + jmeMesh.setBuffer(VertexBuffer.Type.Position, 3, posBuf); + } + if (inspectionVertex.norm != null) { + normBuf = BufferUtils.createVector3Buffer(vertices.size()); + jmeMesh.setBuffer(VertexBuffer.Type.Normal, 3, normBuf); + } + if (inspectionVertex.tang4d != null) { + tangBuf = BufferUtils.createFloatBuffer(vertices.size() * 4); + jmeMesh.setBuffer(VertexBuffer.Type.Tangent, 4, tangBuf); + } + if (inspectionVertex.tang != null || inspectionVertex.bitang != null) { + throw new IllegalStateException("Mesh is using 3D tangents, must be converted to 4D tangents first."); + } + if (inspectionVertex.uv0 != null) { + uv0Buf = BufferUtils.createVector2Buffer(vertices.size()); + jmeMesh.setBuffer(VertexBuffer.Type.TexCoord, 2, uv0Buf); + } + if (inspectionVertex.uv1 != null) { + uv1Buf = BufferUtils.createVector2Buffer(vertices.size()); + jmeMesh.setBuffer(VertexBuffer.Type.TexCoord2, 2, uv1Buf); + } + if (inspectionVertex.color != null) { + colorBuf = BufferUtils.createByteBuffer(vertices.size() * 4); + jmeMesh.setBuffer(VertexBuffer.Type.Color, 4, colorBuf); + jmeMesh.getBuffer(VertexBuffer.Type.Color).setNormalized(true); + } + if (inspectionVertex.boneWeightsIndices != null) { + boneIndices = BufferUtils.createByteBuffer(vertices.size() * 4); + boneWeights = BufferUtils.createFloatBuffer(vertices.size() * 4); + jmeMesh.setBuffer(VertexBuffer.Type.BoneIndex, 4, boneIndices); + jmeMesh.setBuffer(VertexBuffer.Type.BoneWeight, 4, boneWeights); + + //creating empty buffers for HW skinning + //the buffers will be setup if ever used. + VertexBuffer weightsHW = new VertexBuffer(VertexBuffer.Type.HWBoneWeight); + VertexBuffer indicesHW = new VertexBuffer(VertexBuffer.Type.HWBoneIndex); + //setting usage to cpuOnly so that the buffer is not send empty to the GPU + indicesHW.setUsage(VertexBuffer.Usage.CpuOnly); + weightsHW.setUsage(VertexBuffer.Usage.CpuOnly); + + jmeMesh.setBuffer(weightsHW); + jmeMesh.setBuffer(indicesHW); + } + if (vertices.size() >= 65536) { + // too many verticies: use intbuffer instead of shortbuffer + IntBuffer ib = BufferUtils.createIntBuffer(indexes.size()); + jmeMesh.setBuffer(VertexBuffer.Type.Index, 3, ib); + indexBuf = new IndexIntBuffer(ib); + } else { + ShortBuffer sb = BufferUtils.createShortBuffer(indexes.size()); + jmeMesh.setBuffer(VertexBuffer.Type.Index, 3, sb); + indexBuf = new IndexShortBuffer(sb); + } + + jmeMesh.setStatic(); + + int maxBonesPerVertex = -1; + + for (IrVertex vertex : vertices) { + if (posBuf != null) { + posBuf.put(vertex.pos.x).put(vertex.pos.y).put(vertex.pos.z); + } + if (normBuf != null) { + normBuf.put(vertex.norm.x).put(vertex.norm.y).put(vertex.norm.z); + } + if (tangBuf != null) { + tangBuf.put(vertex.tang4d.x).put(vertex.tang4d.y).put(vertex.tang4d.z).put(vertex.tang4d.w); + } + if (uv0Buf != null) { + uv0Buf.put(vertex.uv0.x).put(vertex.uv0.y); + } + if (uv1Buf != null) { + uv1Buf.put(vertex.uv1.x).put(vertex.uv1.y); + } + if (colorBuf != null) { + colorBuf.putInt(vertex.color.asIntABGR()); + } + if (boneIndices != null) { + if (vertex.boneWeightsIndices != null) { + if (vertex.boneWeightsIndices.length > 4) { + throw new UnsupportedOperationException("Mesh uses more than 4 weights per bone. " + + "Call trimBoneWeights() to allieviate this"); + } + for (int i = 0; i < vertex.boneWeightsIndices.length; i++) { + boneIndices.put((byte) (vertex.boneWeightsIndices[i].boneIndex & 0xFF)); + boneWeights.put(vertex.boneWeightsIndices[i].boneWeight); + } + for (int i = 0; i < 4 - vertex.boneWeightsIndices.length; i++) { + boneIndices.put((byte)0); + boneWeights.put(0f); + } + } else { + boneIndices.putInt(0); + boneWeights.put(0f).put(0f).put(0f).put(0f); + } + + maxBonesPerVertex = Math.max(maxBonesPerVertex, vertex.boneWeightsIndices.length); + } + } + + for (int i = 0; i < indexes.size(); i++) { + indexBuf.put(i, indexes.get(i)); + } + + jmeMesh.updateCounts(); + jmeMesh.updateBound(); + + if (boneIndices != null) { + jmeMesh.setMaxNumWeights(maxBonesPerVertex); + jmeMesh.prepareForAnim(true); + jmeMesh.generateBindPose(true); + } + + return jmeMesh; + } +} diff --git a/jme3-plugins/src/main/java/com/jme3/scene/plugins/IrVertex.java b/jme3-plugins/src/main/java/com/jme3/scene/plugins/IrVertex.java new file mode 100644 index 000000000..5870846a1 --- /dev/null +++ b/jme3-plugins/src/main/java/com/jme3/scene/plugins/IrVertex.java @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2009-2015 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.scene.plugins; + +import com.jme3.math.ColorRGBA; +import com.jme3.math.Vector2f; +import com.jme3.math.Vector3f; +import com.jme3.math.Vector4f; +import java.util.Arrays; + +public class IrVertex implements Cloneable { + + public Vector3f pos; + public Vector3f norm; + public Vector4f tang4d; + public Vector3f tang; + public Vector3f bitang; + public Vector2f uv0; + public Vector2f uv1; + public ColorRGBA color; + public Integer material; + public Integer smoothing; + public IrBoneWeightIndex[] boneWeightsIndices; + + public IrVertex deepClone() { + IrVertex v = new IrVertex(); + v.pos = pos != null ? pos.clone() : null; + v.norm = norm != null ? norm.clone() : null; + v.tang4d = tang4d != null ? tang4d.clone() : null; + v.tang = tang != null ? tang.clone() : null; + v.bitang = bitang != null ? bitang.clone() : null; + v.uv0 = uv0 != null ? uv0.clone() : null; + v.uv1 = uv1 != null ? uv1.clone() : null; + v.color = color != null ? color.clone() : null; + v.material = material; + v.smoothing = smoothing; + if (boneWeightsIndices != null) { + v.boneWeightsIndices = new IrBoneWeightIndex[boneWeightsIndices.length]; + for (int i = 0; i < boneWeightsIndices.length; i++) { + v.boneWeightsIndices[i] = (IrBoneWeightIndex) boneWeightsIndices[i].clone(); + } + } + return v; + } + + @Override + public int hashCode() { + int hash = 5; + hash = 73 * hash + (this.pos != null ? this.pos.hashCode() : 0); + hash = 73 * hash + (this.norm != null ? this.norm.hashCode() : 0); + hash = 73 * hash + (this.tang4d != null ? this.tang4d.hashCode() : 0); + hash = 73 * hash + (this.tang != null ? this.tang.hashCode() : 0); + hash = 73 * hash + (this.uv0 != null ? this.uv0.hashCode() : 0); + hash = 73 * hash + (this.uv1 != null ? this.uv1.hashCode() : 0); + hash = 73 * hash + (this.color != null ? this.color.hashCode() : 0); + hash = 73 * hash + (this.material != null ? this.material.hashCode() : 0); + hash = 73 * hash + (this.smoothing != null ? this.smoothing.hashCode() : 0); + hash = 73 * hash + Arrays.deepHashCode(this.boneWeightsIndices); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final IrVertex other = (IrVertex) obj; + if (this.pos != other.pos && (this.pos == null || !this.pos.equals(other.pos))) { + return false; + } + if (this.norm != other.norm && (this.norm == null || !this.norm.equals(other.norm))) { + return false; + } + if (this.tang4d != other.tang4d && (this.tang4d == null || !this.tang4d.equals(other.tang4d))) { + return false; + } + if (this.tang != other.tang && (this.tang == null || !this.tang.equals(other.tang))) { + return false; + } + if (this.uv0 != other.uv0 && (this.uv0 == null || !this.uv0.equals(other.uv0))) { + return false; + } + if (this.uv1 != other.uv1 && (this.uv1 == null || !this.uv1.equals(other.uv1))) { + return false; + } + if (this.color != other.color && (this.color == null || !this.color.equals(other.color))) { + return false; + } + if (this.material != other.material && (this.material == null || !this.material.equals(other.material))) { + return false; + } + if (this.smoothing != other.smoothing && (this.smoothing == null || !this.smoothing.equals(other.smoothing))) { + return false; + } + if (!Arrays.deepEquals(this.boneWeightsIndices, other.boneWeightsIndices)) { + return false; + } + return true; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("Vertex { "); + + if (pos != null) { + sb.append("pos=").append(pos).append(", "); + } + if (norm != null) { + sb.append("norm=").append(pos).append(", "); + } + if (tang != null) { + sb.append("tang=").append(pos).append(", "); + } + if (uv0 != null) { + sb.append("uv0=").append(pos).append(", "); + } + if (uv1 != null) { + sb.append("uv1=").append(pos).append(", "); + } + if (color != null) { + sb.append("color=").append(pos).append(", "); + } + if (material != null) { + sb.append("material=").append(pos).append(", "); + } + if (smoothing != null) { + sb.append("smoothing=").append(pos).append(", "); + } + + if (sb.toString().endsWith(", ")) { + sb.delete(sb.length() - 2, sb.length()); + } + + sb.append(" }"); + return sb.toString(); + } +} diff --git a/jme3-plugins/src/xml/java/com/jme3/export/xml/XMLExporter.java b/jme3-plugins/src/xml/java/com/jme3/export/xml/XMLExporter.java index 32138270d..0ede52884 100644 --- a/jme3-plugins/src/xml/java/com/jme3/export/xml/XMLExporter.java +++ b/jme3-plugins/src/xml/java/com/jme3/export/xml/XMLExporter.java @@ -40,6 +40,7 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; /** * Part of the jME XML IO system as introduced in the google code jmexml project. @@ -61,7 +62,8 @@ public class XMLExporter implements JmeExporter { } - public boolean save(Savable object, OutputStream f) throws IOException { + @Override + public void save(Savable object, OutputStream f) throws IOException { try { //Initialize Document when saving so we don't retain state of previous exports this.domOut = new DOMOutputCapsule(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(), this); @@ -69,18 +71,22 @@ public class XMLExporter implements JmeExporter { DOMSerializer serializer = new DOMSerializer(); serializer.serialize(domOut.getDoc(), f); f.flush(); - return true; - } catch (Exception ex) { - IOException e = new IOException(); - e.initCause(ex); - throw e; + } catch (ParserConfigurationException ex) { + throw new IOException(ex); } } - public boolean save(Savable object, File f) throws IOException { - return save(object, new FileOutputStream(f)); + @Override + public void save(Savable object, File f) throws IOException { + FileOutputStream fos = new FileOutputStream(f); + try { + save(object, fos); + } finally { + fos.close(); + } } + @Override public OutputCapsule getCapsule(Savable object) { return domOut; } diff --git a/jme3-terrain/src/main/java/com/jme3/terrain/geomipmap/TerrainLodControl.java b/jme3-terrain/src/main/java/com/jme3/terrain/geomipmap/TerrainLodControl.java index f52eaee01..8ad2425ad 100644 --- a/jme3-terrain/src/main/java/com/jme3/terrain/geomipmap/TerrainLodControl.java +++ b/jme3-terrain/src/main/java/com/jme3/terrain/geomipmap/TerrainLodControl.java @@ -137,7 +137,7 @@ public class TerrainLodControl extends AbstractControl { return Executors.newSingleThreadExecutor(new ThreadFactory() { public Thread newThread(Runnable r) { Thread th = new Thread(r); - th.setName("jME Terrain Thread"); + th.setName("jME3 Terrain Thread"); th.setDaemon(true); return th; } diff --git a/jme3-testdata/build.gradle b/jme3-testdata/build.gradle index 1df94c4d2..aad9f2ae9 100644 --- a/jme3-testdata/build.gradle +++ b/jme3-testdata/build.gradle @@ -2,5 +2,12 @@ if (!hasProperty('mainClass')) { ext.mainClass = '' } +repositories { + maven { + url 'http://nifty-gui.sourceforge.net/nifty-maven-repo' + } +} + dependencies { + compile 'lessvoid:nifty-examples:1.4.1' } diff --git a/jme3-testdata/src/main/resources/Textures/Terrain/BrickWall/BrickWall.j3m b/jme3-testdata/src/main/resources/Textures/Terrain/BrickWall/BrickWall.j3m index 8b54f9e39..41af10431 100644 --- a/jme3-testdata/src/main/resources/Textures/Terrain/BrickWall/BrickWall.j3m +++ b/jme3-testdata/src/main/resources/Textures/Terrain/BrickWall/BrickWall.j3m @@ -1,8 +1,7 @@ Material Pong Rock : Common/MatDefs/Light/Lighting.j3md { MaterialParameters { Shininess: 2.0 - DiffuseMap : Textures/Terrain/BrickWall/BrickWall.jpg - NormalMap : Textures/Terrain/BrickWall/BrickWall_normal.jpg - ParallaxMap : Textures/Terrain/BrickWall/BrickWall_height.jpg + DiffuseMap : Repeat Textures/Terrain/BrickWall/BrickWall.jpg + ParallaxMap : Repeat Textures/Terrain/BrickWall/BrickWall_height.jpg } } \ No newline at end of file diff --git a/jme3-testdata/src/main/resources/Textures/Terrain/BrickWall/BrickWall2.j3m b/jme3-testdata/src/main/resources/Textures/Terrain/BrickWall/BrickWall2.j3m index 7db3ab893..8f90a9454 100644 --- a/jme3-testdata/src/main/resources/Textures/Terrain/BrickWall/BrickWall2.j3m +++ b/jme3-testdata/src/main/resources/Textures/Terrain/BrickWall/BrickWall2.j3m @@ -1,8 +1,8 @@ Material Pong Rock : Common/MatDefs/Light/Lighting.j3md { MaterialParameters { Shininess: 2.0 - DiffuseMap : Textures/Terrain/BrickWall/BrickWall.jpg - NormalMap : Textures/Terrain/BrickWall/BrickWall_normal_parallax.dds + DiffuseMap : Repeat Textures/Terrain/BrickWall/BrickWall.jpg + NormalMap : Repeat Textures/Terrain/BrickWall/BrickWall_normal_parallax.dds PackedNormalParallax: true } } \ No newline at end of file diff --git a/local.properties b/local.properties new file mode 100644 index 000000000..27e823fff --- /dev/null +++ b/local.properties @@ -0,0 +1 @@ +sdk.dir=C:\\AndroidSDK \ No newline at end of file diff --git a/sdk/build.gradle b/sdk/build.gradle index 55722cbfb..b70e80b13 100644 --- a/sdk/build.gradle +++ b/sdk/build.gradle @@ -25,17 +25,18 @@ dependencies { corelibs project(':jme3-niftygui') corelibs project(':jme3-plugins') corelibs project(':jme3-terrain') - + optlibs project(':jme3-bullet') optlibs project(':jme3-jogl') optlibs project(':jme3-android') optlibs project(':jme3-ios') optlibs project(':jme3-android-native') optlibs project(':jme3-bullet-native') + optlibs project(':jme3-bullet-native-android') testdatalibs project(':jme3-testdata') examplelibs project(':jme3-examples') - + } artifacts { @@ -47,7 +48,7 @@ task checkPlatformConfig { def platformFile = file("nbproject/private/platform-private.properties") if(!platformFile.exists()){ def netbeansFolder = file("../netbeans") - if(!netbeansFolder.exists()){ + if(!netbeansFolder.exists() || netbeansFolder.list().length == 0){ println "Downloading NetBeans Platform base, this only has to be done once.." def f = file("netbeans.zip") new URL(netbeansUrl).withInputStream{ i -> f.withOutputStream{ it << i }} @@ -97,7 +98,7 @@ task createBaseXml(dependsOn: configurations.corelibs) <<{ "jme3-core-baselibs and jme3-core-libraries" def jmeJarFiles = [] // jme3 jar files def externalJarFiles = [] // external jar files - + // collect jar files project.configurations.corelibs.dependencies.each {dep -> // collect external jar files @@ -120,7 +121,7 @@ task createBaseXml(dependsOn: configurations.corelibs) <<{ def packages = [] jmeJarFiles.each{jarFile -> ZipFile file = new ZipFile(jarFile) - file.entries().each { entry -> + file.entries().each { entry -> if(entry.name.endsWith('.class')){ // TODO: "/" works on windows? def pathPart = entry.name.substring(0,entry.name.lastIndexOf('/')) @@ -129,14 +130,14 @@ task createBaseXml(dependsOn: configurations.corelibs) <<{ packages.add(classPath) } } - } + } } - + // collect library packages def extPackages = [] externalJarFiles.each{jarFile -> ZipFile file = new ZipFile(jarFile) - file.entries().each { entry -> + file.entries().each { entry -> if(entry.name.endsWith('.class')){ // TODO: "/" works on windows? def pathPart = entry.name.substring(0,entry.name.lastIndexOf('/')) @@ -145,9 +146,9 @@ task createBaseXml(dependsOn: configurations.corelibs) <<{ extPackages.add(classPath) } } - } + } } - + def writer = new StringWriter() def xml = new MarkupBuilder(writer) xml.mkp.xmlDeclaration(version:'1.0') @@ -252,7 +253,7 @@ task copyProjectLibs(dependsOn: [configurations.corelibs, configurations.testdat into "jme3-project-libraries/release/libs/" } } - + project.configurations.testdatalibs.dependencies.each {dep -> // copy jme3 test data to jme3-project-testdata dep.dependencyProject.configurations.archives.allArtifacts.each{ artifact-> @@ -281,10 +282,10 @@ def makeFile(builder, nameR) { builder.file(name:nameR, url:nameR) } task createProjectXml(dependsOn: configurations.corelibs) <<{ description "Creates needed J2SE library and layer XML files in jme3-project-baselibs" - - def eol = System.properties.'line.separator' + + def eol = System.properties.'line.separator' def j2seLibraries = [] // created J2SE library descriptors - + // for each dependency in corelibs.. def deps = [] deps.addAll(project.configurations.corelibs.dependencies) @@ -315,7 +316,7 @@ task createProjectXml(dependsOn: configurations.corelibs) <<{ def libraryWriter = new StringWriter() def libraryXml = new MarkupBuilder(libraryWriter) // xml.mkp.xmlDeclaration(version:'1.0') - libraryWriter << '' << eol + libraryWriter << '' << eol libraryWriter << '' << eol libraryXml.library(version:"1.0", encoding: "UTF-8"){ makeName(libraryXml, "${dep.dependencyProject.name}") @@ -352,7 +353,7 @@ task createProjectXml(dependsOn: configurations.corelibs) <<{ def layerWriter = new StringWriter() def layerXml = new MarkupBuilder(layerWriter) // layerXml.mkp.xmlDeclaration(version:'1.0') - layerWriter << '' << eol + layerWriter << '' << eol layerWriter << '' << eol layerXml.filesystem{ folder(name:"org-netbeans-api-project-libraries"){ diff --git a/sdk/jme3-android/src/com/jme3/gde/android/AndroidImportantFiles.java b/sdk/jme3-android/src/com/jme3/gde/android/AndroidImportantFiles.java index cbfb487cc..b96bb769c 100644 --- a/sdk/jme3-android/src/com/jme3/gde/android/AndroidImportantFiles.java +++ b/sdk/jme3-android/src/com/jme3/gde/android/AndroidImportantFiles.java @@ -67,6 +67,18 @@ public class AndroidImportantFiles implements ImportantFiles { node.setDisplayName("Android Properties"); list.add(node); } + FileObject layout = project.getProjectDirectory().getFileObject("mobile/res/layout/main.xml"); + if (layout != null) { + Node node = DataObject.find(layout).getNodeDelegate(); + node.setDisplayName("Android Layout"); + list.add(node); + } + FileObject strings = project.getProjectDirectory().getFileObject("mobile/res/values/strings.xml"); + if (strings != null) { + Node node = DataObject.find(strings).getNodeDelegate(); + node.setDisplayName("Android Strings"); + list.add(node); + } } catch (DataObjectNotFoundException ex) { Exceptions.printStackTrace(ex); } diff --git a/sdk/jme3-android/src/com/jme3/gde/android/AndroidSdkTool.java b/sdk/jme3-android/src/com/jme3/gde/android/AndroidSdkTool.java index b93b089cc..21340ab6e 100644 --- a/sdk/jme3-android/src/com/jme3/gde/android/AndroidSdkTool.java +++ b/sdk/jme3-android/src/com/jme3/gde/android/AndroidSdkTool.java @@ -243,6 +243,7 @@ public class AndroidSdkTool { } updateAndroidManifest(project); updateAndroidApplicationName(project, name); + updateAndroidLayout(project, packag); } public static void updateProject(Project project, String target, String name) { @@ -299,17 +300,15 @@ public class AndroidSdkTool { changed = true; } } - // add the following after AndroidHarness.screenOrientation is depreciated - // for jME 3.1 -// if (sdkActivity != null) { -// if (sdkActivity.hasAttribute("android:screenOrientation")) { -// String attrScreenOrientation = sdkActivity.getAttribute("android:screenOrientation"); -// } else { -// Logger.getLogger(AndroidSdkTool.class.getName()).log(Level.INFO, "creating attrScreenOrientation"); -// sdkActivity.setAttribute("android:screenOrientation", "landscape"); -// changed = true; -// } -// } + if (sdkActivity != null) { + if (sdkActivity.hasAttribute("android:screenOrientation")) { + String attrScreenOrientation = sdkActivity.getAttribute("android:screenOrientation"); + } else { + Logger.getLogger(AndroidSdkTool.class.getName()).log(Level.INFO, "creating attrScreenOrientation"); + sdkActivity.setAttribute("android:screenOrientation", "landscape"); + changed = true; + } + } } Element sdkElement = XmlHelper.findChildElement(configuration.getDocumentElement(), "uses-sdk"); @@ -319,7 +318,7 @@ public class AndroidSdkTool { changed = true; } if (!"8".equals(sdkElement.getAttribute("android:minSdkVersion"))) { - sdkElement.setAttribute("android:minSdkVersion", "8"); + sdkElement.setAttribute("android:minSdkVersion", "9"); changed = true; } Element screensElement = XmlHelper.findChildElement(configuration.getDocumentElement(), "supports-screens"); @@ -413,18 +412,79 @@ public class AndroidSdkTool { } } + private static void updateAndroidLayout(Project project, String packag) { + FileObject layout = project.getProjectDirectory().getFileObject("mobile/res/layout/main.xml"); + if (layout == null) { + Logger.getLogger(AndroidSdkTool.class.getName()).log(Level.WARNING, "Cannot find layout"); + return; + } + InputStream in = null; + FileLock lock = null; + OutputStream out = null; + try { + in = layout.getInputStream(); + Document configuration = XMLUtil.parse(new InputSource(in), false, false, null, null); + in.close(); + in = null; + + Element textViewElement = XmlHelper.findChildElement(configuration.getDocumentElement(), "TextView"); + + Element fragmentElement = configuration.createElement("fragment"); + fragmentElement.setAttribute("android:name", packag+".MainActivity$JmeFragment"); + fragmentElement.setAttribute("android:id", "@+id/jmeFragment"); + fragmentElement.setAttribute("android:layout_width", "match_parent"); + fragmentElement.setAttribute("android:layout_height", "match_parent"); + + if (textViewElement == null) { + configuration.getDocumentElement().appendChild(fragmentElement); + } else { + configuration.getDocumentElement().replaceChild(fragmentElement, textViewElement); + } + + lock = layout.lock(); + out = layout.getOutputStream(lock); + XMLUtil.write(configuration, out, "UTF-8"); + out.close(); + out = null; + lock.releaseLock(); + lock = null; + + } catch (SAXException ex) { + Exceptions.printStackTrace(ex); + } catch (IOException ex) { + Exceptions.printStackTrace(ex); + } finally { + if (lock != null) { + lock.releaseLock(); + } + try { + if (in != null) { + in.close(); + } + if (out != null) { + out.close(); + } + } catch (IOException ex1) { + Exceptions.printStackTrace(ex1); + } + } + } + private static String mainActivityString(String mainClass, String packag) { String str = "package " + packag + ";\n" + " \n" - + "import android.content.pm.ActivityInfo;\n" - + "import com.jme3.app.AndroidHarness;\n" - + "import com.jme3.system.android.AndroidConfigChooser.ConfigType;\n" + + "import com.jme3.app.DefaultAndroidProfiler;\n" + + "import android.app.Activity;\n" + + "import android.app.FragmentManager;\n" + + "import android.os.Bundle;\n" + + "import android.view.Window;\n" + + "import android.view.WindowManager;\n" + + "import com.jme3.app.AndroidHarnessFragment;\n" + "import java.util.logging.Level;\n" + "import java.util.logging.LogManager;\n" + " \n" - + "public class MainActivity extends AndroidHarness{\n" - + " \n" + + "public class MainActivity extends Activity {\n" + " /*\n" + " * Note that you can ignore the errors displayed in this file,\n" + " * the android project will build regardless.\n" @@ -433,24 +493,72 @@ public class AndroidSdkTool { + " */\n" + " \n" + " public MainActivity(){\n" - + " // Set the application class to run\n" - + " appClass = \"" + mainClass + "\";\n" - + " // Try ConfigType.FASTEST; or ConfigType.LEGACY if you have problems\n" - + " eglConfigType = ConfigType.BEST;\n" - + " // Exit Dialog title & message\n" - + " exitDialogTitle = \"Exit?\";\n" - + " exitDialogMessage = \"Press Yes\";\n" - + " // Enable verbose logging\n" - + " eglConfigVerboseLogging = false;\n" - + " // Choose screen orientation\n" - + " screenOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;\n" - + " // Enable MouseEvents being generated from TouchEvents (default = true)\n" - + " mouseEventsEnabled = true;\n" + " // Set the default logging level (default=Level.INFO, Level.ALL=All Debug Info)\n" + " LogManager.getLogManager().getLogger(\"\").setLevel(Level.INFO);\n" + " }\n" + " \n" + + " @Override\n" + + " protected void onCreate(Bundle savedInstanceState) {\n" + + " super.onCreate(savedInstanceState);\n" + + " // Set window fullscreen and remove title bar\n" + + " requestWindowFeature(Window.FEATURE_NO_TITLE);\n" + + " getWindow().setFlags(\n" + + " WindowManager.LayoutParams.FLAG_FULLSCREEN,\n" + + " WindowManager.LayoutParams.FLAG_FULLSCREEN);\n" + + " setContentView(R.layout.main);\n" + + " \n" + + " // find the fragment\n" + + " FragmentManager fm = getFragmentManager();\n" + + " AndroidHarnessFragment jmeFragment =\n" + + " (AndroidHarnessFragment) fm.findFragmentById(R.id.jmeFragment);\n" + + " \n" + + " // uncomment the next line to add the default android profiler to the project\n" + + " //jmeFragment.getJmeApplication().setAppProfiler(new DefaultAndroidProfiler());\n" + + " }\n" + + " \n" + + " \n" + + " public static class JmeFragment extends AndroidHarnessFragment {\n" + + " public JmeFragment() {\n" + + " // Set main project class (fully qualified path)\n" + + " appClass = \"" + mainClass + "\";\n" + + " \n" + + " // Set the desired EGL configuration\n" + + " eglBitsPerPixel = 24;\n" + + " eglAlphaBits = 0;\n" + + " eglDepthBits = 16;\n" + + " eglSamples = 0;\n" + + " eglStencilBits = 0;\n" + + " \n" + + " // Set the maximum framerate\n" + + " // (default = -1 for unlimited)\n" + + " frameRate = -1;\n" + + " \n" + + " // Set the maximum resolution dimension\n" + + " // (the smaller side, height or width, is set automatically\n" + + " // to maintain the original device screen aspect ratio)\n" + + " // (default = -1 to match device screen resolution)\n" + + " maxResolutionDimension = -1;\n" + + " \n" + + " // Set input configuration settings\n" + + " joystickEventsEnabled = false;\n" + + " keyEventsEnabled = true;\n" + + " mouseEventsEnabled = true;\n" + + " \n" + + " // Set application exit settings\n" + + " finishOnAppStop = true;\n" + + " handleExitHook = true;\n" + + " exitDialogTitle = \"Do you want to exit?\";\n" + + " exitDialogMessage = \"Use your home key to bring this app into the background or exit to terminate it.\";\n" + + " \n" + + " // Set splash screen resource id, if used\n" + + " // (default = 0, no splash screen)\n" + + " // For example, if the image file name is \"splash\"...\n" + + " // splashPicID = R.drawable.splash;\n" + + " splashPicID = 0;\n" + + " }\n" + + " }\n" + "}\n"; + return str; } diff --git a/sdk/jme3-android/src/com/jme3/gde/android/mobile-targets.xml b/sdk/jme3-android/src/com/jme3/gde/android/mobile-targets.xml index 437500ba6..2a302ee57 100644 --- a/sdk/jme3-android/src/com/jme3/gde/android/mobile-targets.xml +++ b/sdk/jme3-android/src/com/jme3/gde/android/mobile-targets.xml @@ -29,58 +29,58 @@ - + - - + - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + Adding libraries for android. - + + + + - - Replacing bullet library with android native version. - - - - - + + Replacing bullet library with android native bullet version. + + + + + - - - - - - - @@ -91,25 +91,9 @@ - - Adding OpenAL Soft - - - - - - - - - - - - - - - + diff --git a/sdk/jme3-materialeditor/src/com/jme3/gde/materials/EditableMaterialFile.java b/sdk/jme3-materialeditor/src/com/jme3/gde/materials/EditableMaterialFile.java index 4c718c7a2..9b5cf611c 100644 --- a/sdk/jme3-materialeditor/src/com/jme3/gde/materials/EditableMaterialFile.java +++ b/sdk/jme3-materialeditor/src/com/jme3/gde/materials/EditableMaterialFile.java @@ -532,7 +532,7 @@ public class EditableMaterialFile { //TODO: seems like flip is removed due to ImageToAwt texKey.setFlipY(false); Texture texture = manager.loadTexture(texKey); - MatParamTexture newParam = new MatParamTexture(texParam.getVarType(), texParam.getName(), texture, texParam.getUnit()); + MatParamTexture newParam = new MatParamTexture(texParam.getVarType(), texParam.getName(), texture, texParam.getUnit(), null); materialParameters.put(newParam.getName(), new MaterialProperty(newParam)); } catch (Exception ex) { Exceptions.printStackTrace(ex); diff --git a/sdk/jme3-materialeditor/src/com/jme3/gde/shadernodedefinition/wizard/SNDefWizardIterator.java b/sdk/jme3-materialeditor/src/com/jme3/gde/shadernodedefinition/wizard/SNDefWizardIterator.java index 0fdabe192..6ced1f1f9 100644 --- a/sdk/jme3-materialeditor/src/com/jme3/gde/shadernodedefinition/wizard/SNDefWizardIterator.java +++ b/sdk/jme3-materialeditor/src/com/jme3/gde/shadernodedefinition/wizard/SNDefWizardIterator.java @@ -102,7 +102,7 @@ public final class SNDefWizardIterator implements WizardDescriptor.Instantiating //Get the template and convert it: FileObject tplSnd = Templates.getTemplate(wizard); - FileObject tplShd = tplSnd.getParent().getChildren()[1]; + FileObject tplShd = tplSnd.getParent().getChildren()[0]; DataObject templateSnd = DataObject.find(tplSnd); DataObject templateShd = DataObject.find(tplShd); diff --git a/sdk/jme3-model-importer/src/com/jme3/gde/modelimporter/ImportModel.java b/sdk/jme3-model-importer/src/com/jme3/gde/modelimporter/ImportModel.java index 1f3f57bf8..07b129628 100644 --- a/sdk/jme3-model-importer/src/com/jme3/gde/modelimporter/ImportModel.java +++ b/sdk/jme3-model-importer/src/com/jme3/gde/modelimporter/ImportModel.java @@ -212,6 +212,7 @@ public final class ImportModel implements ActionListener { } replaceLocatedTextures(spat, manager); targetData.saveAsset(); + targetData.closeAsset(); ((SpatialAssetDataObject) targetModel).getLookupContents().remove(tempProjectManager); } } catch (Exception ex) { diff --git a/sdk/jme3-model-importer/src/com/jme3/gde/modelimporter/ModelImporterVisualPanel3.java b/sdk/jme3-model-importer/src/com/jme3/gde/modelimporter/ModelImporterVisualPanel3.java index f7eeb57fa..51c0578e3 100644 --- a/sdk/jme3-model-importer/src/com/jme3/gde/modelimporter/ModelImporterVisualPanel3.java +++ b/sdk/jme3-model-importer/src/com/jme3/gde/modelimporter/ModelImporterVisualPanel3.java @@ -126,6 +126,7 @@ public final class ModelImporterVisualPanel3 extends JPanel { DialogDisplayer.getDefault().notifyLater(msg); Exceptions.printStackTrace(e); } + data.closeAsset(); manager.unregisterLocator(manager.getAssetFolderName(), UberAssetLocator.class); panel.fireChangeEvent(); } diff --git a/sdk/jme3-project-baselibs/src/com/jme3/gde/project/baselibs/jme3-android.xml b/sdk/jme3-project-baselibs/src/com/jme3/gde/project/baselibs/jme3-android.xml index 801e5bb3b..d937b98a9 100644 --- a/sdk/jme3-project-baselibs/src/com/jme3/gde/project/baselibs/jme3-android.xml +++ b/sdk/jme3-project-baselibs/src/com/jme3/gde/project/baselibs/jme3-android.xml @@ -7,7 +7,6 @@ classpath jar:nbinst://com.jme3.gde.project.baselibs/libs/jme3-android-3.1.0-snapshot-github.jar!/ - jar:nbinst://com.jme3.gde.project.libraries/libs/android.jar!/ src diff --git a/sdk/jme3-project-baselibs/src/com/jme3/gde/project/baselibs/jme3-bullet-native-android.xml b/sdk/jme3-project-baselibs/src/com/jme3/gde/project/baselibs/jme3-bullet-native-android.xml new file mode 100644 index 000000000..083970e02 --- /dev/null +++ b/sdk/jme3-project-baselibs/src/com/jme3/gde/project/baselibs/jme3-bullet-native-android.xml @@ -0,0 +1,19 @@ + + + + jme3-bullet-native-android + j2se + com.jme3.gde.project.baselibs.Bundle + + classpath + jar:nbinst://com.jme3.gde.project.baselibs/libs/jme3-bullet-native-android-3.1.0-snapshot-github.jar!/ + + + src + jar:nbinst://com.jme3.gde.project.baselibs/libs/jme3-bullet-native-android-3.1.0-snapshot-github-sources.jar!/ + + + javadoc + jar:nbinst://com.jme3.gde.project.baselibs/libs/jme3-bullet-native-android-3.1.0-snapshot-github-javadoc.jar!/ + + \ No newline at end of file diff --git a/sdk/jme3-project-baselibs/src/com/jme3/gde/project/baselibs/layer.xml b/sdk/jme3-project-baselibs/src/com/jme3/gde/project/baselibs/layer.xml index 1a7e7bf0e..837ff7e16 100644 --- a/sdk/jme3-project-baselibs/src/com/jme3/gde/project/baselibs/layer.xml +++ b/sdk/jme3-project-baselibs/src/com/jme3/gde/project/baselibs/layer.xml @@ -20,6 +20,7 @@ + \ No newline at end of file diff --git a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/Bundle.properties b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/Bundle.properties index 86f1414f9..43469051d 100644 --- a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/Bundle.properties +++ b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/Bundle.properties @@ -44,8 +44,8 @@ SceneComposerTopComponent.scaleButton.text= SceneComposerTopComponent.selectButton.text= SceneComposerTopComponent.selectButton.toolTipText=Select SceneComposerTopComponent.moveButton.toolTipText=Move -SceneComposerTopComponent.rotateButton.toolTipText=Rotate (in-development) -SceneComposerTopComponent.scaleButton.toolTipText=Scale (in-development) +SceneComposerTopComponent.rotateButton.toolTipText=Rotate +SceneComposerTopComponent.scaleButton.toolTipText=Scale SceneComposerTopComponent.sceneInfoPanel.border.title=no scene loaded SceneComposerTopComponent.jLabel5.text=Effects : SceneComposerTopComponent.emitButton.toolTipText=Emit all particles of all particle emitters from the selected Node @@ -63,3 +63,5 @@ SceneComposerTopComponent.jToggleScene.toolTipText=Snap to Scene SceneComposerTopComponent.jToggleGrid.toolTipText=Snap to Grid SceneComposerTopComponent.jToggleSelectGeom.toolTipText=Select Geometries SceneComposerTopComponent.jToggleSelectTerrain.toolTipText=Select Terrain +SceneComposerTopComponent.scaleButton.AccessibleContext.accessibleDescription=Scale +SceneComposerTopComponent.transformationTypeComboBox.toolTipText=Choose the transformation type used by tools. diff --git a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/ComposerCameraController.java b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/ComposerCameraController.java index c16933f80..c1689b833 100644 --- a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/ComposerCameraController.java +++ b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/ComposerCameraController.java @@ -79,26 +79,24 @@ public class ComposerCameraController extends AbstractCameraController { @Override public void checkClick(int button, boolean pressed) { - if (button == 0) { - if (isEditButtonEnabled() && !forceCameraControls) { + if (!forceCameraControls || !pressed) { // dont call toolController while forceCam but on button release (for UndoRedo) + if (button == 0) { toolController.doEditToolActivatedPrimary(new Vector2f(mouseX, mouseY), pressed, cam); } - } - if (button == 1) { - if (isEditButtonEnabled() && !forceCameraControls) { + if (button == 1) { toolController.doEditToolActivatedSecondary(new Vector2f(mouseX, mouseY), pressed, cam); } } - - } @Override protected void checkDragged(int button, boolean pressed) { - if (button == 0) { - toolController.doEditToolDraggedPrimary(new Vector2f(mouseX, mouseY), pressed, cam); - } else if (button == 1) { - toolController.doEditToolDraggedSecondary(new Vector2f(mouseX, mouseY), pressed, cam); + if (!forceCameraControls || !pressed) { + if (button == 0) { + toolController.doEditToolDraggedPrimary(new Vector2f(mouseX, mouseY), pressed, cam); + } else if (button == 1) { + toolController.doEditToolDraggedSecondary(new Vector2f(mouseX, mouseY), pressed, cam); + } } } diff --git a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/SceneComposerToolController.java b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/SceneComposerToolController.java index dff940e50..00d15bb2f 100644 --- a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/SceneComposerToolController.java +++ b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/SceneComposerToolController.java @@ -10,6 +10,8 @@ import com.jme3.gde.core.scene.SceneApplication; import com.jme3.gde.core.scene.controller.SceneToolController; import com.jme3.gde.core.sceneexplorer.nodes.JmeNode; import com.jme3.gde.core.sceneexplorer.nodes.JmeSpatial; +import com.jme3.gde.scenecomposer.tools.PickManager; +import com.jme3.gde.scenecomposer.tools.shortcuts.ShortcutManager; import com.jme3.input.event.KeyInputEvent; import com.jme3.light.Light; import com.jme3.light.PointLight; @@ -30,6 +32,7 @@ import com.jme3.scene.control.Control; import com.jme3.scene.shape.Quad; import com.jme3.texture.Texture; import java.util.concurrent.Callable; +import org.openide.util.Lookup; /** * @@ -50,7 +53,12 @@ public class SceneComposerToolController extends SceneToolController { private boolean snapToScene = false; private boolean selectTerrain = false; private boolean selectGeometries = false; - + private TransformationType transformationType = TransformationType.local; + + public enum TransformationType { + local, global, camera + } + public SceneComposerToolController(final Node toolsNode, AssetManager manager, JmeNode rootNode) { super(toolsNode, manager); this.rootNode = rootNode; @@ -178,7 +186,12 @@ public class SceneComposerToolController extends SceneToolController { * @param camera */ public void doEditToolActivatedPrimary(Vector2f mouseLoc, boolean pressed, Camera camera) { - if (editTool != null) { + ShortcutManager scm = Lookup.getDefault().lookup(ShortcutManager.class); + + if (scm.isActive()) { + scm.getActiveShortcut().setCamera(camera); + scm.getActiveShortcut().actionPrimary(mouseLoc, pressed, rootNode, editorController.getCurrentDataObject()); + } else if (editTool != null) { editTool.setCamera(camera); editTool.actionPrimary(mouseLoc, pressed, rootNode, editorController.getCurrentDataObject()); } @@ -192,36 +205,66 @@ public class SceneComposerToolController extends SceneToolController { * @param camera */ public void doEditToolActivatedSecondary(Vector2f mouseLoc, boolean pressed, Camera camera) { - if (editTool != null) { + ShortcutManager scm = Lookup.getDefault().lookup(ShortcutManager.class); + + if (scm.isActive()) { + scm.getActiveShortcut().setCamera(camera); + scm.getActiveShortcut().actionSecondary(mouseLoc, pressed, rootNode, editorController.getCurrentDataObject()); + } else if (editTool != null) { editTool.setCamera(camera); editTool.actionSecondary(mouseLoc, pressed, rootNode, editorController.getCurrentDataObject()); } } public void doEditToolMoved(Vector2f mouseLoc, Camera camera) { - if (editTool != null) { + ShortcutManager scm = Lookup.getDefault().lookup(ShortcutManager.class); + + if (scm.isActive()) { + scm.getActiveShortcut().setCamera(camera); + scm.getActiveShortcut().mouseMoved(mouseLoc, rootNode, editorController.getCurrentDataObject(), selectedSpatial); + } else if (editTool != null) { editTool.setCamera(camera); editTool.mouseMoved(mouseLoc, rootNode, editorController.getCurrentDataObject(), selectedSpatial); } } public void doEditToolDraggedPrimary(Vector2f mouseLoc, boolean pressed, Camera camera) { - if (editTool != null) { + ShortcutManager scm = Lookup.getDefault().lookup(ShortcutManager.class); + + if (scm.isActive()) { + scm.getActiveShortcut().setCamera(camera); + scm.getActiveShortcut().draggedPrimary(mouseLoc, pressed, rootNode, editorController.getCurrentDataObject()); + } else if (editTool != null) { editTool.setCamera(camera); editTool.draggedPrimary(mouseLoc, pressed, rootNode, editorController.getCurrentDataObject()); } } public void doEditToolDraggedSecondary(Vector2f mouseLoc, boolean pressed, Camera camera) { - if (editTool != null) { + ShortcutManager scm = Lookup.getDefault().lookup(ShortcutManager.class); + + if (scm.isActive()) { + scm.getActiveShortcut().setCamera(null); + scm.getActiveShortcut().draggedSecondary(mouseLoc, pressed, rootNode, editorController.getCurrentDataObject()); + } else if (editTool != null) { editTool.setCamera(camera); editTool.draggedSecondary(mouseLoc, pressed, rootNode, editorController.getCurrentDataObject()); } } - void doKeyPressed(KeyInputEvent kie) { - if (editTool != null) { - editTool.keyPressed(kie); + public void doKeyPressed(KeyInputEvent kie) { + ShortcutManager scm = Lookup.getDefault().lookup(ShortcutManager.class); + + if (scm.isActive()) { + scm.doKeyPressed(kie); + } else { + if (scm.activateShortcut(kie)) { + scm.getActiveShortcut().activate(manager, toolsNode, onTopToolsNode, selected, this); + } else { + if (editTool != null) { + editTool.keyPressed(kie); + } + } } } @@ -347,9 +390,39 @@ public class SceneComposerToolController extends SceneToolController { public void setSelectGeometries(boolean selectGeometries) { this.selectGeometries = selectGeometries; } + + public void setTransformationType(String type) { + if(type != null){ + if(type.equals("Local")){ + setTransformationType(TransformationType.local); + } else if(type.equals("Global")){ + setTransformationType(TransformationType.global); + } else if(type.equals("Camera")){ + setTransformationType(TransformationType.camera); + } + } + } + + /** + * @param type the transformationType to set + */ + public void setTransformationType(TransformationType type) { + if(type != this.transformationType){ + this.transformationType = type; + if(editTool != null){ + //update the transform type of the tool + editTool.setTransformType(transformationType); + } + } + } - - + /** + * @return the transformationType + */ + public TransformationType getTransformationType() { + return transformationType; + } + /** * A marker on the screen that shows where a point light or * a spot light is. This marker is not part of the scene, diff --git a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/SceneComposerTopComponent.form b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/SceneComposerTopComponent.form index 8b21fb202..fd4686f24 100644 --- a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/SceneComposerTopComponent.form +++ b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/SceneComposerTopComponent.form @@ -99,6 +99,25 @@ + + + + + + + + + + + + + + + + + + + @@ -184,6 +203,11 @@ + + + + + diff --git a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/SceneComposerTopComponent.java b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/SceneComposerTopComponent.java index 1259d74a9..b06e126dc 100644 --- a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/SceneComposerTopComponent.java +++ b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/SceneComposerTopComponent.java @@ -97,6 +97,8 @@ public final class SceneComposerTopComponent extends TopComponent implements Sce sceneInfoLabel1 = new javax.swing.JLabel(); sceneInfoLabel2 = new javax.swing.JLabel(); jToolBar1 = new javax.swing.JToolBar(); + transformationTypeComboBox = new javax.swing.JComboBox(); + jSeparator9 = new javax.swing.JToolBar.Separator(); selectButton = new javax.swing.JToggleButton(); moveButton = new javax.swing.JToggleButton(); rotateButton = new javax.swing.JToggleButton(); @@ -165,6 +167,16 @@ public final class SceneComposerTopComponent extends TopComponent implements Sce jToolBar1.setFloatable(false); jToolBar1.setRollover(true); + transformationTypeComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Local", "Global", "Camera" })); + transformationTypeComboBox.setToolTipText(org.openide.util.NbBundle.getMessage(SceneComposerTopComponent.class, "SceneComposerTopComponent.transformationTypeComboBox.toolTipText")); // NOI18N + transformationTypeComboBox.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + transformationTypeComboBoxActionPerformed(evt); + } + }); + jToolBar1.add(transformationTypeComboBox); + jToolBar1.add(jSeparator9); + spatialModButtonGroup.add(selectButton); selectButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jme3/gde/scenecomposer/icon_select.png"))); // NOI18N selectButton.setSelected(true); @@ -221,6 +233,8 @@ public final class SceneComposerTopComponent extends TopComponent implements Sce } }); jToolBar1.add(scaleButton); + scaleButton.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(SceneComposerTopComponent.class, "SceneComposerTopComponent.scaleButton.AccessibleContext.accessibleDescription")); // NOI18N + jToolBar1.add(jSeparator5); jToggleScene.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jme3/gde/scenecomposer/snapScene.png"))); // NOI18N @@ -644,6 +658,11 @@ private void jToggleSelectTerrainActionPerformed(java.awt.event.ActionEvent evt) private void jToggleSelectGeomActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleSelectGeomActionPerformed toolController.setSelectGeometries(jToggleSelectGeom.isSelected()); }//GEN-LAST:event_jToggleSelectGeomActionPerformed + + private void transformationTypeComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_transformationTypeComboBoxActionPerformed + toolController.setTransformationType((String)transformationTypeComboBox.getSelectedItem()); + }//GEN-LAST:event_transformationTypeComboBoxActionPerformed + // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton camToCursorSelectionButton; private javax.swing.JButton createPhysicsMeshButton; @@ -671,6 +690,7 @@ private void jToggleSelectGeomActionPerformed(java.awt.event.ActionEvent evt) {/ private javax.swing.JSeparator jSeparator6; private javax.swing.JToolBar.Separator jSeparator7; private javax.swing.JToolBar.Separator jSeparator8; + private javax.swing.JToolBar.Separator jSeparator9; private javax.swing.JTextField jTextField1; private javax.swing.JToggleButton jToggleGrid; private javax.swing.JToggleButton jToggleScene; @@ -692,6 +712,7 @@ private void jToggleSelectGeomActionPerformed(java.awt.event.ActionEvent evt) {/ private javax.swing.JToggleButton showGridToggleButton; private javax.swing.JToggleButton showSelectionToggleButton; private javax.swing.ButtonGroup spatialModButtonGroup; + private javax.swing.JComboBox transformationTypeComboBox; // End of variables declaration//GEN-END:variables private void emit(Spatial root) { diff --git a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/SceneEditTool.java b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/SceneEditTool.java index d2767781c..372984f8e 100644 --- a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/SceneEditTool.java +++ b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/SceneEditTool.java @@ -57,6 +57,7 @@ public abstract class SceneEditTool { protected Node axisMarker; protected Material redMat, blueMat, greenMat, yellowMat, cyanMat, magentaMat, orangeMat; protected Geometry quadXY, quadXZ, quadYZ; + protected SceneComposerToolController.TransformationType transformType; protected enum AxisMarkerPickType { @@ -72,6 +73,7 @@ public abstract class SceneEditTool { public void activate(AssetManager manager, Node toolNode, Node onTopToolNode, Spatial selectedSpatial, SceneComposerToolController toolController) { this.manager = manager; this.toolController = toolController; + this.setTransformType(toolController.getTransformationType()); //this.selectedSpatial = selectedSpatial; addMarker(toolNode, onTopToolNode); } @@ -130,7 +132,19 @@ public abstract class SceneEditTool { public void doUpdateToolsTransformation() { if (toolController.getSelectedSpatial() != null) { axisMarker.setLocalTranslation(toolController.getSelectedSpatial().getWorldTranslation()); - axisMarker.setLocalRotation(toolController.getSelectedSpatial().getLocalRotation()); + switch (transformType) { + case local: + axisMarker.setLocalRotation(toolController.getSelectedSpatial().getLocalRotation()); + break; + case global: + axisMarker.setLocalRotation(Quaternion.IDENTITY); + break; + case camera: + if(camera != null){ + axisMarker.setLocalRotation(camera.getRotation()); + } + break; + } setAxisMarkerScale(toolController.getSelectedSpatial()); } else { axisMarker.setLocalTranslation(Vector3f.ZERO); @@ -285,7 +299,7 @@ public abstract class SceneEditTool { * what part of the axis was selected. * For example if (1,0,0) is returned, then the X-axis pole was selected. * If (0,1,1) is returned, then the Y-Z plane was selected. - * + * * @return null if it did not intersect the marker */ protected Vector3f pickAxisMarker(Camera cam, Vector2f mouseLoc, AxisMarkerPickType pickType) { @@ -336,7 +350,7 @@ public abstract class SceneEditTool { CollisionResults results = new CollisionResults(); Ray ray = new Ray(); Vector3f pos = cam.getWorldCoordinates(mouseLoc, 0).clone(); - Vector3f dir = cam.getWorldCoordinates(mouseLoc, 0.1f).clone(); + Vector3f dir = cam.getWorldCoordinates(mouseLoc, 0.125f).clone(); dir.subtractLocal(pos).normalizeLocal(); ray.setOrigin(pos); ray.setDirection(dir); @@ -347,7 +361,7 @@ public abstract class SceneEditTool { /** * Show what axis or plane the mouse is currently over and will affect. - * @param axisMarkerPickType + * @param axisMarkerPickType */ protected void highlightAxisMarker(Camera camera, Vector2f screenCoord, AxisMarkerPickType axisMarkerPickType) { highlightAxisMarker(camera, screenCoord, axisMarkerPickType, false); @@ -355,12 +369,12 @@ public abstract class SceneEditTool { /** * Show what axis or plane the mouse is currently over and will affect. - * @param axisMarkerPickType + * @param axisMarkerPickType * @param colorAll highlight all parts of the marker when only one is selected */ protected void highlightAxisMarker(Camera camera, Vector2f screenCoord, AxisMarkerPickType axisMarkerPickType, boolean colorAll) { setDefaultAxisMarkerColors(); - Vector3f picked = pickAxisMarker(camera, screenCoord, axisPickType); + Vector3f picked = pickAxisMarker(camera, screenCoord, axisMarkerPickType); if (picked == null) { return; } @@ -371,16 +385,17 @@ public abstract class SceneEditTool { axisMarker.getChild("arrowY").setMaterial(orangeMat); } else if (picked == ARROW_Z) { axisMarker.getChild("arrowZ").setMaterial(orangeMat); - } + } else { - if (picked == QUAD_XY || colorAll) { - axisMarker.getChild("quadXY").setMaterial(orangeMat); - } - if (picked == QUAD_XZ || colorAll) { - axisMarker.getChild("quadXZ").setMaterial(orangeMat); - } - if (picked == QUAD_YZ || colorAll) { - axisMarker.getChild("quadYZ").setMaterial(orangeMat); + if (picked == QUAD_XY || colorAll) { + axisMarker.getChild("quadXY").setMaterial(orangeMat); + } + if (picked == QUAD_XZ || colorAll) { + axisMarker.getChild("quadXZ").setMaterial(orangeMat); + } + if (picked == QUAD_YZ || colorAll) { + axisMarker.getChild("quadYZ").setMaterial(orangeMat); + } } } @@ -453,6 +468,7 @@ public abstract class SceneEditTool { // axis.attachChild(quadYZ); axis.setModelBound(new BoundingBox()); + axis.updateModelBound(); return axis; } @@ -485,4 +501,12 @@ public abstract class SceneEditTool { public void setCamera(Camera camera) { this.camera = camera; } + + public SceneComposerToolController.TransformationType getTransformType() { + return transformType; + } + + public void setTransformType(SceneComposerToolController.TransformationType transformType) { + this.transformType = transformType; + } } diff --git a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/MoveManager.java b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/MoveManager.java deleted file mode 100644 index d7b92db91..000000000 --- a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/MoveManager.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.jme3.gde.scenecomposer.tools; - -import com.jme3.bullet.control.CharacterControl; -import com.jme3.bullet.control.RigidBodyControl; -import com.jme3.gde.core.undoredo.AbstractUndoableSceneEdit; -import com.jme3.gde.scenecomposer.SceneEditTool; -import com.jme3.math.FastMath; -import com.jme3.math.Quaternion; -import com.jme3.math.Vector2f; -import com.jme3.math.Vector3f; -import com.jme3.renderer.Camera; -import com.jme3.scene.Geometry; -import com.jme3.scene.Node; -import com.jme3.scene.Spatial; -import com.jme3.scene.shape.Quad; -import org.openide.util.lookup.ServiceProvider; - -/** - * - * @author Nehon - */ -@ServiceProvider(service = MoveManager.class) -public class MoveManager { - - private Vector3f startLoc; - private Vector3f startWorldLoc; - private Vector3f lastLoc; - private Vector3f offset; - private Node alternativePickTarget = null; - private Node plane; - private Spatial spatial; - protected static final Quaternion XY = new Quaternion().fromAngleAxis(0, new Vector3f(1, 0, 0)); - protected static final Quaternion YZ = new Quaternion().fromAngleAxis(-FastMath.PI / 2, new Vector3f(0, 1, 0)); - protected static final Quaternion XZ = new Quaternion().fromAngleAxis(FastMath.PI / 2, new Vector3f(1, 0, 0)); - //temp vars - private Quaternion rot = new Quaternion(); - private Vector3f newPos = new Vector3f(); - - public MoveManager() { - float size = 1000; - Geometry g = new Geometry("plane", new Quad(size, size)); - g.setLocalTranslation(-size / 2, -size / 2, 0); - plane = new Node(); - plane.attachChild(g); - } - - public Vector3f getOffset() { - return offset; - } - - public void reset() { - offset = null; - startLoc = null; - startWorldLoc = null; - lastLoc = null; - spatial = null; - alternativePickTarget = null; - } - - public void initiateMove(Spatial selectedSpatial, Quaternion planeRotation, boolean local) { - spatial = selectedSpatial; - startLoc = selectedSpatial.getLocalTranslation().clone(); - startWorldLoc = selectedSpatial.getWorldTranslation().clone(); - if (local) { - rot.set(selectedSpatial.getWorldRotation()); - plane.setLocalRotation(rot.multLocal(planeRotation)); - } else { - rot.set(planeRotation); - } - - plane.setLocalRotation(rot); - plane.setLocalTranslation(startWorldLoc); - - } - - public void updatePlaneRotation(Quaternion planeRotation) { - plane.setLocalRotation(rot); - } - - public boolean move(Camera camera, Vector2f screenCoord) { - return move(camera, screenCoord, Vector3f.UNIT_XYZ, false); - } - - public boolean move(Camera camera, Vector2f screenCoord, Vector3f constraintAxis, boolean gridSnap) { - Node toPick = alternativePickTarget == null ? plane : alternativePickTarget; - - Vector3f planeHit = SceneEditTool.pickWorldLocation(camera, screenCoord, toPick, alternativePickTarget == null ? null : spatial); - if (planeHit == null) { - return false; - } - - Spatial parent = spatial.getParent(); - //we are moving the root node, there is a slight chance that something went wrong. - if (parent == null) { - return false; - } - - //offset in world space - if (offset == null) { - offset = planeHit.subtract(spatial.getWorldTranslation()); // get the offset when we start so it doesn't jump - } - - newPos.set(planeHit).subtractLocal(offset); - - //constraining the translation with the contraintAxis. - Vector3f tmp = startWorldLoc.mult(Vector3f.UNIT_XYZ.subtract(constraintAxis)); - newPos.multLocal(constraintAxis).addLocal(tmp); - worldToLocalMove(gridSnap); - return true; - } - - private void worldToLocalMove(boolean gridSnap) { - //snap to grid (grid is assumed 1 WU per cell) - if (gridSnap) { - newPos.set(Math.round(newPos.x), Math.round(newPos.y), Math.round(newPos.z)); - } - - //computing the inverse world transform to get the new localtranslation - newPos.subtractLocal(spatial.getParent().getWorldTranslation()); - newPos = spatial.getParent().getWorldRotation().inverse().normalizeLocal().multLocal(newPos); - newPos.divideLocal(spatial.getParent().getWorldScale()); - - lastLoc = newPos; - spatial.setLocalTranslation(newPos); - - RigidBodyControl control = spatial.getControl(RigidBodyControl.class); - if (control != null) { - control.setPhysicsLocation(spatial.getWorldTranslation()); - } - CharacterControl character = spatial.getControl(CharacterControl.class); - if (character != null) { - character.setPhysicsLocation(spatial.getWorldTranslation()); - } - } - - public boolean moveAcross(Vector3f constraintAxis, float value, boolean gridSnap) { - newPos.set(startWorldLoc).addLocal(constraintAxis.mult(value)); - Spatial parent = spatial.getParent(); - //we are moving the root node, there is a slight chance that something went wrong. - if (parent == null) { - return false; - } - worldToLocalMove(gridSnap); - return true; - } - - public MoveUndo makeUndo() { - return new MoveUndo(spatial, startLoc, lastLoc); - } - - public void setAlternativePickTarget(Node alternativePickTarget) { - this.alternativePickTarget = alternativePickTarget; - } - - protected class MoveUndo extends AbstractUndoableSceneEdit { - - private Spatial spatial; - private Vector3f before = new Vector3f(), after = new Vector3f(); - - MoveUndo(Spatial spatial, Vector3f before, Vector3f after) { - this.spatial = spatial; - this.before.set(before); - if (after != null) { - this.after.set(after); - } - } - - @Override - public void sceneUndo() { - spatial.setLocalTranslation(before); - RigidBodyControl control = spatial.getControl(RigidBodyControl.class); - if (control != null) { - control.setPhysicsLocation(spatial.getWorldTranslation()); - } - CharacterControl character = spatial.getControl(CharacterControl.class); - if (character != null) { - character.setPhysicsLocation(spatial.getWorldTranslation()); - } - // toolController.selectedSpatialTransformed(); - } - - @Override - public void sceneRedo() { - spatial.setLocalTranslation(after); - RigidBodyControl control = spatial.getControl(RigidBodyControl.class); - if (control != null) { - control.setPhysicsLocation(spatial.getWorldTranslation()); - } - CharacterControl character = spatial.getControl(CharacterControl.class); - if (character != null) { - character.setPhysicsLocation(spatial.getWorldTranslation()); - } - //toolController.selectedSpatialTransformed(); - } - - public void setAfter(Vector3f after) { - this.after.set(after); - } - } -} diff --git a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/MoveTool.java b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/MoveTool.java index 97f48cc9f..b3a48a6f6 100644 --- a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/MoveTool.java +++ b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/MoveTool.java @@ -5,8 +5,11 @@ package com.jme3.gde.scenecomposer.tools; import com.jme3.asset.AssetManager; +import com.jme3.bullet.control.CharacterControl; +import com.jme3.bullet.control.RigidBodyControl; import com.jme3.gde.core.sceneexplorer.nodes.JmeNode; import com.jme3.gde.core.sceneexplorer.nodes.JmeSpatial; +import com.jme3.gde.core.undoredo.AbstractUndoableSceneEdit; import com.jme3.gde.scenecomposer.SceneComposerToolController; import com.jme3.gde.scenecomposer.SceneEditTool; import com.jme3.math.Vector2f; @@ -17,19 +20,21 @@ import org.openide.loaders.DataObject; import org.openide.util.Lookup; /** - * Move an object. - * When created, it generates a quad that will lie along a plane - * that the user selects for moving on. When the mouse is over - * the axisMarker, it will highlight the plane that it is over: XY,XZ,YZ. - * When clicked and then dragged, the selected object will move along that - * plane. + * Move an object. When created, it generates a quad that will lie along a plane + * that the user selects for moving on. When the mouse is over the axisMarker, + * it will highlight the plane that it is over: XY,XZ,YZ. When clicked and then + * dragged, the selected object will move along that plane. + * * @author Brent Owens */ public class MoveTool extends SceneEditTool { - private Vector3f pickedPlane; + private Vector3f pickedMarker; + private Vector3f constraintAxis; //used for one axis move private boolean wasDragging = false; - private MoveManager moveManager; + private Vector3f startPosition; + private Vector3f lastPosition; + private PickManager pickManager; public MoveTool() { axisPickType = AxisMarkerPickType.axisAndPlane; @@ -40,7 +45,7 @@ public class MoveTool extends SceneEditTool { @Override public void activate(AssetManager manager, Node toolNode, Node onTopToolNode, Spatial selectedSpatial, SceneComposerToolController toolController) { super.activate(manager, toolNode, onTopToolNode, selectedSpatial, toolController); - moveManager = Lookup.getDefault().lookup(MoveManager.class); + pickManager = Lookup.getDefault().lookup(PickManager.class); displayPlanes(); } @@ -48,27 +53,61 @@ public class MoveTool extends SceneEditTool { public void actionPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) { if (!pressed) { setDefaultAxisMarkerColors(); - pickedPlane = null; // mouse released, reset selection + pickedMarker = null; // mouse released, reset selection + constraintAxis = Vector3f.UNIT_XYZ; // no constraint if (wasDragging) { - actionPerformed(moveManager.makeUndo()); + actionPerformed(new MoveUndo(toolController.getSelectedSpatial(), startPosition, lastPosition)); wasDragging = false; } - moveManager.reset(); + pickManager.reset(); + } else { + if (toolController.getSelectedSpatial() == null) { + return; + } + + if (pickedMarker == null) { + pickedMarker = pickAxisMarker(camera, screenCoord, axisPickType); + if (pickedMarker == null) { + return; + } + + if (pickedMarker.equals(QUAD_XY)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), PickManager.PLANE_XY, getTransformType(), camera, screenCoord); + } else if (pickedMarker.equals(QUAD_XZ)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), PickManager.PLANE_XZ, getTransformType(), camera, screenCoord); + } else if (pickedMarker.equals(QUAD_YZ)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), PickManager.PLANE_YZ, getTransformType(), camera, screenCoord); + } else if (pickedMarker.equals(ARROW_X)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), PickManager.PLANE_XY, getTransformType(), camera, screenCoord); + constraintAxis = Vector3f.UNIT_X; // move only X + } else if (pickedMarker.equals(ARROW_Y)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), PickManager.PLANE_YZ, getTransformType(), camera, screenCoord); + constraintAxis = Vector3f.UNIT_Y; // move only Y + } else if (pickedMarker.equals(ARROW_Z)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), PickManager.PLANE_XZ, getTransformType(), camera, screenCoord); + constraintAxis = Vector3f.UNIT_Z; // move only Z + } + startPosition = toolController.getSelectedSpatial().getLocalTranslation().clone(); + wasDragging = true; + } } } @Override public void actionSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) { + if (pressed) { + cancel(); + } } @Override public void mouseMoved(Vector2f screenCoord, JmeNode rootNode, DataObject currentDataObject, JmeSpatial selectedSpatial) { - - if (pickedPlane == null) { + + if (pickedMarker == null) { highlightAxisMarker(camera, screenCoord, axisPickType); } else { - pickedPlane = null; - moveManager.reset(); + pickedMarker = null; + pickManager.reset(); } } @@ -76,42 +115,92 @@ public class MoveTool extends SceneEditTool { public void draggedPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) { if (!pressed) { setDefaultAxisMarkerColors(); - pickedPlane = null; // mouse released, reset selection + pickedMarker = null; // mouse released, reset selection + constraintAxis = Vector3f.UNIT_XYZ; // no constraint if (wasDragging) { - actionPerformed(moveManager.makeUndo()); + actionPerformed(new MoveUndo(toolController.getSelectedSpatial(), startPosition, lastPosition)); wasDragging = false; } - moveManager.reset(); - return; + pickManager.reset(); + } else if (wasDragging == true) { + if (!pickManager.updatePick(camera, screenCoord)) { + return; + } + Vector3f diff = Vector3f.ZERO; + if (pickedMarker.equals(QUAD_XY) || pickedMarker.equals(QUAD_XZ) || pickedMarker.equals(QUAD_YZ)) { + diff = pickManager.getTranslation(); + + } else if (pickedMarker.equals(ARROW_X) || pickedMarker.equals(ARROW_Y) || pickedMarker.equals(ARROW_Z)) { + diff = pickManager.getTranslation(constraintAxis); + } + Vector3f position = startPosition.add(diff); + lastPosition = position; + toolController.getSelectedSpatial().setLocalTranslation(position); + updateToolsTransformation(); } + } - if (toolController.getSelectedSpatial() == null) { - return; + @Override + public void draggedSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) { + if (pressed) { + cancel(); } + } - if (pickedPlane == null) { - pickedPlane = pickAxisMarker(camera, screenCoord, axisPickType); - if (pickedPlane == null) { - return; - } + private void cancel() { + if (wasDragging) { + wasDragging = false; + toolController.getSelectedSpatial().setLocalTranslation(startPosition); + setDefaultAxisMarkerColors(); + pickedMarker = null; // mouse released, reset selection + constraintAxis = Vector3f.UNIT_XYZ; // no constraint + pickManager.reset(); + } + } - if (pickedPlane.equals(new Vector3f(1, 1, 0))) { - moveManager.initiateMove(toolController.getSelectedSpatial(), MoveManager.XY, true); - } else if (pickedPlane.equals(new Vector3f(1, 0, 1))) { - moveManager.initiateMove(toolController.getSelectedSpatial(), MoveManager.XZ, true); - } else if (pickedPlane.equals(new Vector3f(0, 1, 1))) { - moveManager.initiateMove(toolController.getSelectedSpatial(), MoveManager.YZ, true); + protected class MoveUndo extends AbstractUndoableSceneEdit { + + private Spatial spatial; + private Vector3f before = new Vector3f(), after = new Vector3f(); + + MoveUndo(Spatial spatial, Vector3f before, Vector3f after) { + this.spatial = spatial; + this.before.set(before); + if (after != null) { + this.after.set(after); } } - if (!moveManager.move(camera, screenCoord)) { - return; + + @Override + public void sceneUndo() { + spatial.setLocalTranslation(before); + RigidBodyControl control = spatial.getControl(RigidBodyControl.class); + if (control != null) { + control.setPhysicsLocation(spatial.getWorldTranslation()); + } + CharacterControl character = spatial.getControl(CharacterControl.class); + if (character != null) { + character.setPhysicsLocation(spatial.getWorldTranslation()); + } + // toolController.selectedSpatialTransformed(); } - updateToolsTransformation(); - wasDragging = true; - } + @Override + public void sceneRedo() { + spatial.setLocalTranslation(after); + RigidBodyControl control = spatial.getControl(RigidBodyControl.class); + if (control != null) { + control.setPhysicsLocation(spatial.getWorldTranslation()); + } + CharacterControl character = spatial.getControl(CharacterControl.class); + if (character != null) { + character.setPhysicsLocation(spatial.getWorldTranslation()); + } + //toolController.selectedSpatialTransformed(); + } - @Override - public void draggedSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) { + public void setAfter(Vector3f after) { + this.after.set(after); + } } } diff --git a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/PickManager.java b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/PickManager.java new file mode 100644 index 000000000..af4f11fe5 --- /dev/null +++ b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/PickManager.java @@ -0,0 +1,189 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.jme3.gde.scenecomposer.tools; + +import com.jme3.gde.scenecomposer.SceneComposerToolController; +import com.jme3.gde.scenecomposer.SceneEditTool; +import com.jme3.math.FastMath; +import com.jme3.math.Quaternion; +import com.jme3.math.Vector2f; +import com.jme3.math.Vector3f; +import com.jme3.renderer.Camera; +import com.jme3.scene.Geometry; +import com.jme3.scene.Node; +import com.jme3.scene.Spatial; +import com.jme3.scene.shape.Quad; +import org.openide.util.lookup.ServiceProvider; + +/** + * + * @author dokthar + */ +@ServiceProvider(service = PickManager.class) +public class PickManager { + + private Vector3f startPickLoc; + private Vector3f finalPickLoc; + private Vector3f startSpatialLocation; + private Quaternion origineRotation; + private final Node plane; + private Spatial spatial; + private SceneComposerToolController.TransformationType transformationType; + + public static final Quaternion PLANE_XY = new Quaternion().fromAngleAxis(0, new Vector3f(1, 0, 0)); + public static final Quaternion PLANE_YZ = new Quaternion().fromAngleAxis(-FastMath.PI / 2, new Vector3f(0, 1, 0));//YAW090 + public static final Quaternion PLANE_XZ = new Quaternion().fromAngleAxis(FastMath.PI / 2, new Vector3f(1, 0, 0)); //PITCH090 + + + public PickManager() { + float size = 1000; + Geometry g = new Geometry("plane", new Quad(size, size)); + g.setLocalTranslation(-size / 2, -size / 2, 0); + plane = new Node(); + plane.attachChild(g); + } + + public void reset() { + startPickLoc = null; + finalPickLoc = null; + startSpatialLocation = null; + spatial = null; + } + + public void initiatePick(Spatial selectedSpatial, Quaternion planeRotation, SceneComposerToolController.TransformationType type, Camera camera, Vector2f screenCoord) { + spatial = selectedSpatial; + startSpatialLocation = selectedSpatial.getWorldTranslation().clone(); + + setTransformation(planeRotation, type, camera); + plane.setLocalTranslation(startSpatialLocation); + + startPickLoc = SceneEditTool.pickWorldLocation(camera, screenCoord, plane, null); + } + + public void setTransformation(Quaternion planeRotation, SceneComposerToolController.TransformationType type, Camera camera) { + Quaternion rot = new Quaternion(); + transformationType = type; + if (transformationType == SceneComposerToolController.TransformationType.local) { + rot.set(spatial.getWorldRotation()); + rot.multLocal(planeRotation); + origineRotation = spatial.getWorldRotation().clone(); + } else if (transformationType == SceneComposerToolController.TransformationType.global) { + rot.set(planeRotation); + origineRotation = new Quaternion(Quaternion.IDENTITY); + } else if (transformationType == SceneComposerToolController.TransformationType.camera) { + rot.set(camera.getRotation()); + origineRotation = camera.getRotation(); + } + plane.setLocalRotation(rot); + } + + /** + * + * @param camera + * @param screenCoord + * @return true if the the new picked location is set, else return false. + */ + public boolean updatePick(Camera camera, Vector2f screenCoord) { + finalPickLoc = SceneEditTool.pickWorldLocation(camera, screenCoord, plane, null); + return finalPickLoc != null; + } + + /** + * + * @return the start location in WorldSpace + */ + public Vector3f getStartLocation() { + return startSpatialLocation; + } + + /** + * + * @return the vector from the tool origin to the start location, in + * WorldSpace + */ + public Vector3f getStartOffset() { + return startPickLoc.subtract(startSpatialLocation); + } + + /** + * + * @return the vector from the tool origin to the final location, in + * WorldSpace + */ + public Vector3f getFinalOffset() { + return finalPickLoc.subtract(startSpatialLocation); + } + + /** + * + * @return the angle between the start location and the final location + */ + public float getAngle() { + Vector3f v1, v2; + v1 = startPickLoc.subtract(startSpatialLocation); + v2 = finalPickLoc.subtract(startSpatialLocation); + return v1.angleBetween(v2); + } + + /** + * + * @return the Quaternion rotation in the WorldSpace + */ + public Quaternion getRotation() { + return getRotation(Quaternion.IDENTITY); + } + + /** + * + * @return the Quaternion rotation in the ToolSpace + */ + public Quaternion getLocalRotation() { + return getRotation(origineRotation.inverse()); + } + + /** + * Get the Rotation into a specific custom space. + * @param transforme the rotation to the custom space (World to Custom space) + * @return the Rotation in the custom space + */ + public Quaternion getRotation(Quaternion transforme) { + Vector3f v1, v2; + v1 = transforme.mult(startPickLoc.subtract(startSpatialLocation).normalize()); + v2 = transforme.mult(finalPickLoc.subtract(startSpatialLocation).normalize()); + Vector3f axis = v1.cross(v2); + float angle = v1.angleBetween(v2); + return new Quaternion().fromAngleAxis(angle, axis); + } + + /** + * + * @return the translation in WorldSpace + */ + public Vector3f getTranslation() { + return finalPickLoc.subtract(startPickLoc); + } + + /** + * + * @param axisConstrainte + * @return + */ + public Vector3f getTranslation(Vector3f axisConstrainte) { + Vector3f localConstrainte = (origineRotation.mult(axisConstrainte)).normalize(); // according to the "plane" rotation + Vector3f constrainedTranslation = localConstrainte.mult(getTranslation().dot(localConstrainte)); + return constrainedTranslation; + } + + /** + * + * @param axisConstrainte + * @return + */ + public Vector3f getLocalTranslation(Vector3f axisConstrainte) { + return getTranslation(origineRotation.inverse().mult(axisConstrainte)); + } + +} diff --git a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/RotateTool.java b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/RotateTool.java index 3c4e27b95..e5a125771 100644 --- a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/RotateTool.java +++ b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/RotateTool.java @@ -16,144 +16,142 @@ import com.jme3.math.Vector3f; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import org.openide.loaders.DataObject; - +import org.openide.util.Lookup; + /** * * @author kbender */ public class RotateTool extends SceneEditTool { - - private Vector3f pickedPlane; - private Vector2f lastScreenCoord; + + private Vector3f pickedMarker; private Quaternion startRotate; private Quaternion lastRotate; private boolean wasDragging = false; - + private PickManager pickManager; + public RotateTool() { - axisPickType = AxisMarkerPickType.axisAndPlane; + axisPickType = AxisMarkerPickType.planeOnly; setOverrideCameraControl(true); } - + @Override public void activate(AssetManager manager, Node toolNode, Node onTopToolNode, Spatial selectedSpatial, SceneComposerToolController toolController) { super.activate(manager, toolNode, onTopToolNode, selectedSpatial, toolController); + pickManager = Lookup.getDefault().lookup(PickManager.class); displayPlanes(); } - + @Override public void actionPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) { if (!pressed) { setDefaultAxisMarkerColors(); - pickedPlane = null; // mouse released, reset selection - lastScreenCoord = null; + pickedMarker = null; // mouse released, reset selection if (wasDragging) { - actionPerformed(new ScaleUndo(toolController.getSelectedSpatial(), startRotate, lastRotate)); + actionPerformed(new RotateUndo(toolController.getSelectedSpatial(), startRotate, lastRotate)); wasDragging = false; } + pickManager.reset(); + } else { + if (toolController.getSelectedSpatial() == null) { + return; + } + + if (pickedMarker == null) { + pickedMarker = pickAxisMarker(camera, screenCoord, axisPickType); + if (pickedMarker == null) { + return; + } + + if (pickedMarker.equals(QUAD_XY)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), PickManager.PLANE_XY, getTransformType(), camera, screenCoord); + } else if (pickedMarker.equals(QUAD_XZ)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), PickManager.PLANE_XZ, getTransformType(), camera, screenCoord); + } else if (pickedMarker.equals(QUAD_YZ)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), PickManager.PLANE_YZ, getTransformType(), camera, screenCoord); + } + startRotate = toolController.getSelectedSpatial().getLocalRotation().clone(); + wasDragging = true; + } } } - + @Override public void actionSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) { - + if (pressed) { + cancel(); + } } - + @Override public void mouseMoved(Vector2f screenCoord, JmeNode rootNode, DataObject currentDataObject, JmeSpatial selectedSpatial) { - if (pickedPlane == null) { + if (pickedMarker == null) { highlightAxisMarker(camera, screenCoord, axisPickType); - } - else { - pickedPlane = null; + } else { + pickedMarker = null; + pickManager.reset(); } } - + @Override public void draggedPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) { - if (!pressed) { setDefaultAxisMarkerColors(); - pickedPlane = null; // mouse released, reset selection - lastScreenCoord = null; - + pickedMarker = null; // mouse released, reset selection + if (wasDragging) { - actionPerformed(new ScaleUndo(toolController.getSelectedSpatial(), startRotate, lastRotate)); + actionPerformed(new RotateUndo(toolController.getSelectedSpatial(), startRotate, lastRotate)); wasDragging = false; } - return; - } - - if (toolController.getSelectedSpatial() == null) - { - return; - } - - if (pickedPlane == null) - { - pickedPlane = pickAxisMarker(camera, screenCoord, axisPickType); - if (pickedPlane == null) - { + pickManager.reset(); + } else if (wasDragging) { + if (!pickManager.updatePick(camera, screenCoord)) { return; } - startRotate = toolController.getSelectedSpatial().getLocalRotation().clone(); - } - - if (lastScreenCoord == null) { - lastScreenCoord = screenCoord; - } else { - Quaternion rotate = new Quaternion(); - float diff; - if(pickedPlane.equals(QUAD_XY)) - { - diff = -(screenCoord.x-lastScreenCoord.x); - diff *= 0.03f; - rotate = rotate.fromAngleAxis(diff, Vector3f.UNIT_Z); - } - else if(pickedPlane.equals(QUAD_YZ)) - { - diff = -(screenCoord.y-lastScreenCoord.y); - diff *= 0.03f; - rotate = rotate.fromAngleAxis(diff, Vector3f.UNIT_X); - } - else if(pickedPlane.equals(QUAD_XZ)) - { - diff = screenCoord.x-lastScreenCoord.x; - diff *= 0.03f; - rotate = rotate.fromAngleAxis(diff, Vector3f.UNIT_Y); + + if (pickedMarker.equals(QUAD_XY) || pickedMarker.equals(QUAD_XZ) || pickedMarker.equals(QUAD_YZ)) { + Quaternion rotation = startRotate.mult(pickManager.getRotation(startRotate.inverse())); + toolController.getSelectedSpatial().setLocalRotation(rotation); + lastRotate = rotation; } - - lastScreenCoord = screenCoord; - Quaternion rotation = toolController.getSelectedSpatial().getLocalRotation().mult(rotate); - lastRotate = rotation; - toolController.getSelectedSpatial().setLocalRotation(rotation); updateToolsTransformation(); } - - wasDragging = true; } - + @Override public void draggedSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) { - + if (pressed) { + cancel(); + } } - - private class ScaleUndo extends AbstractUndoableSceneEdit { - + + private void cancel() { + if (wasDragging) { + wasDragging = false; + toolController.getSelectedSpatial().setLocalRotation(startRotate); + setDefaultAxisMarkerColors(); + pickedMarker = null; // mouse released, reset selection + pickManager.reset(); + } + } + + private class RotateUndo extends AbstractUndoableSceneEdit { + private Spatial spatial; - private Quaternion before,after; - - ScaleUndo(Spatial spatial, Quaternion before, Quaternion after) { + private Quaternion before, after; + + RotateUndo(Spatial spatial, Quaternion before, Quaternion after) { this.spatial = spatial; this.before = before; this.after = after; } - + @Override public void sceneUndo() { spatial.setLocalRotation(before); toolController.selectedSpatialTransformed(); } - + @Override public void sceneRedo() { spatial.setLocalRotation(after); diff --git a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/ScaleTool.java b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/ScaleTool.java index 862ef2be2..a34478372 100644 --- a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/ScaleTool.java +++ b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/ScaleTool.java @@ -10,118 +10,159 @@ import com.jme3.gde.core.sceneexplorer.nodes.JmeSpatial; import com.jme3.gde.core.undoredo.AbstractUndoableSceneEdit; import com.jme3.gde.scenecomposer.SceneComposerToolController; import com.jme3.gde.scenecomposer.SceneEditTool; +import com.jme3.math.Quaternion; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import org.openide.loaders.DataObject; +import org.openide.util.Lookup; /** * * @author sploreg */ public class ScaleTool extends SceneEditTool { - - private Vector3f pickedPlane; - private Vector2f lastScreenCoord; + + private Vector3f pickedMarker; + private Vector3f constraintAxis; //used for one axis scale private Vector3f startScale; private Vector3f lastScale; private boolean wasDragging = false; - + private PickManager pickManager; + public ScaleTool() { axisPickType = AxisMarkerPickType.axisAndPlane; setOverrideCameraControl(true); } - + @Override public void activate(AssetManager manager, Node toolNode, Node onTopToolNode, Spatial selectedSpatial, SceneComposerToolController toolController) { super.activate(manager, toolNode, onTopToolNode, selectedSpatial, toolController); + pickManager = Lookup.getDefault().lookup(PickManager.class); displayPlanes(); } - + @Override public void actionPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) { if (!pressed) { setDefaultAxisMarkerColors(); - pickedPlane = null; // mouse released, reset selection - lastScreenCoord = null; + pickedMarker = null; // mouse released, reset selection + constraintAxis = Vector3f.UNIT_XYZ; // no axis constraint if (wasDragging) { actionPerformed(new ScaleUndo(toolController.getSelectedSpatial(), startScale, lastScale)); wasDragging = false; } + pickManager.reset(); + } else { + if (toolController.getSelectedSpatial() == null) { + return; + } + if (pickedMarker == null) { + pickedMarker = pickAxisMarker(camera, screenCoord, axisPickType); + if (pickedMarker == null) { + return; + } + + if (pickedMarker.equals(QUAD_XY) || pickedMarker.equals(QUAD_XZ) || pickedMarker.equals(QUAD_YZ)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), camera.getRotation(), + SceneComposerToolController.TransformationType.camera, camera, screenCoord); + } else if (pickedMarker.equals(ARROW_X)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), PickManager.PLANE_XY, getTransformType(), camera, screenCoord); + constraintAxis = Vector3f.UNIT_X; // scale only X + } else if (pickedMarker.equals(ARROW_Y)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), PickManager.PLANE_YZ, getTransformType(), camera, screenCoord); + constraintAxis = Vector3f.UNIT_Y; // scale only Y + } else if (pickedMarker.equals(ARROW_Z)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), PickManager.PLANE_XZ, getTransformType(), camera, screenCoord); + constraintAxis = Vector3f.UNIT_Z; // scale only Z + } + startScale = toolController.getSelectedSpatial().getLocalScale().clone(); + wasDragging = true; + } } } - + @Override public void actionSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) { - + if (pressed) { + cancel(); + } } @Override public void mouseMoved(Vector2f screenCoord, JmeNode rootNode, DataObject currentDataObject, JmeSpatial selectedSpatial) { - if (pickedPlane == null) { + if (pickedMarker == null) { highlightAxisMarker(camera, screenCoord, axisPickType, true); + } else { + pickedMarker = null; + pickManager.reset(); } - /*else { - pickedPlane = null; - lastScreenCoord = null; - }*/ } @Override public void draggedPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) { if (!pressed) { setDefaultAxisMarkerColors(); - pickedPlane = null; // mouse released, reset selection - lastScreenCoord = null; - + pickedMarker = null; // mouse released, reset selection + constraintAxis = Vector3f.UNIT_XYZ; // no axis constraint if (wasDragging) { actionPerformed(new ScaleUndo(toolController.getSelectedSpatial(), startScale, lastScale)); wasDragging = false; } - return; - } - - if (toolController.getSelectedSpatial() == null) - return; - if (pickedPlane == null) { - pickedPlane = pickAxisMarker(camera, screenCoord, axisPickType); - if (pickedPlane == null) + pickManager.reset(); + } else if (wasDragging) { + if (!pickManager.updatePick(camera, screenCoord)) { return; - startScale = toolController.getSelectedSpatial().getLocalScale().clone(); - } - - if (lastScreenCoord == null) { - lastScreenCoord = screenCoord; - } else { - float diff = screenCoord.y-lastScreenCoord.y; - diff *= 0.1f; - lastScreenCoord = screenCoord; - Vector3f scale = toolController.getSelectedSpatial().getLocalScale().add(diff, diff, diff); - lastScale = scale; - toolController.getSelectedSpatial().setLocalScale(scale); + } + if (pickedMarker.equals(QUAD_XY) || pickedMarker.equals(QUAD_XZ) || pickedMarker.equals(QUAD_YZ)) { + constraintAxis = pickManager.getStartOffset().normalize(); + float diff = pickManager.getTranslation(constraintAxis).dot(constraintAxis); + diff *= 0.5f; + Vector3f scale = startScale.add(new Vector3f(diff, diff, diff)); + lastScale = scale; + toolController.getSelectedSpatial().setLocalScale(scale); + } else if (pickedMarker.equals(ARROW_X) || pickedMarker.equals(ARROW_Y) || pickedMarker.equals(ARROW_Z)) { + // Get the translation in the spatial Space + Quaternion worldToSpatial = toolController.getSelectedSpatial().getWorldRotation().inverse(); + Vector3f diff = pickManager.getTranslation(worldToSpatial.mult(constraintAxis)); + diff.multLocal(0.5f); + Vector3f scale = startScale.add(diff); + lastScale = scale; + toolController.getSelectedSpatial().setLocalScale(scale); + } updateToolsTransformation(); } - - wasDragging = true; } @Override public void draggedSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) { - + if (pressed) { + cancel(); + } + } + + private void cancel() { + if (wasDragging) { + wasDragging = false; + toolController.getSelectedSpatial().setLocalScale(startScale); + setDefaultAxisMarkerColors(); + pickedMarker = null; // mouse released, reset selection + pickManager.reset(); + } } private class ScaleUndo extends AbstractUndoableSceneEdit { private Spatial spatial; - private Vector3f before,after; - + private Vector3f before, after; + ScaleUndo(Spatial spatial, Vector3f before, Vector3f after) { this.spatial = spatial; this.before = before; this.after = after; } - + @Override public void sceneUndo() { spatial.setLocalScale(before); @@ -133,6 +174,6 @@ public class ScaleTool extends SceneEditTool { spatial.setLocalScale(after); toolController.selectedSpatialTransformed(); } - + } } diff --git a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/SelectTool.java b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/SelectTool.java index 43d3cba3a..87f3c283f 100644 --- a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/SelectTool.java +++ b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/SelectTool.java @@ -8,425 +8,51 @@ import com.jme3.gde.core.sceneexplorer.SceneExplorerTopComponent; import com.jme3.gde.core.sceneexplorer.nodes.JmeNode; import com.jme3.gde.core.sceneexplorer.nodes.JmeSpatial; import com.jme3.gde.core.sceneviewer.SceneViewerTopComponent; -import com.jme3.gde.core.undoredo.AbstractUndoableSceneEdit; import com.jme3.gde.scenecomposer.SceneEditTool; -import com.jme3.input.KeyInput; -import com.jme3.input.event.KeyInputEvent; -import com.jme3.math.FastMath; -import com.jme3.math.Quaternion; import com.jme3.math.Vector2f; -import com.jme3.math.Vector3f; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.jme3.terrain.Terrain; import org.openide.loaders.DataObject; -import org.openide.util.Lookup; /** - * This duplicates the Blender manipulate tool. - * It supports quick access to Grab, Rotate, and Scale operations - * by typing one of the following keys: 'g', 'r', or 's' - * Those keys can be followed by an axis key to specify what axis - * to perform the transformation: x, y, z - * Then, after the operation and axis are selected, you can type in a - * number and then hit 'enter' to complete the transformation. - * - * Ctrl+Shift+D will duplicate an object - * X will delete an object - * - * ITEMS TO FINISH: - * 1) fixed scale and rotation values by holding Ctrl and dragging mouse - * BUGS: - * 1) window always needs focus from primary click when it should focus from secondary and middle mouse - * + * This duplicates the Blender manipulate tool. It supports quick access to + * Grab, Rotate, and Scale operations by typing one of the following keys: 'g', + * 'r', or 's' Those keys can be followed by an axis key to specify what axis to + * perform the transformation: x, y, z Then, after the operation and axis are + * selected, you can type in a number and then hit 'enter' to complete the + * transformation. + * + * Ctrl+Shift+D will duplicate an object X will delete an object + * + * ITEMS TO FINISH: 1) fixed scale and rotation values by holding Ctrl and + * dragging mouse BUGS: 1) window always needs focus from primary click when it + * should focus from secondary and middle mouse + * * @author Brent Owens */ public class SelectTool extends SceneEditTool { - private enum State { - - translate, rotate, scale - }; - private State currentState = null; - private Vector3f currentAxis = Vector3f.UNIT_XYZ; - private StringBuilder numberBuilder = new StringBuilder(); // gets appended with numbers - private Quaternion startRot; - private Vector3f startTrans; - private Vector3f startScale; - private boolean wasDraggingL = false; private boolean wasDraggingR = false; private boolean wasDownR = false; - private boolean ctrlDown = false; - private boolean shiftDown = false; - private boolean altDown = false; - private MoveManager.MoveUndo moving; - private ScaleUndo scaling; - private RotateUndo rotating; - private Vector2f startMouseCoord; // for scaling and rotation - private Vector2f startSelectedCoord; // for scaling and rotation - private float lastRotAngle; // used for rotation /** - * This is stateful: - * First it checks for a command (rotate, translate, delete, etc..) - * Then it checks for an axis (x,y,z) - * Then it checks for a number (user typed a number - * Then, finally, it checks if Enter was hit. - * + * This is stateful: First it checks for a command (rotate, translate, + * delete, etc..) Then it checks for an axis (x,y,z) Then it checks for a + * number (user typed a number Then, finally, it checks if Enter was hit. + * * If either of the commands was actioned, the preceeding states/axis/amount - * will be reset. For example if the user types: G Y 2 R - * Then it will: - * 1) Set state as 'Translate' for the G (grab) - * 2) Set the axis as 'Y'; it will translate along the Y axis - * 3) Distance will be 2, when the 2 key is hit - * 4) Distance, Axis, and state are then reset because a new state was set: Rotate - * it won't actually translate because 'Enter' was not hit and 'R' reset the state. - * + * will be reset. For example if the user types: G Y 2 R Then it will: 1) + * Set state as 'Translate' for the G (grab) 2) Set the axis as 'Y'; it will + * translate along the Y axis 3) Distance will be 2, when the 2 key is hit + * 4) Distance, Axis, and state are then reset because a new state was set: + * Rotate it won't actually translate because 'Enter' was not hit and 'R' + * reset the state. + * */ - @Override - public void keyPressed(KeyInputEvent kie) { - - checkModificatorKeys(kie); // alt,shift,ctrl - Spatial selected = toolController.getSelectedSpatial(); - - if (selected == null) { - return; // only do anything if a spatial is selected - } - // key released - if (kie.isPressed()) { - boolean commandUsed = checkCommandKey(kie); - boolean stateChange = checkStateKey(kie); - boolean axisChange = checkAxisKey(kie); - boolean numberChange = checkNumberKey(kie); - boolean enterHit = checkEnterHit(kie); - boolean escHit = checkEscHit(kie); - - if (commandUsed) { - return; // commands take priority - } - if (stateChange) { - currentAxis = Vector3f.UNIT_XYZ; - numberBuilder = new StringBuilder(); - recordInitialState(selected); - } else if (axisChange) { - } else if (numberChange) { - } else if (enterHit) { - if (currentState != null && numberBuilder.length() > 0) { - applyKeyedChangeState(selected); - clearState(false); - } - } - - - // ----------------------- - // reset conditions below: - - if (escHit) { - if (moving != null) { - moving.sceneUndo(); - } - - moving = null; - clearState(); - } - - if (!stateChange && !axisChange && !numberChange && !enterHit && !escHit) { - // nothing valid was hit, reset the state - //clearState(); // this will be - } - } - } - - /** - * Abort any manipulations - */ - private void clearState() { - clearState(true); - } - - private void clearState(boolean resetSelected) { - Spatial selected = toolController.getSelectedSpatial(); - if (resetSelected && selected != null) { - // reset the transforms - if (startRot != null) { - selected.setLocalRotation(startRot); - } - if (startTrans != null) { - selected.setLocalTranslation(startTrans); - } - if (startScale != null) { - selected.setLocalScale(startScale); - } - } - currentState = null; - currentAxis = Vector3f.UNIT_XYZ; - numberBuilder = new StringBuilder(); - startRot = null; - startTrans = null; - startScale = null; - startMouseCoord = null; - startSelectedCoord = null; - lastRotAngle = 0; - } - - private void recordInitialState(Spatial selected) { - startRot = selected.getLocalRotation().clone(); - startTrans = selected.getLocalTranslation().clone(); - startScale = selected.getLocalScale().clone(); - } - - /** - * Applies the changes entered by a number, not by mouse. - * Translate: adds the value to the current local translation - * Rotate: rotates by X degrees - * Scale: scale the current scale by X amount - */ - private void applyKeyedChangeState(Spatial selected) { - Float value = null; - try { - value = new Float(numberBuilder.toString()); - } catch (NumberFormatException e) { - return; - } - - if (currentState == State.translate) { - MoveManager moveManager = Lookup.getDefault().lookup(MoveManager.class); - moveManager.moveAcross(currentAxis, value, toolController.isSnapToGrid()); - moving.setAfter(selected.getLocalTranslation()); - actionPerformed(moving); - moving = null; - } else if (currentState == State.scale) { - float x = 1, y = 1, z = 1; - if (currentAxis == Vector3f.UNIT_X) { - x = value; - } else if (currentAxis == Vector3f.UNIT_Y) { - y = value; - } else if (currentAxis == Vector3f.UNIT_Z) { - z = value; - } else if (currentAxis == Vector3f.UNIT_XYZ) { - x = value; - y = value; - z = value; - } - Vector3f before = selected.getLocalScale().clone(); - Vector3f after = selected.getLocalScale().multLocal(x, y, z); - selected.setLocalScale(after); - actionPerformed(new ScaleUndo(selected, before, after)); - } else if (currentState == State.rotate) { - float x = 0, y = 0, z = 0; - if (currentAxis == Vector3f.UNIT_X) { - x = 1; - } else if (currentAxis == Vector3f.UNIT_Y) { - y = 1; - } else if (currentAxis == Vector3f.UNIT_Z) { - z = 1; - } - Vector3f axis = new Vector3f(x, y, z); - Quaternion initialRot = selected.getLocalRotation().clone(); - Quaternion rot = new Quaternion(); - rot = rot.fromAngleAxis(value * FastMath.DEG_TO_RAD, axis); - selected.setLocalRotation(selected.getLocalRotation().mult(rot)); - RotateUndo undo = new RotateUndo(selected, initialRot, rot); - actionPerformed(undo); - toolController.updateSelection(null);// force a re-draw of the bbox shape - toolController.updateSelection(selected); - - } - clearState(false); - } - - private void checkModificatorKeys(KeyInputEvent kie) { - if (kie.getKeyCode() == KeyInput.KEY_LCONTROL || kie.getKeyCode() == KeyInput.KEY_RCONTROL) { - ctrlDown = kie.isPressed(); - } - - if (kie.getKeyCode() == KeyInput.KEY_LSHIFT || kie.getKeyCode() == KeyInput.KEY_RSHIFT) { - shiftDown = kie.isPressed(); - } - - if (kie.getKeyCode() == KeyInput.KEY_LMENU || kie.getKeyCode() == KeyInput.KEY_RMENU) { - altDown = kie.isPressed(); - } - } - - private boolean checkCommandKey(KeyInputEvent kie) { - if (kie.getKeyCode() == KeyInput.KEY_D) { - if (shiftDown) { - duplicateSelected(); - return true; - } - } - // X will only delete if the user isn't already transforming - if (currentState == null && kie.getKeyCode() == KeyInput.KEY_X) { - if (!ctrlDown && !shiftDown) { - deleteSelected(); - return true; - } - } - return false; - } - - private boolean checkStateKey(KeyInputEvent kie) { - Spatial selected = toolController.getSelectedSpatial(); - if (kie.getKeyCode() == KeyInput.KEY_G && !ctrlDown) { - currentState = State.translate; - MoveManager moveManager = Lookup.getDefault().lookup(MoveManager.class); - moveManager.reset(); - Quaternion rot = camera.getRotation().mult(new Quaternion().fromAngleAxis(FastMath.PI, Vector3f.UNIT_Y)); - moveManager.initiateMove(selected, rot, false); - moving = moveManager.makeUndo(); - return true; - } else if (kie.getKeyCode() == KeyInput.KEY_R && !ctrlDown) { - currentState = State.rotate; - return true; - } else if (kie.getKeyCode() == KeyInput.KEY_S && !ctrlDown) { - currentState = State.scale; - return true; - } - return false; - } - - private boolean checkAxisKey(KeyInputEvent kie) { - if (kie.getKeyCode() == KeyInput.KEY_X) { - currentAxis = Vector3f.UNIT_X; - checkMovePlane(MoveManager.XY, MoveManager.XZ); - return true; - } else if (kie.getKeyCode() == KeyInput.KEY_Y) { - currentAxis = Vector3f.UNIT_Y; - checkMovePlane(MoveManager.XY, MoveManager.YZ); - return true; - } else if (kie.getKeyCode() == KeyInput.KEY_Z) { - currentAxis = Vector3f.UNIT_Z; - checkMovePlane(MoveManager.XZ, MoveManager.YZ); - return true; - } - return false; - } - - private void checkMovePlane(Quaternion rot1, Quaternion rot2) { - if (currentState == State.translate) { - MoveManager moveManager = Lookup.getDefault().lookup(MoveManager.class); - Quaternion rot = camera.getRotation().mult(new Quaternion().fromAngleAxis(FastMath.PI, Vector3f.UNIT_Y)); - Quaternion planRot = null; - if (rot.dot(rot1) < rot.dot(rot2)) { - planRot = rot1; - } else { - planRot = rot2; - } - moveManager.updatePlaneRotation(planRot); - } - } - - private boolean checkNumberKey(KeyInputEvent kie) { - if (kie.getKeyCode() == KeyInput.KEY_MINUS) { - if (numberBuilder.length() > 0) { - if (numberBuilder.charAt(0) == '-') { - numberBuilder.replace(0, 1, ""); - } else { - numberBuilder.insert(0, '-'); - } - } else { - numberBuilder.append('-'); - } - return true; - } else if (kie.getKeyCode() == KeyInput.KEY_0 || kie.getKeyCode() == KeyInput.KEY_NUMPAD0) { - numberBuilder.append('0'); - return true; - } else if (kie.getKeyCode() == KeyInput.KEY_1 || kie.getKeyCode() == KeyInput.KEY_NUMPAD1) { - numberBuilder.append('1'); - return true; - } else if (kie.getKeyCode() == KeyInput.KEY_2 || kie.getKeyCode() == KeyInput.KEY_NUMPAD2) { - numberBuilder.append('2'); - return true; - } else if (kie.getKeyCode() == KeyInput.KEY_3 || kie.getKeyCode() == KeyInput.KEY_NUMPAD3) { - numberBuilder.append('3'); - return true; - } else if (kie.getKeyCode() == KeyInput.KEY_4 || kie.getKeyCode() == KeyInput.KEY_NUMPAD4) { - numberBuilder.append('4'); - return true; - } else if (kie.getKeyCode() == KeyInput.KEY_5 || kie.getKeyCode() == KeyInput.KEY_NUMPAD5) { - numberBuilder.append('5'); - return true; - } else if (kie.getKeyCode() == KeyInput.KEY_6 || kie.getKeyCode() == KeyInput.KEY_NUMPAD6) { - numberBuilder.append('6'); - return true; - } else if (kie.getKeyCode() == KeyInput.KEY_7 || kie.getKeyCode() == KeyInput.KEY_NUMPAD7) { - numberBuilder.append('7'); - return true; - } else if (kie.getKeyCode() == KeyInput.KEY_8 || kie.getKeyCode() == KeyInput.KEY_NUMPAD8) { - numberBuilder.append('8'); - return true; - } else if (kie.getKeyCode() == KeyInput.KEY_9 || kie.getKeyCode() == KeyInput.KEY_NUMPAD9) { - numberBuilder.append('9'); - return true; - } else if (kie.getKeyCode() == KeyInput.KEY_PERIOD) { - if (numberBuilder.indexOf(".") == -1) { // if it doesn't exist yet - if (numberBuilder.length() == 0 - || (numberBuilder.length() == 1 && numberBuilder.charAt(0) == '-')) { - numberBuilder.append("0."); - } else { - numberBuilder.append("."); - } - } - return true; - } - - return false; - } - - private boolean checkEnterHit(KeyInputEvent kie) { - if (kie.getKeyCode() == KeyInput.KEY_RETURN) { - return true; - } - return false; - } - - private boolean checkEscHit(KeyInputEvent kie) { - if (kie.getKeyCode() == KeyInput.KEY_ESCAPE) { - return true; - } - return false; - } - @Override public void actionPrimary(Vector2f screenCoord, boolean pressed, final JmeNode rootNode, DataObject dataObject) { - if (!pressed) { - Spatial selected = toolController.getSelectedSpatial(); - // left mouse released - if (!wasDraggingL) { - // left mouse pressed - if (currentState != null) { - // finish manipulating the spatial - if (moving != null) { - moving.setAfter(selected.getLocalTranslation()); - actionPerformed(moving); - moving = null; - clearState(false); - } else if (scaling != null) { - scaling.after = selected.getLocalScale().clone(); - actionPerformed(scaling); - scaling = null; - clearState(false); - toolController.rebuildSelectionBox(); - } else if (rotating != null) { - rotating.after = selected.getLocalRotation().clone(); - actionPerformed(rotating); - rotating = null; - clearState(false); - } - } else { - // mouse released and wasn't dragging, place cursor - final Vector3f result = pickWorldLocation(getCamera(), screenCoord, rootNode); - if (result != null) { - if (toolController.isSnapToGrid()) { - result.set(Math.round(result.x), result.y, Math.round(result.z)); - } - toolController.setCursorLocation(result); - } - } - } - wasDraggingL = false; - } + } @Override @@ -435,19 +61,7 @@ public class SelectTool extends SceneEditTool { Spatial selected = toolController.getSelectedSpatial(); // mouse down - if (moving != null) { - moving.sceneUndo(); - moving = null; - clearState(); - } else if (scaling != null) { - scaling.sceneUndo(); - scaling = null; - clearState(); - } else if (rotating != null) { - rotating.sceneUndo(); - rotating = null; - clearState(); - } else if (!wasDraggingR && !wasDownR) { // wasn't dragging and was not down already + if (!wasDraggingR && !wasDownR) { // wasn't dragging and was not down already // pick on the spot Spatial s = pickWorldSpatial(camera, screenCoord, rootNode); if (!toolController.selectTerrain() && isTerrain(s)) { @@ -498,8 +112,8 @@ public class SelectTool extends SceneEditTool { } /** - * Climb up the spatial until we find the first node parent. - * TODO: use userData to determine the actual model's parent. + * Climb up the spatial until we find the first node parent. TODO: use + * userData to determine the actual model's parent. */ private Spatial findModelNodeParent(Spatial child) { if (child == null) { @@ -519,14 +133,10 @@ public class SelectTool extends SceneEditTool { @Override public void mouseMoved(Vector2f screenCoord, JmeNode rootNode, DataObject currentDataObject, JmeSpatial selectedSpatial) { - if (currentState != null) { - handleMouseManipulate(screenCoord, currentState, currentAxis, rootNode, currentDataObject, selectedSpatial); - } } @Override public void draggedPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) { - wasDraggingL = pressed; } @Override @@ -535,252 +145,8 @@ public class SelectTool extends SceneEditTool { } /** - * Manipulate the spatial - */ - private void handleMouseManipulate(Vector2f screenCoord, - State state, - Vector3f axis, - JmeNode rootNode, - DataObject currentDataObject, - JmeSpatial selectedSpatial) { - if (state == State.translate) { - doMouseTranslate(axis, screenCoord, rootNode, selectedSpatial); - } else if (state == State.scale) { - doMouseScale(axis, screenCoord, rootNode, selectedSpatial); - } else if (state == State.rotate) { - doMouseRotate(axis, screenCoord, rootNode, selectedSpatial); - } - - } - - private void doMouseTranslate(Vector3f axis, Vector2f screenCoord, JmeNode rootNode, JmeSpatial selectedSpatial) { - MoveManager moveManager = Lookup.getDefault().lookup(MoveManager.class); - if (toolController.isSnapToScene()) { - moveManager.setAlternativePickTarget(rootNode.getLookup().lookup(Node.class)); - } - // free form translation - moveManager.move(camera, screenCoord, axis, toolController.isSnapToGrid()); - } - - private void doMouseScale(Vector3f axis, Vector2f screenCoord, JmeNode rootNode, JmeSpatial selectedSpatial) { - Spatial selected = toolController.getSelectedSpatial(); - // scale based on the original mouse position and original model-to-screen position - // and compare that to the distance from the new mouse position and the original distance - if (startMouseCoord == null) { - startMouseCoord = screenCoord.clone(); - } - if (startSelectedCoord == null) { - Vector3f screen = getCamera().getScreenCoordinates(selected.getWorldTranslation()); - startSelectedCoord = new Vector2f(screen.x, screen.y); - } - - if (scaling == null) { - scaling = new ScaleUndo(selected, selected.getLocalScale().clone(), null); - } - - float origDist = startMouseCoord.distanceSquared(startSelectedCoord); - float newDist = screenCoord.distanceSquared(startSelectedCoord); - if (origDist == 0) { - origDist = 1; - } - float ratio = newDist / origDist; - Vector3f prev = selected.getLocalScale(); - if (axis == Vector3f.UNIT_X) { - selected.setLocalScale(ratio, prev.y, prev.z); - } else if (axis == Vector3f.UNIT_Y) { - selected.setLocalScale(prev.x, ratio, prev.z); - } else if (axis == Vector3f.UNIT_Z) { - selected.setLocalScale(prev.x, prev.y, ratio); - } else { - selected.setLocalScale(ratio, ratio, ratio); - } - } - - private void doMouseRotate(Vector3f axis, Vector2f screenCoord, JmeNode rootNode, JmeSpatial selectedSpatial) { - Spatial selected = toolController.getSelectedSpatial(); - if (startMouseCoord == null) { - startMouseCoord = screenCoord.clone(); - } - if (startSelectedCoord == null) { - Vector3f screen = getCamera().getScreenCoordinates(selected.getWorldTranslation()); - startSelectedCoord = new Vector2f(screen.x, screen.y); - } - - if (rotating == null) { - rotating = new RotateUndo(selected, selected.getLocalRotation().clone(), null); - } - - Vector2f origRot = startMouseCoord.subtract(startSelectedCoord); - Vector2f newRot = screenCoord.subtract(startSelectedCoord); - float newRotAngle = origRot.angleBetween(newRot); - float temp = newRotAngle; - - if (lastRotAngle != 0) { - newRotAngle -= lastRotAngle; - } - - lastRotAngle = temp; - - Quaternion rotate = new Quaternion(); - if (axis != Vector3f.UNIT_XYZ) { - rotate = rotate.fromAngleAxis(newRotAngle, selected.getWorldRotation().inverse().mult(axis)); - } else { - rotate = rotate.fromAngleAxis(newRotAngle, selected.getWorldRotation().inverse().mult(getCamera().getDirection().mult(-1).normalizeLocal())); - } - selected.setLocalRotation(selected.getLocalRotation().mult(rotate)); - - - } - - private void duplicateSelected() { - Spatial selected = toolController.getSelectedSpatial(); - if (selected == null) { - return; - } - Spatial clone = selected.clone(); - clone.move(1, 0, 1); - - selected.getParent().attachChild(clone); - actionPerformed(new DuplicateUndo(clone, selected.getParent())); - selected = clone; - final Spatial cloned = clone; - final JmeNode rootNode = toolController.getRootNode(); - refreshSelected(rootNode, selected.getParent()); - - java.awt.EventQueue.invokeLater(new Runnable() { - - @Override - public void run() { - if (cloned != null) { - SceneViewerTopComponent.findInstance().setActivatedNodes(new org.openide.nodes.Node[]{rootNode.getChild(cloned)}); - SceneExplorerTopComponent.findInstance().setSelectedNode(rootNode.getChild(cloned)); - } - } - }); - - // set to automatically 'grab'/'translate' the new cloned model - toolController.updateSelection(selected); - currentState = State.translate; - currentAxis = Vector3f.UNIT_XYZ; - } - - private void deleteSelected() { - Spatial selected = toolController.getSelectedSpatial(); - if (selected == null) { - return; - } - Node parent = selected.getParent(); - selected.removeFromParent(); - actionPerformed(new DeleteUndo(selected, parent)); - - selected = null; - toolController.updateSelection(selected); - - final JmeNode rootNode = toolController.getRootNode(); - refreshSelected(rootNode, parent); - } - - private void refreshSelected(final JmeNode jmeRootNode, final Node parent) { - java.awt.EventQueue.invokeLater(new Runnable() { - - @Override - public void run() { - jmeRootNode.getChild(parent).refresh(false); - } - }); - } - - private class ScaleUndo extends AbstractUndoableSceneEdit { - - private Spatial spatial; - private Vector3f before, after; - - ScaleUndo(Spatial spatial, Vector3f before, Vector3f after) { - this.spatial = spatial; - this.before = before; - this.after = after; - } - - @Override - public void sceneUndo() { - spatial.setLocalScale(before); - } - - @Override - public void sceneRedo() { - spatial.setLocalScale(after); - } - } - - private class RotateUndo extends AbstractUndoableSceneEdit { - - private Spatial spatial; - private Quaternion before, after; - - RotateUndo(Spatial spatial, Quaternion before, Quaternion after) { - this.spatial = spatial; - this.before = before; - this.after = after; - } - - @Override - public void sceneUndo() { - spatial.setLocalRotation(before); - } - - @Override - public void sceneRedo() { - spatial.setLocalRotation(after); - } - } - - private class DeleteUndo extends AbstractUndoableSceneEdit { - - private Spatial spatial; - private Node parent; - - DeleteUndo(Spatial spatial, Node parent) { - this.spatial = spatial; - this.parent = parent; - } - - @Override - public void sceneUndo() { - parent.attachChild(spatial); - } - - @Override - public void sceneRedo() { - spatial.removeFromParent(); - } - } - - private class DuplicateUndo extends AbstractUndoableSceneEdit { - - private Spatial spatial; - private Node parent; - - DuplicateUndo(Spatial spatial, Node parent) { - this.spatial = spatial; - this.parent = parent; - } - - @Override - public void sceneUndo() { - spatial.removeFromParent(); - } - - @Override - public void sceneRedo() { - parent.attachChild(spatial); - } - } - - /** - * Check if the selected item is a Terrain - * It will climb up the parent tree to see if - * a parent is terrain too. - * Recursive call. + * Check if the selected item is a Terrain It will climb up the parent tree + * to see if a parent is terrain too. Recursive call. */ protected boolean isTerrain(Spatial s) { if (s == null) { diff --git a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/DeleteShortcut.java b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/DeleteShortcut.java new file mode 100644 index 000000000..cc13ece1d --- /dev/null +++ b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/DeleteShortcut.java @@ -0,0 +1,123 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.jme3.gde.scenecomposer.tools.shortcuts; + +import com.jme3.asset.AssetManager; +import com.jme3.gde.core.sceneexplorer.SceneExplorerTopComponent; +import com.jme3.gde.core.sceneexplorer.nodes.JmeNode; +import com.jme3.gde.core.sceneexplorer.nodes.JmeSpatial; +import com.jme3.gde.core.sceneviewer.SceneViewerTopComponent; +import com.jme3.gde.core.undoredo.AbstractUndoableSceneEdit; +import com.jme3.gde.scenecomposer.SceneComposerToolController; +import com.jme3.input.KeyInput; +import com.jme3.input.event.KeyInputEvent; +import com.jme3.math.Vector2f; +import com.jme3.scene.Node; +import com.jme3.scene.Spatial; +import org.openide.loaders.DataObject; +import org.openide.util.Lookup; + +/** + * + * @author dokthar + */ +public class DeleteShortcut extends ShortcutTool { + + @Override + public boolean isActivableBy(KeyInputEvent kie) { + if (kie.getKeyCode() == KeyInput.KEY_X && kie.isPressed()) { + if (Lookup.getDefault().lookup(ShortcutManager.class).isShiftDown()) { + return true; + } + } + return false; + } + + @Override + public void cancel() { + terminate(); + } + + @Override + public void activate(AssetManager manager, Node toolNode, Node onTopToolNode, Spatial selectedSpatial, SceneComposerToolController toolController) { + super.activate(manager, toolNode, onTopToolNode, selectedSpatial, toolController); //To change body of generated methods, choose Tools | Templates. + hideMarker(); + if (selectedSpatial != null) { + delete(); + } + terminate(); + } + + private void delete() { + Spatial selected = toolController.getSelectedSpatial(); + + Node parent = selected.getParent(); + selected.removeFromParent(); + actionPerformed(new DeleteUndo(selected, parent)); + + selected = null; + toolController.updateSelection(selected); + + final JmeNode rootNode = toolController.getRootNode(); + refreshSelected(rootNode, parent); + } + + private void refreshSelected(final JmeNode jmeRootNode, final Node parent) { + java.awt.EventQueue.invokeLater(new Runnable() { + + @Override + public void run() { + jmeRootNode.getChild(parent).refresh(false); + } + }); + } + + @Override + public void keyPressed(KeyInputEvent kie) { + + } + + @Override + public void actionPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) { + } + + @Override + public void actionSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) { + } + + @Override + public void mouseMoved(Vector2f screenCoord, JmeNode rootNode, DataObject dataObject, JmeSpatial selectedSpatial) { + } + + @Override + public void draggedPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) { + } + + @Override + public void draggedSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) { + } + + private class DeleteUndo extends AbstractUndoableSceneEdit { + + private Spatial spatial; + private Node parent; + + DeleteUndo(Spatial spatial, Node parent) { + this.spatial = spatial; + this.parent = parent; + } + + @Override + public void sceneUndo() { + parent.attachChild(spatial); + } + + @Override + public void sceneRedo() { + spatial.removeFromParent(); + } + } +} diff --git a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/DuplicateShortcut.java b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/DuplicateShortcut.java new file mode 100644 index 000000000..d98eb6ee9 --- /dev/null +++ b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/DuplicateShortcut.java @@ -0,0 +1,141 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.jme3.gde.scenecomposer.tools.shortcuts; + +import com.jme3.asset.AssetManager; +import com.jme3.gde.core.sceneexplorer.SceneExplorerTopComponent; +import com.jme3.gde.core.sceneexplorer.nodes.JmeNode; +import com.jme3.gde.core.sceneexplorer.nodes.JmeSpatial; +import com.jme3.gde.core.sceneviewer.SceneViewerTopComponent; +import com.jme3.gde.core.undoredo.AbstractUndoableSceneEdit; +import com.jme3.gde.scenecomposer.SceneComposerToolController; +import com.jme3.input.KeyInput; +import com.jme3.input.event.KeyInputEvent; +import com.jme3.math.Vector2f; +import com.jme3.scene.Node; +import com.jme3.scene.Spatial; +import org.openide.loaders.DataObject; +import org.openide.util.Lookup; + +/** + * + * @author dokthar + */ +public class DuplicateShortcut extends ShortcutTool { + + @Override + public boolean isActivableBy(KeyInputEvent kie) { + if (kie.getKeyCode() == KeyInput.KEY_D && kie.isPressed()) { + if (Lookup.getDefault().lookup(ShortcutManager.class).isShiftDown()) { + return true; + } + } + return false; + } + + @Override + public void cancel() { + terminate(); + } + + @Override + public void activate(AssetManager manager, Node toolNode, Node onTopToolNode, Spatial selectedSpatial, SceneComposerToolController toolController) { + super.activate(manager, toolNode, onTopToolNode, selectedSpatial, toolController); //To change body of generated methods, choose Tools | Templates. + hideMarker(); + if (selectedSpatial != null) { + duplicate(); + terminate(); + + //then enable move shortcut + toolController.doKeyPressed(new KeyInputEvent(KeyInput.KEY_G, 'g', true, false)); + } else { + terminate(); + } + } + + private void duplicate() { + Spatial selected = toolController.getSelectedSpatial(); + + Spatial clone = selected.clone(); + clone.move(1, 0, 1); + + selected.getParent().attachChild(clone); + actionPerformed(new DuplicateUndo(clone, selected.getParent())); + selected = clone; + final Spatial cloned = clone; + final JmeNode rootNode = toolController.getRootNode(); + refreshSelected(rootNode, selected.getParent()); + + java.awt.EventQueue.invokeLater(new Runnable() { + + @Override + public void run() { + if (cloned != null) { + SceneViewerTopComponent.findInstance().setActivatedNodes(new org.openide.nodes.Node[]{rootNode.getChild(cloned)}); + SceneExplorerTopComponent.findInstance().setSelectedNode(rootNode.getChild(cloned)); + } + } + }); + + toolController.updateSelection(selected); + } + + private void refreshSelected(final JmeNode jmeRootNode, final Node parent) { + java.awt.EventQueue.invokeLater(new Runnable() { + + @Override + public void run() { + jmeRootNode.getChild(parent).refresh(false); + } + }); + } + + @Override + public void keyPressed(KeyInputEvent kie) { + + } + + @Override + public void actionPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) { + } + + @Override + public void actionSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) { + } + + @Override + public void mouseMoved(Vector2f screenCoord, JmeNode rootNode, DataObject dataObject, JmeSpatial selectedSpatial) { + } + + @Override + public void draggedPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) { + } + + @Override + public void draggedSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) { + } + + private class DuplicateUndo extends AbstractUndoableSceneEdit { + + private Spatial spatial; + private Node parent; + + DuplicateUndo(Spatial spatial, Node parent) { + this.spatial = spatial; + this.parent = parent; + } + + @Override + public void sceneUndo() { + spatial.removeFromParent(); + } + + @Override + public void sceneRedo() { + parent.attachChild(spatial); + } + } +} diff --git a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/MoveShortcut.java b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/MoveShortcut.java new file mode 100644 index 000000000..6291ab932 --- /dev/null +++ b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/MoveShortcut.java @@ -0,0 +1,227 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.jme3.gde.scenecomposer.tools.shortcuts; + +import com.jme3.asset.AssetManager; +import com.jme3.bullet.control.CharacterControl; +import com.jme3.bullet.control.RigidBodyControl; +import com.jme3.gde.core.sceneexplorer.nodes.JmeNode; +import com.jme3.gde.core.sceneexplorer.nodes.JmeSpatial; +import com.jme3.gde.core.undoredo.AbstractUndoableSceneEdit; +import com.jme3.gde.scenecomposer.SceneComposerToolController; +import com.jme3.gde.scenecomposer.tools.PickManager; +import com.jme3.input.KeyInput; +import com.jme3.input.event.KeyInputEvent; +import com.jme3.math.Vector2f; +import com.jme3.math.Vector3f; +import com.jme3.scene.Node; +import com.jme3.scene.Spatial; +import org.openide.loaders.DataObject; +import org.openide.util.Lookup; + +/** + * + * @author dokthar + */ +public class MoveShortcut extends ShortcutTool { + + private Vector3f currentAxis; + private StringBuilder numberBuilder; + private Spatial spatial; + private PickManager pickManager; + private boolean pickEnabled; + private Vector3f startPosition; + private Vector3f finalPosition; + + @Override + + public boolean isActivableBy(KeyInputEvent kie) { + return kie.getKeyCode() == KeyInput.KEY_G; + } + + @Override + public void cancel() { + spatial.setLocalTranslation(startPosition); + terminate(); + } + + private void apply() { + actionPerformed(new MoveUndo(toolController.getSelectedSpatial(), startPosition, finalPosition)); + terminate(); + } + + private void init(Spatial selectedSpatial) { + spatial = selectedSpatial; + startPosition = spatial.getLocalTranslation().clone(); + currentAxis = Vector3f.UNIT_XYZ; + pickManager = Lookup.getDefault().lookup(PickManager.class); + pickEnabled = false; + } + + @Override + public void activate(AssetManager manager, Node toolNode, Node onTopToolNode, Spatial selectedSpatial, SceneComposerToolController toolController) { + super.activate(manager, toolNode, onTopToolNode, selectedSpatial, toolController); //To change body of generated methods, choose Tools | Templates. + hideMarker(); + numberBuilder = new StringBuilder(); + if (selectedSpatial == null) { + terminate(); + } else { + init(selectedSpatial); + } + } + + @Override + public void keyPressed(KeyInputEvent kie) { + if (kie.isPressed()) { + Lookup.getDefault().lookup(ShortcutManager.class).activateShortcut(kie); + + Vector3f axis = new Vector3f(); + boolean axisChanged = ShortcutManager.checkAxisKey(kie, axis); + if (axisChanged) { + currentAxis = axis; + } + boolean numberChanged = ShortcutManager.checkNumberKey(kie, numberBuilder); + boolean enterHit = ShortcutManager.checkEnterHit(kie); + boolean escHit = ShortcutManager.checkEscHit(kie); + + if (escHit) { + cancel(); + } else if (enterHit) { + apply(); + } else if (axisChanged && pickEnabled) { + //update pick manager + + if (currentAxis.equals(Vector3f.UNIT_X)) { + pickManager.setTransformation(PickManager.PLANE_XY, getTransformType(), camera); + } else if (currentAxis.equals(Vector3f.UNIT_Y)) { + pickManager.setTransformation(PickManager.PLANE_YZ, getTransformType(), camera); + } else if (currentAxis.equals(Vector3f.UNIT_Z)) { + pickManager.setTransformation(PickManager.PLANE_XZ, getTransformType(), camera); + } + } else if (axisChanged || numberChanged) { + //update transformation + float number = ShortcutManager.getNumberKey(numberBuilder); + Vector3f translation = currentAxis.mult(number); + finalPosition = startPosition.add(translation); + spatial.setLocalTranslation(finalPosition); + + } + + } + } + + @Override + public void actionPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) { + if (pressed) { + apply(); + } + } + + @Override + public void actionSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) { + if (pressed) { + cancel(); + } + } + + @Override + public void mouseMoved(Vector2f screenCoord, JmeNode rootNode, DataObject dataObject, JmeSpatial selectedSpatial) { + + if (!pickEnabled) { + if (currentAxis.equals(Vector3f.UNIT_XYZ)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), camera.getRotation(), SceneComposerToolController.TransformationType.camera, camera, screenCoord); + pickEnabled = true; + } else if (currentAxis.equals(Vector3f.UNIT_X)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), PickManager.PLANE_XY, getTransformType(), camera, screenCoord); + pickEnabled = true; + } else if (currentAxis.equals(Vector3f.UNIT_Y)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), PickManager.PLANE_YZ, getTransformType(), camera, screenCoord); + pickEnabled = true; + } else if (currentAxis.equals(Vector3f.UNIT_Z)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), PickManager.PLANE_XZ, getTransformType(), camera, screenCoord); + pickEnabled = true; + } else { + return; + } + } + + if (pickManager.updatePick(camera, screenCoord)) { + //pick update success + Vector3f diff; + + if (currentAxis.equals(Vector3f.UNIT_XYZ)) { + diff = pickManager.getTranslation(); + } else { + diff = pickManager.getTranslation(currentAxis); + } + Vector3f position = startPosition.add(diff); + finalPosition = position; + toolController.getSelectedSpatial().setLocalTranslation(position); + updateToolsTransformation(); + } + } + + @Override + public void draggedPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) { + if (pressed) { + apply(); + } + } + + @Override + public void draggedSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) { + if (pressed) { + cancel(); + } + } + + private class MoveUndo extends AbstractUndoableSceneEdit { + + private Spatial spatial; + private Vector3f before = new Vector3f(), after = new Vector3f(); + + MoveUndo(Spatial spatial, Vector3f before, Vector3f after) { + this.spatial = spatial; + this.before.set(before); + if (after != null) { + this.after.set(after); + } + } + + @Override + public void sceneUndo() { + spatial.setLocalTranslation(before); + RigidBodyControl control = spatial.getControl(RigidBodyControl.class); + if (control != null) { + control.setPhysicsLocation(spatial.getWorldTranslation()); + } + CharacterControl character = spatial.getControl(CharacterControl.class); + if (character != null) { + character.setPhysicsLocation(spatial.getWorldTranslation()); + } + // toolController.selectedSpatialTransformed(); + } + + @Override + public void sceneRedo() { + spatial.setLocalTranslation(after); + RigidBodyControl control = spatial.getControl(RigidBodyControl.class); + if (control != null) { + control.setPhysicsLocation(spatial.getWorldTranslation()); + } + CharacterControl character = spatial.getControl(CharacterControl.class); + if (character != null) { + character.setPhysicsLocation(spatial.getWorldTranslation()); + } + //toolController.selectedSpatialTransformed(); + } + + public void setAfter(Vector3f after) { + this.after.set(after); + } + } + +} diff --git a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/RotateShortcut.java b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/RotateShortcut.java new file mode 100644 index 000000000..8b9ffe404 --- /dev/null +++ b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/RotateShortcut.java @@ -0,0 +1,189 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.jme3.gde.scenecomposer.tools.shortcuts; + +import com.jme3.asset.AssetManager; +import com.jme3.gde.core.sceneexplorer.nodes.JmeNode; +import com.jme3.gde.core.sceneexplorer.nodes.JmeSpatial; +import com.jme3.gde.core.undoredo.AbstractUndoableSceneEdit; +import com.jme3.gde.scenecomposer.SceneComposerToolController; +import com.jme3.gde.scenecomposer.tools.PickManager; +import com.jme3.input.KeyInput; +import com.jme3.input.event.KeyInputEvent; +import com.jme3.math.Quaternion; +import com.jme3.math.Vector2f; +import com.jme3.math.Vector3f; +import com.jme3.scene.Node; +import com.jme3.scene.Spatial; +import org.openide.loaders.DataObject; +import org.openide.util.Lookup; + +/** + * + * @author dokthar + */ +public class RotateShortcut extends ShortcutTool { + + private Vector3f currentAxis; + private StringBuilder numberBuilder; + private Spatial spatial; + private PickManager pickManager; + private boolean pickEnabled; + private Quaternion startRotation; + private Quaternion finalRotation; + + @Override + + public boolean isActivableBy(KeyInputEvent kie) { + return kie.getKeyCode() == KeyInput.KEY_R; + } + + @Override + public void cancel() { + spatial.setLocalRotation(startRotation); + terminate(); + } + + private void apply() { + actionPerformed(new RotateUndo(toolController.getSelectedSpatial(), startRotation, finalRotation)); + terminate(); + } + + private void init(Spatial selectedSpatial) { + spatial = selectedSpatial; + startRotation = spatial.getLocalRotation().clone(); + currentAxis = Vector3f.UNIT_XYZ; + pickManager = Lookup.getDefault().lookup(PickManager.class); + pickEnabled = false; + } + + @Override + public void activate(AssetManager manager, Node toolNode, Node onTopToolNode, Spatial selectedSpatial, SceneComposerToolController toolController) { + super.activate(manager, toolNode, onTopToolNode, selectedSpatial, toolController); //To change body of generated methods, choose Tools | Templates. + hideMarker(); + numberBuilder = new StringBuilder(); + if (selectedSpatial == null) { + terminate(); + } else { + init(selectedSpatial); + } + } + + @Override + public void keyPressed(KeyInputEvent kie) { + if (kie.isPressed()) { + Lookup.getDefault().lookup(ShortcutManager.class).activateShortcut(kie); + + Vector3f axis = new Vector3f(); + boolean axisChanged = ShortcutManager.checkAxisKey(kie, axis); + if (axisChanged) { + currentAxis = axis; + } + boolean numberChanged = ShortcutManager.checkNumberKey(kie, numberBuilder); + boolean enterHit = ShortcutManager.checkEnterHit(kie); + boolean escHit = ShortcutManager.checkEscHit(kie); + + if (escHit) { + cancel(); + } else if (enterHit) { + apply(); + } else if (axisChanged && pickEnabled) { + pickEnabled = false; + spatial.setLocalRotation(startRotation.clone()); + } else if (axisChanged || numberChanged) { + //update transformation + /* float number = ShortcutManager.getNumberKey(numberBuilder); + Vector3f translation = currentAxis.mult(number); + finalPosition = startPosition.add(translation); + spatial.setLocalTranslation(finalPosition); + */ + } + + } + } + + @Override + public void actionPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) { + if (pressed) { + apply(); + } + } + + @Override + public void actionSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) { + if (pressed) { + cancel(); + } + } + + @Override + public void mouseMoved(Vector2f screenCoord, JmeNode rootNode, DataObject dataObject, JmeSpatial selectedSpatial) { + + if (!pickEnabled) { + if (currentAxis.equals(Vector3f.UNIT_XYZ)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), camera.getRotation(), SceneComposerToolController.TransformationType.camera, camera, screenCoord); + pickEnabled = true; + } else if (currentAxis.equals(Vector3f.UNIT_X)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), PickManager.PLANE_YZ, getTransformType(), camera, screenCoord); + pickEnabled = true; + } else if (currentAxis.equals(Vector3f.UNIT_Y)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), PickManager.PLANE_XZ, getTransformType(), camera, screenCoord); + pickEnabled = true; + } else if (currentAxis.equals(Vector3f.UNIT_Z)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), PickManager.PLANE_XY, getTransformType(), camera, screenCoord); + pickEnabled = true; + } else { + return; + } + } + + if (pickManager.updatePick(camera, screenCoord)) { + + Quaternion rotation = startRotation.mult(pickManager.getRotation(startRotation.inverse())); + toolController.getSelectedSpatial().setLocalRotation(rotation); + finalRotation = rotation; + updateToolsTransformation(); + } + } + + @Override + public void draggedPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) { + if (pressed) { + apply(); + } + } + + @Override + public void draggedSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) { + if (pressed) { + cancel(); + } + } + + private class RotateUndo extends AbstractUndoableSceneEdit { + + private Spatial spatial; + private Quaternion before, after; + + RotateUndo(Spatial spatial, Quaternion before, Quaternion after) { + this.spatial = spatial; + this.before = before; + this.after = after; + } + + @Override + public void sceneUndo() { + spatial.setLocalRotation(before); + toolController.selectedSpatialTransformed(); + } + + @Override + public void sceneRedo() { + spatial.setLocalRotation(after); + toolController.selectedSpatialTransformed(); + } + } +} diff --git a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/ScaleShortcut.java b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/ScaleShortcut.java new file mode 100644 index 000000000..8fa18858f --- /dev/null +++ b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/ScaleShortcut.java @@ -0,0 +1,199 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.jme3.gde.scenecomposer.tools.shortcuts; + +import com.jme3.asset.AssetManager; +import com.jme3.gde.core.sceneexplorer.nodes.JmeNode; +import com.jme3.gde.core.sceneexplorer.nodes.JmeSpatial; +import com.jme3.gde.core.undoredo.AbstractUndoableSceneEdit; +import com.jme3.gde.scenecomposer.SceneComposerToolController; +import com.jme3.gde.scenecomposer.tools.PickManager; +import com.jme3.input.KeyInput; +import com.jme3.input.event.KeyInputEvent; +import com.jme3.math.Quaternion; +import com.jme3.math.Vector2f; +import com.jme3.math.Vector3f; +import com.jme3.scene.Node; +import com.jme3.scene.Spatial; +import org.openide.loaders.DataObject; +import org.openide.util.Lookup; + +/** + * + * @author dokthar + */ +public class ScaleShortcut extends ShortcutTool { + + private Vector3f currentAxis; + private StringBuilder numberBuilder; + private Spatial spatial; + private PickManager pickManager; + private boolean pickEnabled; + private Vector3f startScale; + private Vector3f finalScale; + + @Override + + public boolean isActivableBy(KeyInputEvent kie) { + return kie.getKeyCode() == KeyInput.KEY_S; + } + + @Override + public void cancel() { + spatial.setLocalScale(startScale); + terminate(); + } + + private void apply() { + actionPerformed(new ScaleUndo(toolController.getSelectedSpatial(), startScale, finalScale)); + terminate(); + } + + private void init(Spatial selectedSpatial) { + spatial = selectedSpatial; + startScale = spatial.getLocalScale().clone(); + currentAxis = Vector3f.UNIT_XYZ; + pickManager = Lookup.getDefault().lookup(PickManager.class); + pickEnabled = false; + } + + @Override + public void activate(AssetManager manager, Node toolNode, Node onTopToolNode, Spatial selectedSpatial, SceneComposerToolController toolController) { + super.activate(manager, toolNode, onTopToolNode, selectedSpatial, toolController); //To change body of generated methods, choose Tools | Templates. + hideMarker(); + numberBuilder = new StringBuilder(); + if (selectedSpatial == null) { + terminate(); + } else { + init(selectedSpatial); + } + } + + @Override + public void keyPressed(KeyInputEvent kie) { + if (kie.isPressed()) { + Lookup.getDefault().lookup(ShortcutManager.class).activateShortcut(kie); + + Vector3f axis = new Vector3f(); + boolean axisChanged = ShortcutManager.checkAxisKey(kie, axis); + if (axisChanged) { + currentAxis = axis; + } + boolean numberChanged = ShortcutManager.checkNumberKey(kie, numberBuilder); + boolean enterHit = ShortcutManager.checkEnterHit(kie); + boolean escHit = ShortcutManager.checkEscHit(kie); + + if (escHit) { + cancel(); + } else if (enterHit) { + apply(); + } else if (axisChanged && pickEnabled) { + pickEnabled = false; + } else if (axisChanged || numberChanged) { + //update transformation + /* float number = ShortcutManager.getNumberKey(numberBuilder); + Vector3f translation = currentAxis.mult(number); + finalPosition = startPosition.add(translation); + spatial.setLocalTranslation(finalPosition); + */ + } + + } + } + + @Override + public void actionPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) { + if (pressed) { + apply(); + } + } + + @Override + public void actionSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) { + if (pressed) { + cancel(); + } + } + + @Override + public void mouseMoved(Vector2f screenCoord, JmeNode rootNode, DataObject dataObject, JmeSpatial selectedSpatial) { + + if (!pickEnabled) { + if (currentAxis.equals(Vector3f.UNIT_XYZ)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), camera.getRotation(), SceneComposerToolController.TransformationType.camera, camera, screenCoord); + pickEnabled = true; + } else if (currentAxis.equals(Vector3f.UNIT_X)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), PickManager.PLANE_XY, getTransformType(), camera, screenCoord); + pickEnabled = true; + } else if (currentAxis.equals(Vector3f.UNIT_Y)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), PickManager.PLANE_YZ, getTransformType(), camera, screenCoord); + pickEnabled = true; + } else if (currentAxis.equals(Vector3f.UNIT_Z)) { + pickManager.initiatePick(toolController.getSelectedSpatial(), PickManager.PLANE_XZ, getTransformType(), camera, screenCoord); + pickEnabled = true; + } else { + return; + } + } + + if (pickManager.updatePick(camera, screenCoord)) { + Vector3f scale = startScale; + if (currentAxis.equals(Vector3f.UNIT_XYZ)) { + Vector3f constraintAxis = pickManager.getStartOffset().normalize(); + float diff = pickManager.getTranslation(constraintAxis).dot(constraintAxis); + diff *= 0.5f; + scale = startScale.add(new Vector3f(diff, diff, diff)); + } else { + // Get the translation in the spatial Space + Quaternion worldToSpatial = toolController.getSelectedSpatial().getWorldRotation().inverse(); + Vector3f diff = pickManager.getTranslation(worldToSpatial.mult(currentAxis)); + diff.multLocal(0.5f); + scale = startScale.add(diff); + } + finalScale = scale; + toolController.getSelectedSpatial().setLocalScale(scale); + updateToolsTransformation(); + } + } + + @Override + public void draggedPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) { + if (pressed) { + apply(); + } + } + + @Override + public void draggedSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) { + if (pressed) { + cancel(); + } + } + + private class ScaleUndo extends AbstractUndoableSceneEdit { + + private Spatial spatial; + private Vector3f before, after; + + ScaleUndo(Spatial spatial, Vector3f before, Vector3f after) { + this.spatial = spatial; + this.before = before; + this.after = after; + } + + @Override + public void sceneUndo() { + spatial.setLocalScale(before); + toolController.selectedSpatialTransformed(); + } + + @Override + public void sceneRedo() { + spatial.setLocalScale(after); + toolController.selectedSpatialTransformed(); + } + } +} diff --git a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/ShortcutManager.java b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/ShortcutManager.java new file mode 100644 index 000000000..187293e92 --- /dev/null +++ b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/ShortcutManager.java @@ -0,0 +1,335 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.jme3.gde.scenecomposer.tools.shortcuts; + +import com.jme3.gde.scenecomposer.SceneEditTool; +import com.jme3.input.KeyInput; +import com.jme3.input.event.KeyInputEvent; +import com.jme3.math.Vector3f; +import java.util.ArrayList; +import org.openide.util.Lookup; +import org.openide.util.lookup.ServiceProvider; + +/** + * + * @author dokthar + */ +@ServiceProvider(service = ShortcutManager.class) +public class ShortcutManager { + + private ShortcutTool currentShortcut; + private ArrayList shortcutList; + private boolean ctrlDown = false; + private boolean shiftDown = false; + private boolean altDown = false; + + public ShortcutManager() { + shortcutList = new ArrayList(); + shortcutList.add(new MoveShortcut()); + shortcutList.add(new RotateShortcut()); + shortcutList.add(new ScaleShortcut()); + shortcutList.add(new DuplicateShortcut()); + shortcutList.add(new DeleteShortcut()); + } + + /* + Methodes + */ + /** + * This MUST be called by the shortcut tool once the modifications are done. + */ + public void terminate() { + currentShortcut = null; + } + + /** + * + * @return true if a shortCutTool is active, else return false. + */ + public boolean isActive() { + return currentShortcut != null; + } + + /** + * @return the ctrlDown + */ + public boolean isCtrlDown() { + return ctrlDown; + } + + /** + * @return the shiftDown + */ + public boolean isShiftDown() { + return shiftDown; + } + + /** + * @return the altDown + */ + public boolean isAltDown() { + return altDown; + } + + /** + * Set the current shortcut to shortcut. cancel the current + * shortcut if it was still active + * + * @param shortcut the ShortCutTool to set + */ + public void setShortCut(ShortcutTool shortcut) { + if (isActive()) { + currentShortcut.cancel(); + } + currentShortcut = shortcut; + } + + /** + * Get the shortcut that can be enable with the given kei, the current + * shortcut cannot be enable twice. This also check for command key used to + * provide isCtrlDown(), isShiftDown() and isAltDown(). + * + * @param kie the KeyInputEvent + * @return the activable shortcut else return null + */ + public ShortcutTool getActivableShortcut(KeyInputEvent kie) { + if (checkCommandeKey(kie)) { + return null; + } + for (ShortcutTool s : shortcutList) { + if (s != currentShortcut) { + if (s.isActivableBy(kie)) { + return s; + } + } + } + return null; + } + + /** + * + * @return the current active shortcut + */ + public ShortcutTool getActiveShortcut() { + return currentShortcut; + } + + /** + * + * @param kie the KeyInputEvent + * @return true if the given Kei can enable a sortcut, else false + */ + public boolean canActivateShortcut(KeyInputEvent kie) { + return getActivableShortcut(kie) != null; + } + + /** + * Set the current shortcut with the shortcut one that can be enable with + * the given key + * + * @param kie the KeyInputEvent + * @return true is the shortcut changed, else false + */ + public boolean activateShortcut(KeyInputEvent kie) { + ShortcutTool newShortcut = getActivableShortcut(kie); + if (newShortcut != null) { + currentShortcut = newShortcut; + } + return newShortcut != null; + } + + /** + * This should be called to trigger the currentShortcut.keyPressed() method. + * This also check for command key used to provide isCtrlDown(), + * isShiftDown() and isAltDown(). + * + * @param kie + */ + public void doKeyPressed(KeyInputEvent kie) { + if (checkCommandeKey(kie)) { + //return; + } else if (isActive()) { + currentShortcut.keyPressed(kie); + } + } + + private boolean checkCommandeKey(KeyInputEvent kie) { + if (checkCtrlHit(kie)) { + ctrlDown = kie.isPressed(); + return true; + } else if (checkAltHit(kie)) { + altDown = kie.isPressed(); + return true; + } else if (checkShiftHit(kie)) { + shiftDown = kie.isPressed(); + return true; + } + return false; + } + + /* + STATIC + */ + /** + * + * @param kie + * @return true if the given kie is KEY_RETURN + */ + public static boolean checkEnterHit(KeyInputEvent kie) { + if (kie.getKeyCode() == KeyInput.KEY_RETURN) { + return true; + } + return false; + } + + /** + * + * @param kie + * @return true if the given kie is KEY_ESCAPE + */ + public static boolean checkEscHit(KeyInputEvent kie) { + if (kie.getKeyCode() == KeyInput.KEY_ESCAPE) { + return true; + } + return false; + } + + /** + * + * @param kie + * @return true if the given kie is KEY_LCONTROL || KEY_RCONTROL + */ + public static boolean checkCtrlHit(KeyInputEvent kie) { + if (kie.getKeyCode() == KeyInput.KEY_LCONTROL || kie.getKeyCode() == KeyInput.KEY_RCONTROL) { + return true; + } + return false; + } + + /** + * + * @param kie + * @return true if the given kie is KEY_LSHIFT || KEY_RSHIFT + */ + public static boolean checkShiftHit(KeyInputEvent kie) { + if (kie.getKeyCode() == KeyInput.KEY_LSHIFT || kie.getKeyCode() == KeyInput.KEY_RSHIFT) { + return true; + } + return false; + } + + /** + * + * @param kie + * @return true if the given kie is KEY_LMENU || KEY_RMENU + */ + public static boolean checkAltHit(KeyInputEvent kie) { + if (kie.getKeyCode() == KeyInput.KEY_LMENU || kie.getKeyCode() == KeyInput.KEY_RMENU) { + return true; + } + return false; + } + + /** + * store the number kie into the numberBuilder + * + * @param kie + * @param numberBuilder + * @return true if the given kie is handled as a number key event + */ + public static boolean checkNumberKey(KeyInputEvent kie, StringBuilder numberBuilder) { + if (kie.getKeyCode() == KeyInput.KEY_MINUS) { + if (numberBuilder.length() > 0) { + if (numberBuilder.charAt(0) == '-') { + numberBuilder.replace(0, 1, ""); + } else { + numberBuilder.insert(0, '-'); + } + } else { + numberBuilder.append('-'); + } + return true; + } else if (kie.getKeyCode() == KeyInput.KEY_0 || kie.getKeyCode() == KeyInput.KEY_NUMPAD0) { + numberBuilder.append('0'); + return true; + } else if (kie.getKeyCode() == KeyInput.KEY_1 || kie.getKeyCode() == KeyInput.KEY_NUMPAD1) { + numberBuilder.append('1'); + return true; + } else if (kie.getKeyCode() == KeyInput.KEY_2 || kie.getKeyCode() == KeyInput.KEY_NUMPAD2) { + numberBuilder.append('2'); + return true; + } else if (kie.getKeyCode() == KeyInput.KEY_3 || kie.getKeyCode() == KeyInput.KEY_NUMPAD3) { + numberBuilder.append('3'); + return true; + } else if (kie.getKeyCode() == KeyInput.KEY_4 || kie.getKeyCode() == KeyInput.KEY_NUMPAD4) { + numberBuilder.append('4'); + return true; + } else if (kie.getKeyCode() == KeyInput.KEY_5 || kie.getKeyCode() == KeyInput.KEY_NUMPAD5) { + numberBuilder.append('5'); + return true; + } else if (kie.getKeyCode() == KeyInput.KEY_6 || kie.getKeyCode() == KeyInput.KEY_NUMPAD6) { + numberBuilder.append('6'); + return true; + } else if (kie.getKeyCode() == KeyInput.KEY_7 || kie.getKeyCode() == KeyInput.KEY_NUMPAD7) { + numberBuilder.append('7'); + return true; + } else if (kie.getKeyCode() == KeyInput.KEY_8 || kie.getKeyCode() == KeyInput.KEY_NUMPAD8) { + numberBuilder.append('8'); + return true; + } else if (kie.getKeyCode() == KeyInput.KEY_9 || kie.getKeyCode() == KeyInput.KEY_NUMPAD9) { + numberBuilder.append('9'); + return true; + } else if (kie.getKeyCode() == KeyInput.KEY_PERIOD) { + if (numberBuilder.indexOf(".") == -1) { // if it doesn't exist yet + if (numberBuilder.length() == 0 + || (numberBuilder.length() == 1 && numberBuilder.charAt(0) == '-')) { + numberBuilder.append("0."); + } else { + numberBuilder.append("."); + } + } + return true; + } + + return false; + } + + /** + * + * @param numberBuilder the StringBuilder storing the float number + * @return the float value created from the given StringBuilder + */ + public static float getNumberKey(StringBuilder numberBuilder) { + if (numberBuilder.length() == 0) { + return 0; + } else { + return new Float(numberBuilder.toString()); + } + } + + /** + * Check for axis input for key X,Y,Z and store the corresponding UNIT_ into + * the axisStore + * + * @param kie + * @param axisStore + * @return true if the given kie is handled as a Axis input + */ + public static boolean checkAxisKey(KeyInputEvent kie, Vector3f axisStore) { + if (kie.getKeyCode() == KeyInput.KEY_X) { + axisStore.set(Vector3f.UNIT_X); + return true; + } else if (kie.getKeyCode() == KeyInput.KEY_Y) { + axisStore.set(Vector3f.UNIT_Y); + return true; + } else if (kie.getKeyCode() == KeyInput.KEY_Z) { + axisStore.set(Vector3f.UNIT_Z); + return true; + } + return false; + } + +} diff --git a/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/ShortcutTool.java b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/ShortcutTool.java new file mode 100644 index 000000000..9b094fc1d --- /dev/null +++ b/sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/ShortcutTool.java @@ -0,0 +1,29 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.jme3.gde.scenecomposer.tools.shortcuts; + +import com.jme3.gde.scenecomposer.SceneEditTool; +import com.jme3.input.event.KeyInputEvent; +import org.openide.util.Lookup; + +/** + * + * @author dokthar + */ +public abstract class ShortcutTool extends SceneEditTool { + + public abstract boolean isActivableBy(KeyInputEvent kie); + + public abstract void cancel(); + + protected final void terminate() { + Lookup.getDefault().lookup(ShortcutManager.class).terminate(); + } + + @Override + public abstract void keyPressed(KeyInputEvent kie); + +} diff --git a/settings.gradle b/settings.gradle index 346532460..89b8fc075 100644 --- a/settings.gradle +++ b/settings.gradle @@ -35,6 +35,10 @@ include 'jme3-testdata' // Example projects include 'jme3-examples' +if(buildAndroidExamples == "true"){ + include 'jme3-android-examples' +} + if(buildSdkProject == "true"){ include 'sdk' }