Improve code / xml formatting #54

This commit is contained in:
Emux 2016-11-20 19:26:38 +02:00
parent 308497ffa6
commit 3388e1401f
4 changed files with 521 additions and 435 deletions

View File

@ -1,12 +1,12 @@
/******************************************************************************* /*******************************************************************************
* Copyright 2011 See AUTHORS file. * Copyright 2011 See AUTHORS file.
* * <p>
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* * <p>
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* * <p>
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -55,10 +55,13 @@ import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget; import com.google.gwt.user.client.ui.Widget;
/** Implementation of an {@link Application} based on GWT. Clients have to override {@link #getConfig()} and /**
* Implementation of an {@link Application} based on GWT. Clients have to override {@link #getConfig()} and
* {@link #createApplicationListener()}. Clients can override the default loading screen via * {@link #createApplicationListener()}. Clients can override the default loading screen via
* {@link #getPreloaderCallback()} and implement any loading screen drawing via GWT widgets. * {@link #getPreloaderCallback()} and implement any loading screen drawing via GWT widgets.
* @author mzechner */ *
* @author mzechner
*/
public abstract class GwtApplication implements EntryPoint, Application { public abstract class GwtApplication implements EntryPoint, Application {
private ApplicationListener listener; private ApplicationListener listener;
GwtApplicationConfiguration config; GwtApplicationConfiguration config;
@ -79,12 +82,13 @@ public abstract class GwtApplication implements EntryPoint, Application {
private Clipboard clipboard; private Clipboard clipboard;
LoadingListener loadingListener; LoadingListener loadingListener;
/** @return the configuration for the {@link GwtApplication}. */ /**
public abstract GwtApplicationConfiguration getConfig (); * @return the configuration for the {@link GwtApplication}.
*/
public abstract GwtApplicationConfiguration getConfig();
public String getPreloaderBaseURL() public String getPreloaderBaseURL() {
{
return GWT.getHostPageBaseURL() + "assets/"; return GWT.getHostPageBaseURL() + "assets/";
} }
@ -96,7 +100,7 @@ public abstract class GwtApplication implements EntryPoint, Application {
public abstract ApplicationListener createApplicationListener(); public abstract ApplicationListener createApplicationListener();
@Override @Override
public void onModuleLoad () { public void onModuleLoad() {
GwtApplication.agentInfo = computeAgentInfo(); GwtApplication.agentInfo = computeAgentInfo();
this.listener = createApplicationListener(); this.listener = createApplicationListener();
this.config = getConfig(); this.config = getConfig();
@ -133,19 +137,19 @@ public abstract class GwtApplication implements EntryPoint, Application {
preloader = createPreloader(); preloader = createPreloader();
preloader.preload("assets.txt", new PreloaderCallback() { preloader.preload("assets.txt", new PreloaderCallback() {
@Override @Override
public void error (String file) { public void error(String file) {
callback.error(file); callback.error(file);
} }
@Override @Override
public void update (PreloaderState state) { public void update(PreloaderState state) {
callback.update(state); callback.update(state);
if (state.hasEnded()) { if (state.hasEnded()) {
getRootPanel().clear(); getRootPanel().clear();
if(loadingListener != null) if (loadingListener != null)
loadingListener.beforeSetup(); loadingListener.beforeSetup();
setupLoop(); setupLoop();
if(loadingListener != null) if (loadingListener != null)
loadingListener.afterSetup(); loadingListener.afterSetup();
} }
} }
@ -161,7 +165,7 @@ public abstract class GwtApplication implements EntryPoint, Application {
return new Label("Sorry, your browser doesn't seem to support WebGL"); return new Label("Sorry, your browser doesn't seem to support WebGL");
} }
void setupLoop () { void setupLoop() {
// setup modules // setup modules
try { try {
graphics = new GwtGraphics(root, config); graphics = new GwtGraphics(root, config);
@ -197,7 +201,7 @@ public abstract class GwtApplication implements EntryPoint, Application {
AnimationScheduler.get().requestAnimationFrame(new AnimationCallback() { AnimationScheduler.get().requestAnimationFrame(new AnimationCallback() {
@Override @Override
public void execute (double timestamp) { public void execute(double timestamp) {
try { try {
mainLoop(); mainLoop();
} catch (Throwable t) { } catch (Throwable t) {
@ -228,7 +232,7 @@ public abstract class GwtApplication implements EntryPoint, Application {
input.reset(); input.reset();
} }
public Panel getRootPanel () { public Panel getRootPanel() {
return root; return root;
} }
@ -238,7 +242,7 @@ public abstract class GwtApplication implements EntryPoint, Application {
return new Preloader(getPreloaderBaseURL()); return new Preloader(getPreloaderBaseURL());
} }
public PreloaderCallback getPreloaderCallback () { public PreloaderCallback getPreloaderCallback() {
final Panel preloaderPanel = new VerticalPanel(); final Panel preloaderPanel = new VerticalPanel();
preloaderPanel.setStyleName("gdx-preloader"); preloaderPanel.setStyleName("gdx-preloader");
final Image logo = new Image(GWT.getModuleBaseURL() + "logo.png"); final Image logo = new Image(GWT.getModuleBaseURL() + "logo.png");
@ -256,12 +260,12 @@ public abstract class GwtApplication implements EntryPoint, Application {
return new PreloaderCallback() { return new PreloaderCallback() {
@Override @Override
public void error (String file) { public void error(String file) {
System.out.println("error: " + file); System.out.println("error: " + file);
} }
@Override @Override
public void update (PreloaderState state) { public void update(PreloaderState state) {
meterStyle.setWidth(100f * state.getProgress(), Unit.PCT); meterStyle.setWidth(100f * state.getProgress(), Unit.PCT);
} }
@ -269,22 +273,22 @@ public abstract class GwtApplication implements EntryPoint, Application {
} }
@Override @Override
public Graphics getGraphics () { public Graphics getGraphics() {
return graphics; return graphics;
} }
@Override @Override
public Audio getAudio () { public Audio getAudio() {
return Gdx.audio; return Gdx.audio;
} }
@Override @Override
public Input getInput () { public Input getInput() {
return Gdx.input; return Gdx.input;
} }
@Override @Override
public Files getFiles () { public Files getFiles() {
return Gdx.files; return Gdx.files;
} }
@ -293,7 +297,7 @@ public abstract class GwtApplication implements EntryPoint, Application {
return Gdx.net; return Gdx.net;
} }
private void updateLogLabelSize () { private void updateLogLabelSize() {
if (log != null) { if (log != null) {
if (graphics != null) { if (graphics != null) {
log.setSize(graphics.getWidth() + "px", "200px"); log.setSize(graphics.getWidth() + "px", "200px");
@ -303,7 +307,7 @@ public abstract class GwtApplication implements EntryPoint, Application {
} }
} }
private void checkLogLabel () { private void checkLogLabel() {
if (log == null) { if (log == null) {
log = new TextArea(); log = new TextArea();
@ -322,7 +326,7 @@ public abstract class GwtApplication implements EntryPoint, Application {
} }
@Override @Override
public void log (String tag, String message) { public void log(String tag, String message) {
if (logLevel >= LOG_INFO) { if (logLevel >= LOG_INFO) {
checkLogLabel(); checkLogLabel();
log.setText(log.getText() + "\n" + tag + ": " + message); log.setText(log.getText() + "\n" + tag + ": " + message);
@ -332,7 +336,7 @@ public abstract class GwtApplication implements EntryPoint, Application {
} }
@Override @Override
public void log (String tag, String message, Throwable exception) { public void log(String tag, String message, Throwable exception) {
if (logLevel >= LOG_INFO) { if (logLevel >= LOG_INFO) {
checkLogLabel(); checkLogLabel();
log.setText(log.getText() + "\n" + tag + ": " + message + "\n" + getMessages(exception) + "\n"); log.setText(log.getText() + "\n" + tag + ": " + message + "\n" + getMessages(exception) + "\n");
@ -343,7 +347,7 @@ public abstract class GwtApplication implements EntryPoint, Application {
} }
@Override @Override
public void error (String tag, String message) { public void error(String tag, String message) {
if (logLevel >= LOG_ERROR) { if (logLevel >= LOG_ERROR) {
checkLogLabel(); checkLogLabel();
log.setText(log.getText() + "\n" + tag + ": " + message + "\n"); log.setText(log.getText() + "\n" + tag + ": " + message + "\n");
@ -353,7 +357,7 @@ public abstract class GwtApplication implements EntryPoint, Application {
} }
@Override @Override
public void error (String tag, String message, Throwable exception) { public void error(String tag, String message, Throwable exception) {
if (logLevel >= LOG_ERROR) { if (logLevel >= LOG_ERROR) {
checkLogLabel(); checkLogLabel();
log.setText(log.getText() + "\n" + tag + ": " + message + "\n" + getMessages(exception) + "\n"); log.setText(log.getText() + "\n" + tag + ": " + message + "\n" + getMessages(exception) + "\n");
@ -364,7 +368,7 @@ public abstract class GwtApplication implements EntryPoint, Application {
} }
@Override @Override
public void debug (String tag, String message) { public void debug(String tag, String message) {
if (logLevel >= LOG_DEBUG) { if (logLevel >= LOG_DEBUG) {
checkLogLabel(); checkLogLabel();
log.setText(log.getText() + "\n" + tag + ": " + message + "\n"); log.setText(log.getText() + "\n" + tag + ": " + message + "\n");
@ -374,7 +378,7 @@ public abstract class GwtApplication implements EntryPoint, Application {
} }
@Override @Override
public void debug (String tag, String message, Throwable exception) { public void debug(String tag, String message, Throwable exception) {
if (logLevel >= LOG_DEBUG) { if (logLevel >= LOG_DEBUG) {
checkLogLabel(); checkLogLabel();
log.setText(log.getText() + "\n" + tag + ": " + message + "\n" + getMessages(exception) + "\n"); log.setText(log.getText() + "\n" + tag + ": " + message + "\n" + getMessages(exception) + "\n");
@ -384,7 +388,7 @@ public abstract class GwtApplication implements EntryPoint, Application {
} }
} }
private String getMessages (Throwable e) { private String getMessages(Throwable e) {
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
while (e != null) { while (e != null) {
buffer.append(e.getMessage() + "\n"); buffer.append(e.getMessage() + "\n");
@ -393,7 +397,7 @@ public abstract class GwtApplication implements EntryPoint, Application {
return buffer.toString(); return buffer.toString();
} }
private String getStackTrace (Throwable e) { private String getStackTrace(Throwable e) {
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
for (StackTraceElement trace : e.getStackTrace()) { for (StackTraceElement trace : e.getStackTrace()) {
buffer.append(trace.toString() + "\n"); buffer.append(trace.toString() + "\n");
@ -402,7 +406,7 @@ public abstract class GwtApplication implements EntryPoint, Application {
} }
@Override @Override
public void setLogLevel (int logLevel) { public void setLogLevel(int logLevel) {
this.logLevel = logLevel; this.logLevel = logLevel;
} }
@ -412,27 +416,27 @@ public abstract class GwtApplication implements EntryPoint, Application {
} }
@Override @Override
public ApplicationType getType () { public ApplicationType getType() {
return ApplicationType.WebGL; return ApplicationType.WebGL;
} }
@Override @Override
public int getVersion () { public int getVersion() {
return 0; return 0;
} }
@Override @Override
public long getJavaHeap () { public long getJavaHeap() {
return 0; return 0;
} }
@Override @Override
public long getNativeHeap () { public long getNativeHeap() {
return 0; return 0;
} }
@Override @Override
public Preferences getPreferences (String name) { public Preferences getPreferences(String name) {
Preferences pref = prefs.get(name); Preferences pref = prefs.get(name);
if (pref == null) { if (pref == null) {
pref = new GwtPreferences(name); pref = new GwtPreferences(name);
@ -442,126 +446,132 @@ public abstract class GwtApplication implements EntryPoint, Application {
} }
@Override @Override
public Clipboard getClipboard () { public Clipboard getClipboard() {
return clipboard; return clipboard;
} }
@Override @Override
public void postRunnable (Runnable runnable) { public void postRunnable(Runnable runnable) {
runnables.add(runnable); runnables.add(runnable);
} }
@Override @Override
public void exit () { public void exit() {
} }
/** Contains precomputed information on the user-agent. Useful for dealing with browser and OS behavioral differences. Kindly /**
* borrowed from PlayN */ * Contains precomputed information on the user-agent. Useful for dealing with browser and OS behavioral differences. Kindly
public static AgentInfo agentInfo () { * borrowed from PlayN
*/
public static AgentInfo agentInfo() {
return agentInfo; return agentInfo;
} }
/** kindly borrowed from PlayN **/ /**
private static native AgentInfo computeAgentInfo () /*-{ * kindly borrowed from PlayN
var userAgent = navigator.userAgent.toLowerCase(); **/
return { private static native AgentInfo computeAgentInfo() /*-{
// browser type flags var userAgent = navigator.userAgent.toLowerCase();
isFirefox : userAgent.indexOf("firefox") != -1, return {
isChrome : userAgent.indexOf("chrome") != -1, // browser type flags
isSafari : userAgent.indexOf("safari") != -1, isFirefox : userAgent.indexOf("firefox") != -1,
isOpera : userAgent.indexOf("opera") != -1, isChrome : userAgent.indexOf("chrome") != -1,
isIE : userAgent.indexOf("msie") != -1, isSafari : userAgent.indexOf("safari") != -1,
// OS type flags isOpera : userAgent.indexOf("opera") != -1,
isMacOS : userAgent.indexOf("mac") != -1, isIE : userAgent.indexOf("msie") != -1,
isLinux : userAgent.indexOf("linux") != -1, // OS type flags
isWindows : userAgent.indexOf("win") != -1 isMacOS : userAgent.indexOf("mac") != -1,
}; isLinux : userAgent.indexOf("linux") != -1,
}-*/; isWindows : userAgent.indexOf("win") != -1
};
}-*/;
/** Returned by {@link #agentInfo}. Kindly borrowed from PlayN. */ /**
* Returned by {@link #agentInfo}. Kindly borrowed from PlayN.
*/
public static class AgentInfo extends JavaScriptObject { public static class AgentInfo extends JavaScriptObject {
public final native boolean isFirefox () /*-{ public final native boolean isFirefox() /*-{
return this.isFirefox; return this.isFirefox;
}-*/; }-*/;
public final native boolean isChrome () /*-{ public final native boolean isChrome() /*-{
return this.isChrome; return this.isChrome;
}-*/; }-*/;
public final native boolean isSafari () /*-{ public final native boolean isSafari() /*-{
return this.isSafari; return this.isSafari;
}-*/; }-*/;
public final native boolean isOpera () /*-{ public final native boolean isOpera() /*-{
return this.isOpera; return this.isOpera;
}-*/; }-*/;
public final native boolean isIE () /*-{ public final native boolean isIE() /*-{
return this.isIE; return this.isIE;
}-*/; }-*/;
public final native boolean isMacOS () /*-{ public final native boolean isMacOS() /*-{
return this.isMacOS; return this.isMacOS;
}-*/; }-*/;
public final native boolean isLinux () /*-{ public final native boolean isLinux() /*-{
return this.isLinux; return this.isLinux;
}-*/; }-*/;
public final native boolean isWindows () /*-{ public final native boolean isWindows() /*-{
return this.isWindows; return this.isWindows;
}-*/; }-*/;
protected AgentInfo () { protected AgentInfo() {
} }
} }
public String getBaseUrl () { public String getBaseUrl() {
return preloader.baseUrl; return preloader.baseUrl;
} }
public Preloader getPreloader () { public Preloader getPreloader() {
return preloader; return preloader;
} }
public CanvasElement getCanvasElement(){ public CanvasElement getCanvasElement() {
return graphics.canvas; return graphics.canvas;
} }
public LoadingListener getLoadingListener () { public LoadingListener getLoadingListener() {
return loadingListener; return loadingListener;
} }
public void setLoadingListener (LoadingListener loadingListener) { public void setLoadingListener(LoadingListener loadingListener) {
this.loadingListener = loadingListener; this.loadingListener = loadingListener;
} }
@Override @Override
public void addLifecycleListener (LifecycleListener listener) { public void addLifecycleListener(LifecycleListener listener) {
synchronized(lifecycleListeners) { synchronized (lifecycleListeners) {
lifecycleListeners.add(listener); lifecycleListeners.add(listener);
} }
} }
@Override @Override
public void removeLifecycleListener (LifecycleListener listener) { public void removeLifecycleListener(LifecycleListener listener) {
synchronized(lifecycleListeners) { synchronized (lifecycleListeners) {
lifecycleListeners.removeValue(listener, true); lifecycleListeners.removeValue(listener, true);
} }
} }
native static public void consoleLog(String message) /*-{ native static public void consoleLog(String message) /*-{
console.log( "GWT: " + message ); console.log( "GWT: " + message );
}-*/; }-*/;
private native void addEventListeners () /*-{ private native void addEventListeners() /*-{
var self = this; var self = this;
$doc.addEventListener('visibilitychange', function (e) { $doc.addEventListener('visibilitychange', function (e) {
self.@com.badlogic.gdx.backends.gwt.GwtApplication::onVisibilityChange(Z)($doc['hidden'] !== true); self.@com.badlogic.gdx.backends.gwt.GwtApplication::onVisibilityChange(Z)($doc['hidden'] !== true);
}); });
}-*/; }-*/;
private void onVisibilityChange (boolean visible) { private void onVisibilityChange(boolean visible) {
if (visible) { if (visible) {
for (LifecycleListener listener : lifecycleListeners) { for (LifecycleListener listener : lifecycleListeners) {
listener.resume(); listener.resume();
@ -578,7 +588,7 @@ public abstract class GwtApplication implements EntryPoint, Application {
/** /**
* LoadingListener interface main purpose is to do some things before or after {@link GwtApplication#setupLoop()} * LoadingListener interface main purpose is to do some things before or after {@link GwtApplication#setupLoop()}
*/ */
public interface LoadingListener{ public interface LoadingListener {
/** /**
* Method called before the setup * Method called before the setup
*/ */

View File

@ -1,12 +1,12 @@
/******************************************************************************* /*******************************************************************************
* Copyright 2011 See AUTHORS file. * Copyright 2011 See AUTHORS file.
* * <p>
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* * <p>
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* * <p>
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@ -1,12 +1,12 @@
/******************************************************************************* /*******************************************************************************
* Copyright 2011 See AUTHORS file. * Copyright 2011 See AUTHORS file.
* * <p>
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* * <p>
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* * <p>
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -52,12 +52,12 @@ public class GwtInput implements Input {
final CanvasElement canvas; final CanvasElement canvas;
boolean hasFocus = true; boolean hasFocus = true;
public GwtInput (CanvasElement canvas) { public GwtInput(CanvasElement canvas) {
this.canvas = canvas; this.canvas = canvas;
hookEvents(); hookEvents();
} }
void reset () { void reset() {
justTouched = false; justTouched = false;
if (keyJustPressed) { if (keyJustPressed) {
keyJustPressed = false; keyJustPressed = false;
@ -68,80 +68,80 @@ public class GwtInput implements Input {
} }
@Override @Override
public float getAccelerometerX () { public float getAccelerometerX() {
return 0; return 0;
} }
@Override @Override
public float getAccelerometerY () { public float getAccelerometerY() {
return 0; return 0;
} }
@Override @Override
public float getAccelerometerZ () { public float getAccelerometerZ() {
return 0; return 0;
} }
@Override @Override
public float getGyroscopeX () { public float getGyroscopeX() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return 0; return 0;
} }
@Override @Override
public float getGyroscopeY () { public float getGyroscopeY() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return 0; return 0;
} }
@Override @Override
public float getGyroscopeZ () { public float getGyroscopeZ() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return 0; return 0;
} }
@Override @Override
public int getX () { public int getX() {
return touchX[0]; return touchX[0];
} }
@Override @Override
public int getX (int pointer) { public int getX(int pointer) {
return touchX[pointer]; return touchX[pointer];
} }
@Override @Override
public int getDeltaX () { public int getDeltaX() {
return deltaX[0]; return deltaX[0];
} }
@Override @Override
public int getDeltaX (int pointer) { public int getDeltaX(int pointer) {
return deltaX[pointer]; return deltaX[pointer];
} }
@Override @Override
public int getY () { public int getY() {
return touchY[0]; return touchY[0];
} }
@Override @Override
public int getY (int pointer) { public int getY(int pointer) {
return touchY[pointer]; return touchY[pointer];
} }
@Override @Override
public int getDeltaY () { public int getDeltaY() {
return deltaY[0]; return deltaY[0];
} }
@Override @Override
public int getDeltaY (int pointer) { public int getDeltaY(int pointer) {
return deltaY[pointer]; return deltaY[pointer];
} }
@Override @Override
public boolean isTouched () { public boolean isTouched() {
for (int pointer = 0; pointer < MAX_TOUCHES; pointer++) { for (int pointer = 0; pointer < MAX_TOUCHES; pointer++) {
if (touched[pointer]) { if (touched[pointer]) {
return true; return true;
@ -151,22 +151,22 @@ public class GwtInput implements Input {
} }
@Override @Override
public boolean justTouched () { public boolean justTouched() {
return justTouched; return justTouched;
} }
@Override @Override
public boolean isTouched (int pointer) { public boolean isTouched(int pointer) {
return touched[pointer]; return touched[pointer];
} }
@Override @Override
public boolean isButtonPressed (int button) { public boolean isButtonPressed(int button) {
return pressedButtons.contains(button) && touched[0]; return pressedButtons.contains(button) && touched[0];
} }
@Override @Override
public boolean isKeyPressed (int key) { public boolean isKeyPressed(int key) {
if (key == Keys.ANY_KEY) { if (key == Keys.ANY_KEY) {
return pressedKeyCount > 0; return pressedKeyCount > 0;
} }
@ -177,7 +177,7 @@ public class GwtInput implements Input {
} }
@Override @Override
public boolean isKeyJustPressed (int key) { public boolean isKeyJustPressed(int key) {
if (key == Keys.ANY_KEY) { if (key == Keys.ANY_KEY) {
return keyJustPressed; return keyJustPressed;
} }
@ -187,19 +187,19 @@ public class GwtInput implements Input {
return justPressedKeys[key]; return justPressedKeys[key];
} }
public void getTextInput (TextInputListener listener, String title, String text, String hint) { public void getTextInput(TextInputListener listener, String title, String text, String hint) {
TextInputDialogBox dialog = new TextInputDialogBox(title, text, hint); TextInputDialogBox dialog = new TextInputDialogBox(title, text, hint);
final TextInputListener capturedListener = listener; final TextInputListener capturedListener = listener;
dialog.setListener(new TextInputDialogListener() { dialog.setListener(new TextInputDialogListener() {
@Override @Override
public void onPositive (String text) { public void onPositive(String text) {
if (capturedListener != null) { if (capturedListener != null) {
capturedListener.input(text); capturedListener.input(text);
} }
} }
@Override @Override
public void onNegative () { public void onNegative() {
if (capturedListener != null) { if (capturedListener != null) {
capturedListener.canceled(); capturedListener.canceled();
} }
@ -208,75 +208,75 @@ public class GwtInput implements Input {
} }
@Override @Override
public void setOnscreenKeyboardVisible (boolean visible) { public void setOnscreenKeyboardVisible(boolean visible) {
} }
@Override @Override
public void vibrate (int milliseconds) { public void vibrate(int milliseconds) {
} }
@Override @Override
public void vibrate (long[] pattern, int repeat) { public void vibrate(long[] pattern, int repeat) {
} }
@Override @Override
public void cancelVibrate () { public void cancelVibrate() {
} }
@Override @Override
public float getAzimuth () { public float getAzimuth() {
return 0; return 0;
} }
@Override @Override
public float getPitch () { public float getPitch() {
return 0; return 0;
} }
@Override @Override
public float getRoll () { public float getRoll() {
return 0; return 0;
} }
@Override @Override
public void getRotationMatrix (float[] matrix) { public void getRotationMatrix(float[] matrix) {
} }
@Override @Override
public long getCurrentEventTime () { public long getCurrentEventTime() {
return currentEventTimeStamp; return currentEventTimeStamp;
} }
@Override @Override
public void setCatchBackKey (boolean catchBack) { public void setCatchBackKey(boolean catchBack) {
} }
@Override @Override
public boolean isCatchBackKey () { public boolean isCatchBackKey() {
return false; return false;
} }
@Override @Override
public void setCatchMenuKey (boolean catchMenu) { public void setCatchMenuKey(boolean catchMenu) {
} }
@Override @Override
public boolean isCatchMenuKey () { public boolean isCatchMenuKey() {
return false; return false;
} }
@Override @Override
public void setInputProcessor (InputProcessor processor) { public void setInputProcessor(InputProcessor processor) {
this.processor = processor; this.processor = processor;
} }
@Override @Override
public InputProcessor getInputProcessor () { public InputProcessor getInputProcessor() {
return processor; return processor;
} }
@Override @Override
public boolean isPeripheralAvailable (Peripheral peripheral) { public boolean isPeripheralAvailable(Peripheral peripheral) {
if (peripheral == Peripheral.Accelerometer) return false; if (peripheral == Peripheral.Accelerometer) return false;
if (peripheral == Peripheral.Compass) return false; if (peripheral == Peripheral.Compass) return false;
if (peripheral == Peripheral.HardwareKeyboard) return true; if (peripheral == Peripheral.HardwareKeyboard) return true;
@ -287,95 +287,111 @@ public class GwtInput implements Input {
} }
@Override @Override
public int getRotation () { public int getRotation() {
return 0; return 0;
} }
@Override @Override
public Orientation getNativeOrientation () { public Orientation getNativeOrientation() {
return Orientation.Landscape; return Orientation.Landscape;
} }
/** from https://github.com/toji/game-shim/blob/master/game-shim.js /**
* @return is Cursor catched */ * from https://github.com/toji/game-shim/blob/master/game-shim.js
private native boolean isCursorCatchedJSNI () /*-{ *
if (!navigator.pointer) { * @return is Cursor catched
navigator.pointer = navigator.webkitPointer || navigator.mozPointer; */
} private native boolean isCursorCatchedJSNI() /*-{
if (navigator.pointer) { if (!navigator.pointer) {
if (typeof (navigator.pointer.isLocked) === "boolean") { navigator.pointer = navigator.webkitPointer || navigator.mozPointer;
// Chrome initially launched with this interface }
return navigator.pointer.isLocked; if (navigator.pointer) {
} else if (typeof (navigator.pointer.isLocked) === "function") { if (typeof (navigator.pointer.isLocked) === "boolean") {
// Some older builds might provide isLocked as a function // Chrome initially launched with this interface
return navigator.pointer.isLocked(); return navigator.pointer.isLocked;
} else if (typeof (navigator.pointer.islocked) === "function") { } else if (typeof (navigator.pointer.isLocked) === "function") {
// For compatibility with early Firefox build // Some older builds might provide isLocked as a function
return navigator.pointer.islocked(); return navigator.pointer.isLocked();
} } else if (typeof (navigator.pointer.islocked) === "function") {
} // For compatibility with early Firefox build
return false; return navigator.pointer.islocked();
}-*/; }
}
return false;
}-*/;
/** from https://github.com/toji/game-shim/blob/master/game-shim.js /**
* @param element Canvas */ * from https://github.com/toji/game-shim/blob/master/game-shim.js
private native void setCursorCatchedJSNI (CanvasElement element) /*-{ *
// Navigator pointer is not the right interface according to spec. * @param element Canvas
// Here for backwards compatibility only */
if (!navigator.pointer) { private native void setCursorCatchedJSNI(CanvasElement element) /*-{
navigator.pointer = navigator.webkitPointer || navigator.mozPointer; // Navigator pointer is not the right interface according to spec.
} // Here for backwards compatibility only
// element.requestPointerLock if (!navigator.pointer) {
if (!element.requestPointerLock) { navigator.pointer = navigator.webkitPointer || navigator.mozPointer;
element.requestPointerLock = (function() { }
return element.webkitRequestPointerLock // element.requestPointerLock
|| element.mozRequestPointerLock || function() { if (!element.requestPointerLock) {
if (navigator.pointer) { element.requestPointerLock = (function() {
navigator.pointer.lock(element); return element.webkitRequestPointerLock
} || element.mozRequestPointerLock || function() {
}; if (navigator.pointer) {
})(); navigator.pointer.lock(element);
} }
element.requestPointerLock(); };
}-*/; })();
}
element.requestPointerLock();
}-*/;
/** from https://github.com/toji/game-shim/blob/master/game-shim.js */ /**
private native void exitCursorCatchedJSNI () /*-{ * from https://github.com/toji/game-shim/blob/master/game-shim.js
if (!$doc.exitPointerLock) { */
$doc.exitPointerLock = (function() { private native void exitCursorCatchedJSNI() /*-{
return $doc.webkitExitPointerLock || $doc.mozExitPointerLock if (!$doc.exitPointerLock) {
|| function() { $doc.exitPointerLock = (function() {
if (navigator.pointer) { return $doc.webkitExitPointerLock || $doc.mozExitPointerLock
var elem = this; || function() {
navigator.pointer.unlock(); if (navigator.pointer) {
} var elem = this;
}; navigator.pointer.unlock();
})(); }
} };
}-*/; })();
}
}-*/;
/** from https://github.com/toji/game-shim/blob/master/game-shim.js /**
* from https://github.com/toji/game-shim/blob/master/game-shim.js
*
* @param event JavaScript Mouse Event * @param event JavaScript Mouse Event
* @return movement in x direction */ * @return movement in x direction
private native float getMovementXJSNI (NativeEvent event) /*-{ */
return event.movementX || event.webkitMovementX || 0; private native float getMovementXJSNI(NativeEvent event) /*-{
}-*/; return event.movementX || event.webkitMovementX || 0;
}-*/;
/** from https://github.com/toji/game-shim/blob/master/game-shim.js /**
* from https://github.com/toji/game-shim/blob/master/game-shim.js
*
* @param event JavaScript Mouse Event * @param event JavaScript Mouse Event
* @return movement in y direction */ * @return movement in y direction
private native float getMovementYJSNI (NativeEvent event) /*-{ */
return event.movementY || event.webkitMovementY || 0; private native float getMovementYJSNI(NativeEvent event) /*-{
}-*/; return event.movementY || event.webkitMovementY || 0;
}-*/;
private static native boolean isTouchScreen () /*-{ private static native boolean isTouchScreen() /*-{
return (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0)); return (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0));
}-*/; }-*/;
/** works only for Chrome > Version 18 with enabled Mouse Lock enable in about:flags or start Chrome with the /**
* --enable-pointer-lock flag */ * works only for Chrome > Version 18 with enabled Mouse Lock enable in about:flags or start Chrome with the
* --enable-pointer-lock flag
*/
@Override @Override
public void setCursorCatched (boolean catched) { public void setCursorCatched(boolean catched) {
if (catched) if (catched)
setCursorCatchedJSNI(canvas); setCursorCatchedJSNI(canvas);
else else
@ -383,90 +399,96 @@ public class GwtInput implements Input {
} }
@Override @Override
public boolean isCursorCatched () { public boolean isCursorCatched() {
return isCursorCatchedJSNI(); return isCursorCatchedJSNI();
} }
@Override @Override
public void setCursorPosition (int x, int y) { public void setCursorPosition(int x, int y) {
// FIXME?? // FIXME??
} }
// kindly borrowed from our dear playn friends... // kindly borrowed from our dear playn friends...
static native void addEventListener (JavaScriptObject target, String name, GwtInput handler, boolean capture) /*-{ static native void addEventListener(JavaScriptObject target, String name, GwtInput handler, boolean capture) /*-{
target target
.addEventListener( .addEventListener(
name, name,
function(e) { function(e) {
handler.@com.badlogic.gdx.backends.gwt.GwtInput::handleEvent(Lcom/google/gwt/dom/client/NativeEvent;)(e); handler.@com.badlogic.gdx.backends.gwt.GwtInput::handleEvent(Lcom/google/gwt/dom/client/NativeEvent;)(e);
}, capture); }, capture);
}-*/; }-*/;
private static native float getMouseWheelVelocity (NativeEvent evt) /*-{ private static native float getMouseWheelVelocity(NativeEvent evt) /*-{
var delta = 0.0; var delta = 0.0;
var agentInfo = @com.badlogic.gdx.backends.gwt.GwtApplication::agentInfo()(); var agentInfo = @com.badlogic.gdx.backends.gwt.GwtApplication::agentInfo()();
if (agentInfo.isFirefox) { if (agentInfo.isFirefox) {
if (agentInfo.isMacOS) { if (agentInfo.isMacOS) {
delta = 1.0 * evt.detail; delta = 1.0 * evt.detail;
} else { } else {
delta = 1.0 * evt.detail / 3; delta = 1.0 * evt.detail / 3;
} }
} else if (agentInfo.isOpera) { } else if (agentInfo.isOpera) {
if (agentInfo.isLinux) { if (agentInfo.isLinux) {
delta = -1.0 * evt.wheelDelta / 80; delta = -1.0 * evt.wheelDelta / 80;
} else { } else {
// on mac // on mac
delta = -1.0 * evt.wheelDelta / 40; delta = -1.0 * evt.wheelDelta / 40;
} }
} else if (agentInfo.isChrome || agentInfo.isSafari) { } else if (agentInfo.isChrome || agentInfo.isSafari) {
delta = -1.0 * evt.wheelDelta / 120; delta = -1.0 * evt.wheelDelta / 120;
// handle touchpad for chrome // handle touchpad for chrome
if (Math.abs(delta) < 1) { if (Math.abs(delta) < 1) {
if (agentInfo.isWindows) { if (agentInfo.isWindows) {
delta = -1.0 * evt.wheelDelta; delta = -1.0 * evt.wheelDelta;
} else if (agentInfo.isMacOS) { } else if (agentInfo.isMacOS) {
delta = -1.0 * evt.wheelDelta / 3; delta = -1.0 * evt.wheelDelta / 3;
} }
} }
} }
return delta; return delta;
}-*/; }-*/;
/** Kindly borrowed from PlayN. **/ /**
protected static native String getMouseWheelEvent () /*-{ * Kindly borrowed from PlayN.
if (navigator.userAgent.toLowerCase().indexOf('firefox') != -1) { **/
return "DOMMouseScroll"; protected static native String getMouseWheelEvent() /*-{
} else { if (navigator.userAgent.toLowerCase().indexOf('firefox') != -1) {
return "mousewheel"; return "DOMMouseScroll";
} } else {
}-*/; return "mousewheel";
}
}-*/;
/** Kindly borrowed from PlayN. **/ /**
protected int getRelativeX (NativeEvent e, CanvasElement target) { * Kindly borrowed from PlayN.
**/
protected int getRelativeX(NativeEvent e, CanvasElement target) {
float xScaleRatio = target.getWidth() * 1f / target.getClientWidth(); // Correct for canvas CSS scaling float xScaleRatio = target.getWidth() * 1f / target.getClientWidth(); // Correct for canvas CSS scaling
return Math.round(xScaleRatio return Math.round(xScaleRatio
* (e.getClientX() - target.getAbsoluteLeft() + target.getScrollLeft() + target.getOwnerDocument().getScrollLeft())); * (e.getClientX() - target.getAbsoluteLeft() + target.getScrollLeft() + target.getOwnerDocument().getScrollLeft()));
} }
/** Kindly borrowed from PlayN. **/ /**
protected int getRelativeY (NativeEvent e, CanvasElement target) { * Kindly borrowed from PlayN.
**/
protected int getRelativeY(NativeEvent e, CanvasElement target) {
float yScaleRatio = target.getHeight() * 1f / target.getClientHeight(); // Correct for canvas CSS scaling float yScaleRatio = target.getHeight() * 1f / target.getClientHeight(); // Correct for canvas CSS scaling
return Math.round(yScaleRatio return Math.round(yScaleRatio
* (e.getClientY() - target.getAbsoluteTop() + target.getScrollTop() + target.getOwnerDocument().getScrollTop())); * (e.getClientY() - target.getAbsoluteTop() + target.getScrollTop() + target.getOwnerDocument().getScrollTop()));
} }
protected int getRelativeX (Touch touch, CanvasElement target) { protected int getRelativeX(Touch touch, CanvasElement target) {
float xScaleRatio = target.getWidth() * 1f / target.getClientWidth(); // Correct for canvas CSS scaling float xScaleRatio = target.getWidth() * 1f / target.getClientWidth(); // Correct for canvas CSS scaling
return Math.round(xScaleRatio * touch.getRelativeX(target)); return Math.round(xScaleRatio * touch.getRelativeX(target));
} }
protected int getRelativeY (Touch touch, CanvasElement target) { protected int getRelativeY(Touch touch, CanvasElement target) {
float yScaleRatio = target.getHeight() * 1f / target.getClientHeight(); // Correct for canvas CSS scaling float yScaleRatio = target.getHeight() * 1f / target.getClientHeight(); // Correct for canvas CSS scaling
return Math.round(yScaleRatio * touch.getRelativeY(target)); return Math.round(yScaleRatio * touch.getRelativeY(target));
} }
private void hookEvents () { private void hookEvents() {
addEventListener(canvas, "mousedown", this, true); addEventListener(canvas, "mousedown", this, true);
// addEventListener(Document.get(), "mousedown", this, true); // addEventListener(Document.get(), "mousedown", this, true);
addEventListener(canvas, "mouseup", this, true); addEventListener(canvas, "mouseup", this, true);
@ -488,14 +510,14 @@ public class GwtInput implements Input {
} }
private int getButton (int button) { private int getButton(int button) {
if (button == NativeEvent.BUTTON_LEFT) return Buttons.LEFT; if (button == NativeEvent.BUTTON_LEFT) return Buttons.LEFT;
if (button == NativeEvent.BUTTON_RIGHT) return Buttons.RIGHT; if (button == NativeEvent.BUTTON_RIGHT) return Buttons.RIGHT;
if (button == NativeEvent.BUTTON_MIDDLE) return Buttons.MIDDLE; if (button == NativeEvent.BUTTON_MIDDLE) return Buttons.MIDDLE;
return Buttons.LEFT; return Buttons.LEFT;
} }
private void handleEvent (NativeEvent e) { private void handleEvent(NativeEvent e) {
if (e.getType().equals("mousedown")) { if (e.getType().equals("mousedown")) {
if (!e.getEventTarget().equals(canvas) || touched[0]) { if (!e.getEventTarget().equals(canvas) || touched[0]) {
float mouseX = getRelativeX(e, canvas); float mouseX = getRelativeX(e, canvas);
@ -519,13 +541,14 @@ public class GwtInput implements Input {
this.touchY[0] = getRelativeY(e, canvas); this.touchY[0] = getRelativeY(e, canvas);
} }
this.currentEventTimeStamp = TimeUtils.nanoTime(); this.currentEventTimeStamp = TimeUtils.nanoTime();
if (processor != null) processor.touchDown(touchX[0], touchY[0], 0, getButton(e.getButton())); if (processor != null)
processor.touchDown(touchX[0], touchY[0], 0, getButton(e.getButton()));
} }
if (e.getType().equals("mousemove")) { if (e.getType().equals("mousemove")) {
if (isCursorCatched()) { if (isCursorCatched()) {
this.deltaX[0] = (int)getMovementXJSNI(e); this.deltaX[0] = (int) getMovementXJSNI(e);
this.deltaY[0] = (int)getMovementYJSNI(e); this.deltaY[0] = (int) getMovementYJSNI(e);
this.touchX[0] += getMovementXJSNI(e); this.touchX[0] += getMovementXJSNI(e);
this.touchY[0] += getMovementYJSNI(e); this.touchY[0] += getMovementYJSNI(e);
} else { } else {
@ -548,8 +571,8 @@ public class GwtInput implements Input {
this.pressedButtons.remove(getButton(e.getButton())); this.pressedButtons.remove(getButton(e.getButton()));
this.touched[0] = pressedButtons.size > 0; this.touched[0] = pressedButtons.size > 0;
if (isCursorCatched()) { if (isCursorCatched()) {
this.deltaX[0] = (int)getMovementXJSNI(e); this.deltaX[0] = (int) getMovementXJSNI(e);
this.deltaY[0] = (int)getMovementYJSNI(e); this.deltaY[0] = (int) getMovementYJSNI(e);
this.touchX[0] += getMovementXJSNI(e); this.touchX[0] += getMovementXJSNI(e);
this.touchY[0] += getMovementYJSNI(e); this.touchY[0] += getMovementYJSNI(e);
} else { } else {
@ -560,11 +583,12 @@ public class GwtInput implements Input {
} }
this.currentEventTimeStamp = TimeUtils.nanoTime(); this.currentEventTimeStamp = TimeUtils.nanoTime();
this.touched[0] = false; this.touched[0] = false;
if (processor != null) processor.touchUp(touchX[0], touchY[0], 0, getButton(e.getButton())); if (processor != null)
processor.touchUp(touchX[0], touchY[0], 0, getButton(e.getButton()));
} }
if (e.getType().equals(getMouseWheelEvent())) { if (e.getType().equals(getMouseWheelEvent())) {
if (processor != null) { if (processor != null) {
processor.scrolled((int)getMouseWheelVelocity(e)); processor.scrolled((int) getMouseWheelVelocity(e));
} }
this.currentEventTimeStamp = TimeUtils.nanoTime(); this.currentEventTimeStamp = TimeUtils.nanoTime();
e.preventDefault(); e.preventDefault();
@ -593,7 +617,7 @@ public class GwtInput implements Input {
if (e.getType().equals("keypress") && hasFocus) { if (e.getType().equals("keypress") && hasFocus) {
// System.out.println("keypress"); // System.out.println("keypress");
char c = (char)e.getCharCode(); char c = (char) e.getCharCode();
if (processor != null) processor.keyTyped(c); if (processor != null) processor.keyTyped(c);
} }
@ -687,15 +711,17 @@ public class GwtInput implements Input {
// if(hasFocus) e.preventDefault(); // if(hasFocus) e.preventDefault();
} }
private int getAvailablePointer () { private int getAvailablePointer() {
for (int i = 0; i < MAX_TOUCHES; i++) { for (int i = 0; i < MAX_TOUCHES; i++) {
if (!touchMap.containsValue(i, false)) return i; if (!touchMap.containsValue(i, false)) return i;
} }
return -1; return -1;
} }
/** borrowed from PlayN, thanks guys **/ /**
private static int keyForCode (int keyCode) { * borrowed from PlayN, thanks guys
**/
private static int keyForCode(int keyCode) {
switch (keyCode) { switch (keyCode) {
case KeyCodes.KEY_ALT: case KeyCodes.KEY_ALT:
return Keys.ALT_LEFT; return Keys.ALT_LEFT;

View File

@ -1,12 +1,12 @@
/******************************************************************************* /*******************************************************************************
* Copyright 2011 See AUTHORS file. * Copyright 2011 See AUTHORS file.
* * <p>
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* * <p>
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* * <p>
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -16,11 +16,6 @@
package com.badlogic.gdx.graphics; package com.badlogic.gdx.graphics;
import java.nio.Buffer;
import java.nio.IntBuffer;
import java.util.HashMap;
import java.util.Map;
import com.badlogic.gdx.backends.gwt.GwtFileHandle; import com.badlogic.gdx.backends.gwt.GwtFileHandle;
import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.BufferUtils; import com.badlogic.gdx.utils.BufferUtils;
@ -33,17 +28,24 @@ import com.google.gwt.canvas.dom.client.Context2d.Composite;
import com.google.gwt.dom.client.CanvasElement; import com.google.gwt.dom.client.CanvasElement;
import com.google.gwt.dom.client.ImageElement; import com.google.gwt.dom.client.ImageElement;
import java.nio.Buffer;
import java.nio.IntBuffer;
import java.util.HashMap;
import java.util.Map;
public class Pixmap implements Disposable { public class Pixmap implements Disposable {
public static Map<Integer, Pixmap> pixmaps = new HashMap<Integer, Pixmap>(); public static Map<Integer, Pixmap> pixmaps = new HashMap<Integer, Pixmap>();
static int nextId = 0; static int nextId = 0;
/** Different pixel formats. /**
* Different pixel formats.
* *
* @author mzechner */ * @author mzechner
*/
public enum Format { public enum Format {
Alpha, Intensity, LuminanceAlpha, RGB565, RGBA4444, RGB888, RGBA8888; Alpha, Intensity, LuminanceAlpha, RGB565, RGBA4444, RGB888, RGBA8888;
public static int toGlFormat (Format format) { public static int toGlFormat(Format format) {
if (format == Alpha) return GL20.GL_ALPHA; if (format == Alpha) return GL20.GL_ALPHA;
if (format == Intensity) return GL20.GL_ALPHA; if (format == Intensity) return GL20.GL_ALPHA;
if (format == LuminanceAlpha) return GL20.GL_LUMINANCE_ALPHA; if (format == LuminanceAlpha) return GL20.GL_LUMINANCE_ALPHA;
@ -54,7 +56,7 @@ public class Pixmap implements Disposable {
throw new GdxRuntimeException("unknown format: " + format); throw new GdxRuntimeException("unknown format: " + format);
} }
public static int toGlType (Format format) { public static int toGlType(Format format) {
if (format == Alpha) return GL20.GL_UNSIGNED_BYTE; if (format == Alpha) return GL20.GL_UNSIGNED_BYTE;
if (format == Intensity) return GL20.GL_UNSIGNED_BYTE; if (format == Intensity) return GL20.GL_UNSIGNED_BYTE;
if (format == LuminanceAlpha) return GL20.GL_UNSIGNED_BYTE; if (format == LuminanceAlpha) return GL20.GL_UNSIGNED_BYTE;
@ -66,15 +68,20 @@ public class Pixmap implements Disposable {
} }
} }
/** Blending functions to be set with {@link Pixmap#setBlending}. /**
* @author mzechner */ * Blending functions to be set with {@link Pixmap#setBlending}.
*
* @author mzechner
*/
public enum Blending { public enum Blending {
None, SourceOver None, SourceOver
} }
/** Filters to be used with {@link Pixmap#drawPixmap(Pixmap, int, int, int, int, int, int, int, int)}. /**
* Filters to be used with {@link Pixmap#drawPixmap(Pixmap, int, int, int, int, int, int, int, int)}.
* *
* @author mzechner */ * @author mzechner
*/
public enum Filter { public enum Filter {
NearestNeighbour, BiLinear NearestNeighbour, BiLinear
} }
@ -94,9 +101,10 @@ public class Pixmap implements Disposable {
CanvasPixelArray pixels; CanvasPixelArray pixels;
private ImageElement imageElement; private ImageElement imageElement;
public Pixmap (FileHandle file) { public Pixmap(FileHandle file) {
this(((GwtFileHandle)file).preloader.images.get(file.path())); this(((GwtFileHandle) file).preloader.images.get(file.path()));
if (imageElement == null) throw new GdxRuntimeException("Couldn't load image '" + file.path() + "', file does not exist"); if (imageElement == null)
throw new GdxRuntimeException("Couldn't load image '" + file.path() + "', file does not exist");
} }
public Context2d getContext() { public Context2d getContext() {
@ -104,16 +112,16 @@ public class Pixmap implements Disposable {
return context; return context;
} }
private static Composite getComposite () { private static Composite getComposite() {
return Composite.SOURCE_OVER; return Composite.SOURCE_OVER;
} }
public Pixmap (ImageElement img) { public Pixmap(ImageElement img) {
this(-1, -1, img); this(-1, -1, img);
} }
public Pixmap (int width, int height, Format format) { public Pixmap(int width, int height, Format format) {
this(width, height, (ImageElement)null); this(width, height, (ImageElement) null);
} }
private Pixmap(int width, int height, ImageElement imageElement) { private Pixmap(int width, int height, ImageElement imageElement) {
@ -127,7 +135,7 @@ public class Pixmap implements Disposable {
pixmaps.put(id, this); pixmaps.put(id, this);
} }
private void create () { private void create() {
canvas = Canvas.createIfSupported(); canvas = Canvas.createIfSupported();
canvas.getCanvasElement().setWidth(width); canvas.getCanvasElement().setWidth(width);
canvas.getCanvasElement().setHeight(height); canvas.getCanvasElement().setHeight(height);
@ -135,13 +143,16 @@ public class Pixmap implements Disposable {
context.setGlobalCompositeOperation(getComposite()); context.setGlobalCompositeOperation(getComposite());
} }
public static String make (int r2, int g2, int b2, float a2) { public static String make(int r2, int g2, int b2, float a2) {
return "rgba(" + r2 + "," + g2 + "," + b2 + "," + a2 + ")"; return "rgba(" + r2 + "," + g2 + "," + b2 + "," + a2 + ")";
} }
/** Sets the type of {@link Blending} to be used for all operations. Default is {@link Blending#SourceOver}. /**
* @param blending the blending type */ * Sets the type of {@link Blending} to be used for all operations. Default is {@link Blending#SourceOver}.
public static void setBlending (Blending blending) { *
* @param blending the blending type
*/
public static void setBlending(Blending blending) {
Pixmap.blending = blending; Pixmap.blending = blending;
Composite composite = getComposite(); Composite composite = getComposite();
for (Pixmap pixmap : pixmaps.values()) { for (Pixmap pixmap : pixmaps.values()) {
@ -150,56 +161,61 @@ public class Pixmap implements Disposable {
} }
} }
/** @return the currently set {@link Blending} */ /**
public static Blending getBlending () { * @return the currently set {@link Blending}
*/
public static Blending getBlending() {
return blending; return blending;
} }
/** Sets the type of interpolation {@link Filter} to be used in conjunction with /**
* Sets the type of interpolation {@link Filter} to be used in conjunction with
* {@link Pixmap#drawPixmap(Pixmap, int, int, int, int, int, int, int, int)}. * {@link Pixmap#drawPixmap(Pixmap, int, int, int, int, int, int, int, int)}.
* @param filter the filter. */ *
public static void setFilter (Filter filter) { * @param filter the filter.
*/
public static void setFilter(Filter filter) {
} }
public Format getFormat () { public Format getFormat() {
return format; return format;
} }
public int getGLInternalFormat () { public int getGLInternalFormat() {
return GL20.GL_RGBA; return GL20.GL_RGBA;
} }
public int getGLFormat () { public int getGLFormat() {
return GL20.GL_RGBA; return GL20.GL_RGBA;
} }
public int getGLType () { public int getGLType() {
return GL20.GL_UNSIGNED_BYTE; return GL20.GL_UNSIGNED_BYTE;
} }
public int getWidth () { public int getWidth() {
return width; return width;
} }
public int getHeight () { public int getHeight() {
return height; return height;
} }
public Buffer getPixels () { public Buffer getPixels() {
return buffer; return buffer;
} }
@Override @Override
public void dispose () { public void dispose() {
pixmaps.remove(id); pixmaps.remove(id);
} }
public CanvasElement getCanvasElement () { public CanvasElement getCanvasElement() {
ensureCanvasExists(); ensureCanvasExists();
return canvas.getCanvasElement(); return canvas.getCanvasElement();
} }
private void ensureCanvasExists () { private void ensureCanvasExists() {
if (canvas == null) { if (canvas == null) {
create(); create();
if (imageElement != null) { if (imageElement != null) {
@ -210,17 +226,20 @@ public class Pixmap implements Disposable {
} }
} }
public boolean canUseImageElement () { public boolean canUseImageElement() {
return canvas == null && imageElement != null; return canvas == null && imageElement != null;
} }
public ImageElement getImageElement () { public ImageElement getImageElement() {
return imageElement; return imageElement;
} }
/** Sets the color for the following drawing operations /**
* @param color the color, encoded as RGBA8888 */ * Sets the color for the following drawing operations
public void setColor (int color) { *
* @param color the color, encoded as RGBA8888
*/
public void setColor(int color) {
ensureCanvasExists(); ensureCanvasExists();
r = (color >>> 24) & 0xff; r = (color >>> 24) & 0xff;
g = (color >>> 16) & 0xff; g = (color >>> 16) & 0xff;
@ -231,31 +250,38 @@ public class Pixmap implements Disposable {
context.setStrokeStyle(this.color); context.setStrokeStyle(this.color);
} }
/** Sets the color for the following drawing operations. /**
* Sets the color for the following drawing operations.
* *
* @param r The red component. * @param r The red component.
* @param g The green component. * @param g The green component.
* @param b The blue component. * @param b The blue component.
* @param a The alpha component. */ * @param a The alpha component.
public void setColor (float r, float g, float b, float a) { */
public void setColor(float r, float g, float b, float a) {
ensureCanvasExists(); ensureCanvasExists();
this.r = (int)(r * 255); this.r = (int) (r * 255);
this.g = (int)(g * 255); this.g = (int) (g * 255);
this.b = (int)(b * 255); this.b = (int) (b * 255);
this.a = a; this.a = a;
color = make(this.r, this.g, this.b, this.a); color = make(this.r, this.g, this.b, this.a);
context.setFillStyle(color); context.setFillStyle(color);
context.setStrokeStyle(this.color); context.setStrokeStyle(this.color);
} }
/** Sets the color for the following drawing operations. /**
* @param color The color. */ * Sets the color for the following drawing operations.
public void setColor (Color color) { *
* @param color The color.
*/
public void setColor(Color color) {
setColor(color.r, color.g, color.b, color.a); setColor(color.r, color.g, color.b, color.a);
} }
/** Fills the complete bitmap with the currently set color. */ /**
public void fill () { * Fills the complete bitmap with the currently set color.
*/
public void fill() {
ensureCanvasExists(); ensureCanvasExists();
context.clearRect(0, 0, getWidth(), getHeight()); context.clearRect(0, 0, getWidth(), getHeight());
rectangle(0, 0, getWidth(), getHeight(), DrawType.FILL); rectangle(0, 0, getWidth(), getHeight(), DrawType.FILL);
@ -268,116 +294,136 @@ public class Pixmap implements Disposable {
// */ // */
// public void setStrokeWidth (int width); // public void setStrokeWidth (int width);
/** Draws a line between the given coordinates using the currently set color. /**
* Draws a line between the given coordinates using the currently set color.
* *
* @param x The x-coodinate of the first point * @param x The x-coodinate of the first point
* @param y The y-coordinate of the first point * @param y The y-coordinate of the first point
* @param x2 The x-coordinate of the first point * @param x2 The x-coordinate of the first point
* @param y2 The y-coordinate of the first point */ * @param y2 The y-coordinate of the first point
public void drawLine (int x, int y, int x2, int y2) { */
public void drawLine(int x, int y, int x2, int y2) {
line(x, y, x2, y2, DrawType.STROKE); line(x, y, x2, y2, DrawType.STROKE);
} }
/** Draws a rectangle outline starting at x, y extending by width to the right and by height downwards (y-axis points downwards) /**
* Draws a rectangle outline starting at x, y extending by width to the right and by height downwards (y-axis points downwards)
* using the current color. * using the current color.
* *
* @param x The x coordinate * @param x The x coordinate
* @param y The y coordinate * @param y The y coordinate
* @param width The width in pixels * @param width The width in pixels
* @param height The height in pixels */ * @param height The height in pixels
public void drawRectangle (int x, int y, int width, int height) { */
public void drawRectangle(int x, int y, int width, int height) {
rectangle(x, y, width, height, DrawType.STROKE); rectangle(x, y, width, height, DrawType.STROKE);
} }
/** Draws an area form another Pixmap to this Pixmap. /**
* Draws an area form another Pixmap to this Pixmap.
* *
* @param pixmap The other Pixmap * @param pixmap The other Pixmap
* @param x The target x-coordinate (top left corner) * @param x The target x-coordinate (top left corner)
* @param y The target y-coordinate (top left corner) */ * @param y The target y-coordinate (top left corner)
public void drawPixmap (Pixmap pixmap, int x, int y) { */
public void drawPixmap(Pixmap pixmap, int x, int y) {
CanvasElement image = pixmap.getCanvasElement(); CanvasElement image = pixmap.getCanvasElement();
image(image, 0, 0, image.getWidth(), image.getHeight(), x, y, image.getWidth(), image.getHeight()); image(image, 0, 0, image.getWidth(), image.getHeight(), x, y, image.getWidth(), image.getHeight());
} }
/** Draws an area form another Pixmap to this Pixmap. /**
* Draws an area form another Pixmap to this Pixmap.
* *
* @param pixmap The other Pixmap * @param pixmap The other Pixmap
* @param x The target x-coordinate (top left corner) * @param x The target x-coordinate (top left corner)
* @param y The target y-coordinate (top left corner) * @param y The target y-coordinate (top left corner)
* @param srcx The source x-coordinate (top left corner) * @param srcx The source x-coordinate (top left corner)
* @param srcy The source y-coordinate (top left corner); * @param srcy The source y-coordinate (top left corner);
* @param srcWidth The width of the area form the other Pixmap in pixels * @param srcWidth The width of the area form the other Pixmap in pixels
* @param srcHeight The height of the area form the other Pixmap in pixles */ * @param srcHeight The height of the area form the other Pixmap in pixles
public void drawPixmap (Pixmap pixmap, int x, int y, int srcx, int srcy, int srcWidth, int srcHeight) { */
public void drawPixmap(Pixmap pixmap, int x, int y, int srcx, int srcy, int srcWidth, int srcHeight) {
CanvasElement image = pixmap.getCanvasElement(); CanvasElement image = pixmap.getCanvasElement();
image(image, srcx, srcy, srcWidth, srcHeight, x, y, srcWidth, srcHeight); image(image, srcx, srcy, srcWidth, srcHeight, x, y, srcWidth, srcHeight);
} }
/** Draws an area form another Pixmap to this Pixmap. This will automatically scale and stretch the source image to the /**
* Draws an area form another Pixmap to this Pixmap. This will automatically scale and stretch the source image to the
* specified target rectangle. Use {@link Pixmap#setFilter(Filter)} to specify the type of filtering to be used (nearest * specified target rectangle. Use {@link Pixmap#setFilter(Filter)} to specify the type of filtering to be used (nearest
* neighbour or bilinear). * neighbour or bilinear).
* *
* @param pixmap The other Pixmap * @param pixmap The other Pixmap
* @param srcx The source x-coordinate (top left corner) * @param srcx The source x-coordinate (top left corner)
* @param srcy The source y-coordinate (top left corner); * @param srcy The source y-coordinate (top left corner);
* @param srcWidth The width of the area form the other Pixmap in pixels * @param srcWidth The width of the area form the other Pixmap in pixels
* @param srcHeight The height of the area form the other Pixmap in pixles * @param srcHeight The height of the area form the other Pixmap in pixles
* @param dstx The target x-coordinate (top left corner) * @param dstx The target x-coordinate (top left corner)
* @param dsty The target y-coordinate (top left corner) * @param dsty The target y-coordinate (top left corner)
* @param dstWidth The target width * @param dstWidth The target width
* @param dstHeight the target height */ * @param dstHeight the target height
public void drawPixmap (Pixmap pixmap, int srcx, int srcy, int srcWidth, int srcHeight, int dstx, int dsty, int dstWidth, */
int dstHeight) { public void drawPixmap(Pixmap pixmap, int srcx, int srcy, int srcWidth, int srcHeight, int dstx, int dsty, int dstWidth,
int dstHeight) {
image(pixmap.getCanvasElement(), srcx, srcy, srcWidth, srcHeight, dstx, dsty, dstWidth, dstHeight); image(pixmap.getCanvasElement(), srcx, srcy, srcWidth, srcHeight, dstx, dsty, dstWidth, dstHeight);
} }
/** Fills a rectangle starting at x, y extending by width to the right and by height downwards (y-axis points downwards) using /**
* Fills a rectangle starting at x, y extending by width to the right and by height downwards (y-axis points downwards) using
* the current color. * the current color.
* *
* @param x The x coordinate * @param x The x coordinate
* @param y The y coordinate * @param y The y coordinate
* @param width The width in pixels * @param width The width in pixels
* @param height The height in pixels */ * @param height The height in pixels
public void fillRectangle (int x, int y, int width, int height) { */
public void fillRectangle(int x, int y, int width, int height) {
rectangle(x, y, width, height, DrawType.FILL); rectangle(x, y, width, height, DrawType.FILL);
} }
/** Draws a circle outline with the center at x,y and a radius using the current color and stroke width. /**
* Draws a circle outline with the center at x,y and a radius using the current color and stroke width.
* *
* @param x The x-coordinate of the center * @param x The x-coordinate of the center
* @param y The y-coordinate of the center * @param y The y-coordinate of the center
* @param radius The radius in pixels */ * @param radius The radius in pixels
public void drawCircle (int x, int y, int radius) { */
public void drawCircle(int x, int y, int radius) {
circle(x, y, radius, DrawType.STROKE); circle(x, y, radius, DrawType.STROKE);
} }
/** Fills a circle with the center at x,y and a radius using the current color. /**
* Fills a circle with the center at x,y and a radius using the current color.
* *
* @param x The x-coordinate of the center * @param x The x-coordinate of the center
* @param y The y-coordinate of the center * @param y The y-coordinate of the center
* @param radius The radius in pixels */ * @param radius The radius in pixels
public void fillCircle (int x, int y, int radius) { */
public void fillCircle(int x, int y, int radius) {
circle(x, y, radius, DrawType.FILL); circle(x, y, radius, DrawType.FILL);
} }
/** Fills a triangle with vertices at x1,y1 and x2,y2 and x3,y3 using the current color. /**
* Fills a triangle with vertices at x1,y1 and x2,y2 and x3,y3 using the current color.
* *
* @param x1 The x-coordinate of vertex 1 * @param x1 The x-coordinate of vertex 1
* @param y1 The y-coordinate of vertex 1 * @param y1 The y-coordinate of vertex 1
* @param x2 The x-coordinate of vertex 2 * @param x2 The x-coordinate of vertex 2
* @param y2 The y-coordinate of vertex 2 * @param y2 The y-coordinate of vertex 2
* @param x3 The x-coordinate of vertex 3 * @param x3 The x-coordinate of vertex 3
* @param y3 The y-coordinate of vertex 3 */ * @param y3 The y-coordinate of vertex 3
public void fillTriangle (int x1, int y1, int x2, int y2, int x3, int y3) { */
public void fillTriangle(int x1, int y1, int x2, int y2, int x3, int y3) {
triangle(x1, y1, x2, y2, x3, y3, DrawType.FILL); triangle(x1, y1, x2, y2, x3, y3, DrawType.FILL);
} }
/** Returns the 32-bit RGBA8888 value of the pixel at x, y. For Alpha formats the RGB components will be one. /**
* Returns the 32-bit RGBA8888 value of the pixel at x, y. For Alpha formats the RGB components will be one.
* *
* @param x The x-coordinate * @param x The x-coordinate
* @param y The y-coordinate * @param y The y-coordinate
* @return The pixel color in RGBA8888 format. */ * @return The pixel color in RGBA8888 format.
public int getPixel (int x, int y) { */
public int getPixel(int x, int y) {
ensureCanvasExists(); ensureCanvasExists();
if (pixels == null) pixels = context.getImageData(0, 0, width, height).getData(); if (pixels == null) pixels = context.getImageData(0, 0, width, height).getData();
int i = x * 4 + y * width * 4; int i = x * 4 + y * width * 4;
@ -388,25 +434,29 @@ public class Pixmap implements Disposable {
return (r << 24) | (g << 16) | (b << 8) | (a); return (r << 24) | (g << 16) | (b << 8) | (a);
} }
/** Draws a pixel at the given location with the current color. /**
* * Draws a pixel at the given location with the current color.
* @param x the x-coordinate
* @param y the y-coordinate */
public void drawPixel (int x, int y) {
rectangle(x, y, 1, 1, DrawType.FILL);
}
/** Draws a pixel at the given location with the given color.
* *
* @param x the x-coordinate * @param x the x-coordinate
* @param y the y-coordinate * @param y the y-coordinate
* @param color the color in RGBA8888 format. */ */
public void drawPixel (int x, int y, int color) { public void drawPixel(int x, int y) {
rectangle(x, y, 1, 1, DrawType.FILL);
}
/**
* Draws a pixel at the given location with the given color.
*
* @param x the x-coordinate
* @param y the y-coordinate
* @param color the color in RGBA8888 format.
*/
public void drawPixel(int x, int y, int color) {
setColor(color); setColor(color);
drawPixel(x, y); drawPixel(x, y);
} }
private void circle (int x, int y, int radius, DrawType drawType) { private void circle(int x, int y, int radius, DrawType drawType) {
ensureCanvasExists(); ensureCanvasExists();
if (blending == Blending.None) { if (blending == Blending.None) {
context.setFillStyle(clearColor); context.setFillStyle(clearColor);
@ -478,10 +528,10 @@ public class Pixmap implements Disposable {
context.setStrokeStyle(clearColor); context.setStrokeStyle(clearColor);
context.setGlobalCompositeOperation("destination-out"); context.setGlobalCompositeOperation("destination-out");
context.beginPath(); context.beginPath();
context.moveTo(x1,y1); context.moveTo(x1, y1);
context.lineTo(x2,y2); context.lineTo(x2, y2);
context.lineTo(x3,y3); context.lineTo(x3, y3);
context.lineTo(x1,y1); context.lineTo(x1, y1);
fillOrStrokePath(drawType); fillOrStrokePath(drawType);
context.closePath(); context.closePath();
context.setFillStyle(color); context.setFillStyle(color);
@ -489,16 +539,16 @@ public class Pixmap implements Disposable {
context.setGlobalCompositeOperation(Composite.SOURCE_OVER); context.setGlobalCompositeOperation(Composite.SOURCE_OVER);
} }
context.beginPath(); context.beginPath();
context.moveTo(x1,y1); context.moveTo(x1, y1);
context.lineTo(x2,y2); context.lineTo(x2, y2);
context.lineTo(x3,y3); context.lineTo(x3, y3);
context.lineTo(x1,y1); context.lineTo(x1, y1);
fillOrStrokePath(drawType); fillOrStrokePath(drawType);
context.closePath(); context.closePath();
pixels = null; pixels = null;
} }
private void image (CanvasElement image, int srcX, int srcY, int srcWidth, int srcHeight, int dstX, int dstY, int dstWidth, int dstHeight) { private void image(CanvasElement image, int srcX, int srcY, int srcWidth, int srcHeight, int dstX, int dstY, int dstWidth, int dstHeight) {
ensureCanvasExists(); ensureCanvasExists();
if (blending == Blending.None) { if (blending == Blending.None) {
context.setFillStyle(clearColor); context.setFillStyle(clearColor);