From fc73dc2cc275169c8620833ce99144a1db88c075 Mon Sep 17 00:00:00 2001 From: Raven Szewczyk Date: Wed, 14 Feb 2024 21:12:44 +0000 Subject: [PATCH] Add missing lwjgl.util subpackages Closes #92 --- src/main/java/org/lwjglx/PointerBuffer.java | 14 + .../lwjglx/util/input/ControllerAdapter.java | 326 ++++ .../java/org/lwjglx/util/jinput/KeyMap.java | 290 ++++ .../util/jinput/LWJGLEnvironmentPlugin.java | 51 + .../org/lwjglx/util/jinput/LWJGLKeyboard.java | 119 ++ .../org/lwjglx/util/jinput/LWJGLMouse.java | 182 ++ .../org/lwjglx/util/mapped/CacheLinePad.java | 61 + .../org/lwjglx/util/mapped/CacheLineSize.java | 146 ++ .../org/lwjglx/util/mapped/CacheUtil.java | 195 +++ .../org/lwjglx/util/mapped/MappedField.java | 60 + .../org/lwjglx/util/mapped/MappedForeach.java | 66 + .../org/lwjglx/util/mapped/MappedHelper.java | 385 +++++ .../org/lwjglx/util/mapped/MappedObject.java | 286 +++ .../util/mapped/MappedObjectClassLoader.java | 185 ++ .../util/mapped/MappedObjectTransformer.java | 1530 +++++++++++++++++ .../util/mapped/MappedObjectUnsafe.java | 103 ++ .../org/lwjglx/util/mapped/MappedSet.java | 64 + .../org/lwjglx/util/mapped/MappedSet2.java | 51 + .../org/lwjglx/util/mapped/MappedSet3.java | 54 + .../org/lwjglx/util/mapped/MappedSet4.java | 56 + .../org/lwjglx/util/mapped/MappedType.java | 98 ++ .../java/org/lwjglx/util/mapped/Pointer.java | 45 + 22 files changed, 4367 insertions(+) create mode 100644 src/main/java/org/lwjglx/util/input/ControllerAdapter.java create mode 100644 src/main/java/org/lwjglx/util/jinput/KeyMap.java create mode 100644 src/main/java/org/lwjglx/util/jinput/LWJGLEnvironmentPlugin.java create mode 100644 src/main/java/org/lwjglx/util/jinput/LWJGLKeyboard.java create mode 100644 src/main/java/org/lwjglx/util/jinput/LWJGLMouse.java create mode 100644 src/main/java/org/lwjglx/util/mapped/CacheLinePad.java create mode 100644 src/main/java/org/lwjglx/util/mapped/CacheLineSize.java create mode 100644 src/main/java/org/lwjglx/util/mapped/CacheUtil.java create mode 100644 src/main/java/org/lwjglx/util/mapped/MappedField.java create mode 100644 src/main/java/org/lwjglx/util/mapped/MappedForeach.java create mode 100644 src/main/java/org/lwjglx/util/mapped/MappedHelper.java create mode 100644 src/main/java/org/lwjglx/util/mapped/MappedObject.java create mode 100644 src/main/java/org/lwjglx/util/mapped/MappedObjectClassLoader.java create mode 100644 src/main/java/org/lwjglx/util/mapped/MappedObjectTransformer.java create mode 100644 src/main/java/org/lwjglx/util/mapped/MappedObjectUnsafe.java create mode 100644 src/main/java/org/lwjglx/util/mapped/MappedSet.java create mode 100644 src/main/java/org/lwjglx/util/mapped/MappedSet2.java create mode 100644 src/main/java/org/lwjglx/util/mapped/MappedSet3.java create mode 100644 src/main/java/org/lwjglx/util/mapped/MappedSet4.java create mode 100644 src/main/java/org/lwjglx/util/mapped/MappedType.java create mode 100644 src/main/java/org/lwjglx/util/mapped/Pointer.java diff --git a/src/main/java/org/lwjglx/PointerBuffer.java b/src/main/java/org/lwjglx/PointerBuffer.java index 1cd17b8..be42979 100644 --- a/src/main/java/org/lwjglx/PointerBuffer.java +++ b/src/main/java/org/lwjglx/PointerBuffer.java @@ -50,6 +50,16 @@ public class PointerBuffer extends org.lwjgl.PointerBuffer { super(ver3.address(), getContainer(ver3), ver3.position(), ver3.position(), ver3.limit(), ver3.capacity()); } + public PointerBuffer(ByteBuffer buffer) { + this( + org.lwjgl.system.MemoryUtil.memAddress(buffer), + buffer, + 0, + buffer.position(), + buffer.limit(), + buffer.capacity()); + } + /** * Allocates a new pointer buffer. * @@ -85,4 +95,8 @@ public class PointerBuffer extends org.lwjgl.PointerBuffer { public static PointerBuffer create(ByteBuffer source) { return new PointerBuffer(org.lwjgl.PointerBuffer.create(source)); } + + public static int getPointerSize() { + return org.lwjgl.PointerBuffer.POINTER_SIZE; + } } diff --git a/src/main/java/org/lwjglx/util/input/ControllerAdapter.java b/src/main/java/org/lwjglx/util/input/ControllerAdapter.java new file mode 100644 index 0000000..5cfac02 --- /dev/null +++ b/src/main/java/org/lwjglx/util/input/ControllerAdapter.java @@ -0,0 +1,326 @@ +/* + * Copyright (c) 2002-2008 LWJGL Project + * 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 'LWJGL' 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 org.lwjglx.util.input; + +import org.lwjgl.input.Controller; + +/** + * Adapter for the Controller interface. It can be used as placeholder + * Controller, which doesn't do anything (eg if Controllers.create() fails and + * you don't want to take care of that). + * + * @author Onyx, Aho and all the other aliases... + */ +public class ControllerAdapter implements Controller { + + /** + * Get the name assigned to this controller. + * + * @return The name assigned to this controller + */ + public String getName() { + return "Dummy Controller"; + } + + /** + * Get the index of this controller in the collection + * + * @return The index of this controller in the collection + */ + public int getIndex() { + return 0; // -1 maybe? + } + + /** + * Retrieve the number of buttons available on this controller + * + * @return The number of butotns available on this controller + */ + public int getButtonCount() { + return 0; + } + + /** + * Get the name of the specified button. Be warned, often this is as + * exciting as "Button X" + * + * @param index The index of the button whose name should be retrieved + * @return The name of the button requested + */ + public String getButtonName(int index) { + return "button n/a"; + } + + /** + * Check if a button is currently pressed + * + * @param index The button to check + * @return True if the button is currently pressed + */ + public boolean isButtonPressed(int index) { + return false; + } + + /** + * Poll the controller for new data. This will also update events + */ + public void poll() {} + + /** + * Get the X-Axis value of the POV on this controller + * + * @return The X-Axis value of the POV on this controller + */ + public float getPovX() { + return 0f; + } + + /** + * Get the Y-Axis value of the POV on this controller + * + * @return The Y-Axis value of the POV on this controller + */ + public float getPovY() { + return 0f; + } + + /** + * Get the dead zone for a specified axis + * + * @param index The index of the axis for which to retrieve the dead zone + * @return The dead zone for the specified axis + */ + public float getDeadZone(int index) { + return 0f; + } + + /** + * Set the dead zone for the specified axis + * + * @param index The index of hte axis for which to set the dead zone + * @param zone The dead zone to use for the specified axis + */ + public void setDeadZone(int index, float zone) {} + + /** + * Retrieve the number of axes available on this controller. + * + * @return The number of axes available on this controller. + */ + public int getAxisCount() { + return 0; + } + + /** + * Get the name that's given to the specified axis + * + * @param index The index of the axis whose name should be retrieved + * @return The name of the specified axis. + */ + public String getAxisName(int index) { + return "axis n/a"; + } + + /** + * Retrieve the value thats currently available on a specified axis. The + * value will always be between 1.0 and -1.0 and will calibrate as values + * are passed read. It may be useful to get the player to wiggle the + * joystick from side to side to get the calibration right. + * + * @param index The index of axis to be read + * @return The value from the specified axis. + */ + public float getAxisValue(int index) { + return 0f; + } + + /** + * Get the value from the X axis if there is one. If no X axis is defined a + * zero value will be returned. + * + * @return The value from the X axis + */ + public float getXAxisValue() { + return 0f; + } + + /** + * Get the dead zone for the X axis. + * + * @return The dead zone for the X axis + */ + public float getXAxisDeadZone() { + return 0f; + } + + /** + * Set the dead zone for the X axis + * + * @param zone The dead zone to use for the X axis + */ + public void setXAxisDeadZone(float zone) {} + + /** + * Get the value from the Y axis if there is one. If no Y axis is defined a + * zero value will be returned. + * + * @return The value from the Y axis + */ + public float getYAxisValue() { + return 0f; + } + + /** + * Get the dead zone for the Y axis. + * + * @return The dead zone for the Y axis + */ + public float getYAxisDeadZone() { + return 0f; + } + + /** + * Set the dead zone for the Y axis + * + * @param zone The dead zone to use for the Y axis + */ + public void setYAxisDeadZone(float zone) {} + + /** + * Get the value from the Z axis if there is one. If no Z axis is defined a + * zero value will be returned. + * + * @return The value from the Z axis + */ + public float getZAxisValue() { + return 0f; + } + + /** + * Get the dead zone for the Z axis. + * + * @return The dead zone for the Z axis + */ + public float getZAxisDeadZone() { + return 0f; + } + + /** + * Set the dead zone for the Z axis + * + * @param zone The dead zone to use for the Z axis + */ + public void setZAxisDeadZone(float zone) {} + + /** + * Get the value from the RX axis if there is one. If no RX axis is defined + * a zero value will be returned. + * + * @return The value from the RX axis + */ + public float getRXAxisValue() { + return 0f; + } + + /** + * Get the dead zone for the RX axis. + * + * @return The dead zone for the RX axis + */ + public float getRXAxisDeadZone() { + return 0f; + } + + /** + * Set the dead zone for the RX axis + * + * @param zone The dead zone to use for the RX axis + */ + public void setRXAxisDeadZone(float zone) {} + + /** + * Get the value from the RY axis if there is one. If no RY axis is defined + * a zero value will be returned. + * + * @return The value from the RY axis + */ + public float getRYAxisValue() { + return 0f; + } + + /** + * Get the dead zone for the RY axis. + * + * @return The dead zone for the RY axis + */ + public float getRYAxisDeadZone() { + return 0f; + } + + /** + * Set the dead zone for the RY axis + * + * @param zone The dead zone to use for the RY axis + */ + public void setRYAxisDeadZone(float zone) {} + + /** + * Get the value from the RZ axis if there is one. If no RZ axis is defined + * a zero value will be returned. + * + * @return The value from the RZ axis + */ + public float getRZAxisValue() { + return 0f; + } + + /** + * Get the dead zone for the RZ axis. + * + * @return The dead zone for the RZ axis + */ + public float getRZAxisDeadZone() { + return 0f; + } + + /** + * Set the dead zone for the RZ axis + * + * @param zone The dead zone to use for the RZ axis + */ + public void setRZAxisDeadZone(float zone) {} + + public int getRumblerCount() { + return 0; + } + + public String getRumblerName(int index) { + return "rumber n/a"; + } + + public void setRumblerStrength(int index, float strength) {} +} diff --git a/src/main/java/org/lwjglx/util/jinput/KeyMap.java b/src/main/java/org/lwjglx/util/jinput/KeyMap.java new file mode 100644 index 0000000..bed6825 --- /dev/null +++ b/src/main/java/org/lwjglx/util/jinput/KeyMap.java @@ -0,0 +1,290 @@ +/* + * Copyright (c) 2002-2008 LWJGL Project + * 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 'LWJGL' 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 org.lwjglx.util.jinput; + +import net.java.games.input.Component; + +import org.lwjgl.input.Keyboard; + +/** + * @author elias + */ +final class KeyMap { + + public static Component.Identifier.Key map(int lwjgl_key_code) { + switch (lwjgl_key_code) { + case Keyboard.KEY_ESCAPE: + return Component.Identifier.Key.ESCAPE; + case Keyboard.KEY_1: + return Component.Identifier.Key._1; + case Keyboard.KEY_2: + return Component.Identifier.Key._2; + case Keyboard.KEY_3: + return Component.Identifier.Key._3; + case Keyboard.KEY_4: + return Component.Identifier.Key._4; + case Keyboard.KEY_5: + return Component.Identifier.Key._5; + case Keyboard.KEY_6: + return Component.Identifier.Key._6; + case Keyboard.KEY_7: + return Component.Identifier.Key._7; + case Keyboard.KEY_8: + return Component.Identifier.Key._8; + case Keyboard.KEY_9: + return Component.Identifier.Key._9; + case Keyboard.KEY_0: + return Component.Identifier.Key._0; + case Keyboard.KEY_MINUS: + return Component.Identifier.Key.MINUS; + case Keyboard.KEY_EQUALS: + return Component.Identifier.Key.EQUALS; + case Keyboard.KEY_BACK: + return Component.Identifier.Key.BACK; + case Keyboard.KEY_TAB: + return Component.Identifier.Key.TAB; + case Keyboard.KEY_Q: + return Component.Identifier.Key.Q; + case Keyboard.KEY_W: + return Component.Identifier.Key.W; + case Keyboard.KEY_E: + return Component.Identifier.Key.E; + case Keyboard.KEY_R: + return Component.Identifier.Key.R; + case Keyboard.KEY_T: + return Component.Identifier.Key.T; + case Keyboard.KEY_Y: + return Component.Identifier.Key.Y; + case Keyboard.KEY_U: + return Component.Identifier.Key.U; + case Keyboard.KEY_I: + return Component.Identifier.Key.I; + case Keyboard.KEY_O: + return Component.Identifier.Key.O; + case Keyboard.KEY_P: + return Component.Identifier.Key.P; + case Keyboard.KEY_LBRACKET: + return Component.Identifier.Key.LBRACKET; + case Keyboard.KEY_RBRACKET: + return Component.Identifier.Key.RBRACKET; + case Keyboard.KEY_RETURN: + return Component.Identifier.Key.RETURN; + case Keyboard.KEY_LCONTROL: + return Component.Identifier.Key.LCONTROL; + case Keyboard.KEY_A: + return Component.Identifier.Key.A; + case Keyboard.KEY_S: + return Component.Identifier.Key.S; + case Keyboard.KEY_D: + return Component.Identifier.Key.D; + case Keyboard.KEY_F: + return Component.Identifier.Key.F; + case Keyboard.KEY_G: + return Component.Identifier.Key.G; + case Keyboard.KEY_H: + return Component.Identifier.Key.H; + case Keyboard.KEY_J: + return Component.Identifier.Key.J; + case Keyboard.KEY_K: + return Component.Identifier.Key.K; + case Keyboard.KEY_L: + return Component.Identifier.Key.L; + case Keyboard.KEY_SEMICOLON: + return Component.Identifier.Key.SEMICOLON; + case Keyboard.KEY_APOSTROPHE: + return Component.Identifier.Key.APOSTROPHE; + case Keyboard.KEY_GRAVE: + return Component.Identifier.Key.GRAVE; + case Keyboard.KEY_LSHIFT: + return Component.Identifier.Key.LSHIFT; + case Keyboard.KEY_BACKSLASH: + return Component.Identifier.Key.BACKSLASH; + case Keyboard.KEY_Z: + return Component.Identifier.Key.Z; + case Keyboard.KEY_X: + return Component.Identifier.Key.X; + case Keyboard.KEY_C: + return Component.Identifier.Key.C; + case Keyboard.KEY_V: + return Component.Identifier.Key.V; + case Keyboard.KEY_B: + return Component.Identifier.Key.B; + case Keyboard.KEY_N: + return Component.Identifier.Key.N; + case Keyboard.KEY_M: + return Component.Identifier.Key.M; + case Keyboard.KEY_COMMA: + return Component.Identifier.Key.COMMA; + case Keyboard.KEY_PERIOD: + return Component.Identifier.Key.PERIOD; + case Keyboard.KEY_SLASH: + return Component.Identifier.Key.SLASH; + case Keyboard.KEY_RSHIFT: + return Component.Identifier.Key.RSHIFT; + case Keyboard.KEY_MULTIPLY: + return Component.Identifier.Key.MULTIPLY; + case Keyboard.KEY_LMENU: + return Component.Identifier.Key.LALT; + case Keyboard.KEY_SPACE: + return Component.Identifier.Key.SPACE; + case Keyboard.KEY_CAPITAL: + return Component.Identifier.Key.CAPITAL; + case Keyboard.KEY_F1: + return Component.Identifier.Key.F1; + case Keyboard.KEY_F2: + return Component.Identifier.Key.F2; + case Keyboard.KEY_F3: + return Component.Identifier.Key.F3; + case Keyboard.KEY_F4: + return Component.Identifier.Key.F4; + case Keyboard.KEY_F5: + return Component.Identifier.Key.F5; + case Keyboard.KEY_F6: + return Component.Identifier.Key.F6; + case Keyboard.KEY_F7: + return Component.Identifier.Key.F7; + case Keyboard.KEY_F8: + return Component.Identifier.Key.F8; + case Keyboard.KEY_F9: + return Component.Identifier.Key.F9; + case Keyboard.KEY_F10: + return Component.Identifier.Key.F10; + case Keyboard.KEY_NUMLOCK: + return Component.Identifier.Key.NUMLOCK; + case Keyboard.KEY_SCROLL: + return Component.Identifier.Key.SCROLL; + case Keyboard.KEY_NUMPAD7: + return Component.Identifier.Key.NUMPAD7; + case Keyboard.KEY_NUMPAD8: + return Component.Identifier.Key.NUMPAD8; + case Keyboard.KEY_NUMPAD9: + return Component.Identifier.Key.NUMPAD9; + case Keyboard.KEY_SUBTRACT: + return Component.Identifier.Key.SUBTRACT; + case Keyboard.KEY_NUMPAD4: + return Component.Identifier.Key.NUMPAD4; + case Keyboard.KEY_NUMPAD5: + return Component.Identifier.Key.NUMPAD5; + case Keyboard.KEY_NUMPAD6: + return Component.Identifier.Key.NUMPAD6; + case Keyboard.KEY_ADD: + return Component.Identifier.Key.ADD; + case Keyboard.KEY_NUMPAD1: + return Component.Identifier.Key.NUMPAD1; + case Keyboard.KEY_NUMPAD2: + return Component.Identifier.Key.NUMPAD2; + case Keyboard.KEY_NUMPAD3: + return Component.Identifier.Key.NUMPAD3; + case Keyboard.KEY_NUMPAD0: + return Component.Identifier.Key.NUMPAD0; + case Keyboard.KEY_DECIMAL: + return Component.Identifier.Key.DECIMAL; + case Keyboard.KEY_F11: + return Component.Identifier.Key.F11; + case Keyboard.KEY_F12: + return Component.Identifier.Key.F12; + case Keyboard.KEY_F13: + return Component.Identifier.Key.F13; + case Keyboard.KEY_F14: + return Component.Identifier.Key.F14; + case Keyboard.KEY_F15: + return Component.Identifier.Key.F15; + case Keyboard.KEY_KANA: + return Component.Identifier.Key.KANA; + case Keyboard.KEY_CONVERT: + return Component.Identifier.Key.CONVERT; + case Keyboard.KEY_NOCONVERT: + return Component.Identifier.Key.NOCONVERT; + case Keyboard.KEY_YEN: + return Component.Identifier.Key.YEN; + case Keyboard.KEY_NUMPADEQUALS: + return Component.Identifier.Key.NUMPADEQUAL; + case Keyboard.KEY_CIRCUMFLEX: + return Component.Identifier.Key.CIRCUMFLEX; + case Keyboard.KEY_AT: + return Component.Identifier.Key.AT; + case Keyboard.KEY_COLON: + return Component.Identifier.Key.COLON; + case Keyboard.KEY_UNDERLINE: + return Component.Identifier.Key.UNDERLINE; + case Keyboard.KEY_KANJI: + return Component.Identifier.Key.KANJI; + case Keyboard.KEY_STOP: + return Component.Identifier.Key.STOP; + case Keyboard.KEY_AX: + return Component.Identifier.Key.AX; + case Keyboard.KEY_UNLABELED: + return Component.Identifier.Key.UNLABELED; + case Keyboard.KEY_NUMPADENTER: + return Component.Identifier.Key.NUMPADENTER; + case Keyboard.KEY_RCONTROL: + return Component.Identifier.Key.RCONTROL; + case Keyboard.KEY_NUMPADCOMMA: + return Component.Identifier.Key.NUMPADCOMMA; + case Keyboard.KEY_DIVIDE: + return Component.Identifier.Key.DIVIDE; + case Keyboard.KEY_SYSRQ: + return Component.Identifier.Key.SYSRQ; + case Keyboard.KEY_RMENU: + return Component.Identifier.Key.RALT; + case Keyboard.KEY_PAUSE: + return Component.Identifier.Key.PAUSE; + case Keyboard.KEY_HOME: + return Component.Identifier.Key.HOME; + case Keyboard.KEY_UP: + return Component.Identifier.Key.UP; + case Keyboard.KEY_PRIOR: + return Component.Identifier.Key.PAGEUP; + case Keyboard.KEY_LEFT: + return Component.Identifier.Key.LEFT; + case Keyboard.KEY_RIGHT: + return Component.Identifier.Key.RIGHT; + case Keyboard.KEY_END: + return Component.Identifier.Key.END; + case Keyboard.KEY_DOWN: + return Component.Identifier.Key.DOWN; + case Keyboard.KEY_NEXT: + return Component.Identifier.Key.PAGEDOWN; + case Keyboard.KEY_INSERT: + return Component.Identifier.Key.INSERT; + case Keyboard.KEY_DELETE: + return Component.Identifier.Key.DELETE; + case Keyboard.KEY_LMETA: + return Component.Identifier.Key.LWIN; + case Keyboard.KEY_RMETA: + return Component.Identifier.Key.RWIN; + case Keyboard.KEY_APPS: + return Component.Identifier.Key.APPS; + case Keyboard.KEY_POWER: + return Component.Identifier.Key.POWER; + case Keyboard.KEY_SLEEP: + return Component.Identifier.Key.SLEEP; + default: + return Component.Identifier.Key.UNKNOWN; + } + } +} diff --git a/src/main/java/org/lwjglx/util/jinput/LWJGLEnvironmentPlugin.java b/src/main/java/org/lwjglx/util/jinput/LWJGLEnvironmentPlugin.java new file mode 100644 index 0000000..f08a024 --- /dev/null +++ b/src/main/java/org/lwjglx/util/jinput/LWJGLEnvironmentPlugin.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2002-2008 LWJGL Project + * 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 'LWJGL' 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 org.lwjglx.util.jinput; + +import net.java.games.input.Controller; +import net.java.games.input.ControllerEnvironment; +import net.java.games.util.plugins.Plugin; + +/** + * @author elias + */ +public class LWJGLEnvironmentPlugin extends ControllerEnvironment implements Plugin { + + private final Controller[] controllers; + + public LWJGLEnvironmentPlugin() { + this.controllers = new Controller[] { new LWJGLKeyboard(), new LWJGLMouse() }; + } + + public Controller[] getControllers() { + return controllers; + } + + public boolean isSupported() { + return true; + } +} diff --git a/src/main/java/org/lwjglx/util/jinput/LWJGLKeyboard.java b/src/main/java/org/lwjglx/util/jinput/LWJGLKeyboard.java new file mode 100644 index 0000000..1d907c5 --- /dev/null +++ b/src/main/java/org/lwjglx/util/jinput/LWJGLKeyboard.java @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2002-2008 LWJGL Project + * 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 'LWJGL' 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 org.lwjglx.util.jinput; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +import net.java.games.input.AbstractComponent; +import net.java.games.input.Component; +import net.java.games.input.Controller; +import net.java.games.input.Event; +import net.java.games.input.Keyboard; +import net.java.games.input.Rumbler; + +/** + * @author elias + */ +final class LWJGLKeyboard extends Keyboard { + + LWJGLKeyboard() { + super("LWJGLKeyboard", createComponents(), new Controller[] {}, new Rumbler[] {}); + } + + private static Component[] createComponents() { + List components = new ArrayList(); + Field[] vkey_fields = org.lwjglx.input.Keyboard.class.getFields(); + for (Field vkey_field : vkey_fields) { + try { + if (Modifier.isStatic(vkey_field.getModifiers()) && vkey_field.getType() == int.class + && vkey_field.getName() + .startsWith("KEY_")) { + int vkey_code = vkey_field.getInt(null); + Component.Identifier.Key key_id = KeyMap.map(vkey_code); + if (key_id != Component.Identifier.Key.UNKNOWN) components.add(new Key(key_id, vkey_code)); + } + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } + return components.toArray(new Component[components.size()]); + } + + public synchronized void pollDevice() throws IOException { + if (!org.lwjglx.input.Keyboard.isCreated()) return; + org.lwjglx.input.Keyboard.poll(); + for (Component component : getComponents()) { + Key key = (Key) component; + key.update(); + } + } + + protected synchronized boolean getNextDeviceEvent(Event event) throws IOException { + if (!org.lwjglx.input.Keyboard.isCreated()) return false; + if (!org.lwjglx.input.Keyboard.next()) return false; + int lwjgl_key = org.lwjglx.input.Keyboard.getEventKey(); + if (lwjgl_key == org.lwjglx.input.Keyboard.KEY_NONE) return false; + Component.Identifier.Key key_id = KeyMap.map(lwjgl_key); + if (key_id == null) return false; + Component key = getComponent(key_id); + if (key == null) return false; + float value = org.lwjglx.input.Keyboard.getEventKeyState() ? 1 : 0; + event.set(key, value, org.lwjglx.input.Keyboard.getEventNanoseconds()); + return true; + } + + private static final class Key extends AbstractComponent { + + private final int lwjgl_key; + private float value; + + Key(Identifier.Key key_id, int lwjgl_key) { + super(key_id.getName(), key_id); + this.lwjgl_key = lwjgl_key; + } + + public void update() { + this.value = org.lwjglx.input.Keyboard.isKeyDown(lwjgl_key) ? 1 : 0; + } + + protected float poll() { + return value; + } + + public boolean isRelative() { + return false; + } + + public boolean isAnalog() { + return false; + } + } +} diff --git a/src/main/java/org/lwjglx/util/jinput/LWJGLMouse.java b/src/main/java/org/lwjglx/util/jinput/LWJGLMouse.java new file mode 100644 index 0000000..54faf1d --- /dev/null +++ b/src/main/java/org/lwjglx/util/jinput/LWJGLMouse.java @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2002-2008 LWJGL Project + * 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 'LWJGL' 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 org.lwjglx.util.jinput; + +import java.io.IOException; + +import net.java.games.input.AbstractComponent; +import net.java.games.input.Component; +import net.java.games.input.Controller; +import net.java.games.input.Event; +import net.java.games.input.Mouse; +import net.java.games.input.Rumbler; + +/** + * @author elias + */ +final class LWJGLMouse extends Mouse { + + private static final int EVENT_X = 1; + private static final int EVENT_Y = 2; + private static final int EVENT_WHEEL = 3; + private static final int EVENT_BUTTON = 4; + private static final int EVENT_DONE = 5; + + private int event_state = EVENT_DONE; + + LWJGLMouse() { + super("LWJGLMouse", createComponents(), new Controller[] {}, new Rumbler[] {}); + } + + private static Component[] createComponents() { + return new Component[] { new Axis(Component.Identifier.Axis.X), new Axis(Component.Identifier.Axis.Y), + new Axis(Component.Identifier.Axis.Z), new Button(Component.Identifier.Button.LEFT), + new Button(Component.Identifier.Button.MIDDLE), new Button(Component.Identifier.Button.RIGHT) }; + } + + public synchronized void pollDevice() throws IOException { + if (!org.lwjglx.input.Mouse.isCreated()) return; + org.lwjglx.input.Mouse.poll(); + for (int i = 0; i < 3; i++) setButtonState(i); + } + + private Button map(int lwjgl_button) { + switch (lwjgl_button) { + case 0: + return (Button) getLeft(); + case 1: + return (Button) getRight(); + case 2: + return (Button) getMiddle(); + default: + return null; + } + } + + private void setButtonState(int lwjgl_button) { + Button button = map(lwjgl_button); + if (button != null) button.setValue(org.lwjglx.input.Mouse.isButtonDown(lwjgl_button) ? 1 : 0); + } + + protected synchronized boolean getNextDeviceEvent(Event event) throws IOException { + if (!org.lwjglx.input.Mouse.isCreated()) return false; + while (true) { + long nanos = org.lwjglx.input.Mouse.getEventNanoseconds(); + switch (event_state) { + case EVENT_X: + event_state = EVENT_Y; + int dx = org.lwjglx.input.Mouse.getEventDX(); + if (dx != 0) { + event.set(getX(), dx, nanos); + return true; + } + break; + case EVENT_Y: + event_state = EVENT_WHEEL; + /* + * We must negate the y coord since lwjgl uses the + * OpenGL coordinate system + */ + int dy = -org.lwjglx.input.Mouse.getEventDY(); + if (dy != 0) { + event.set(getY(), dy, nanos); + return true; + } + break; + case EVENT_WHEEL: + event_state = EVENT_BUTTON; + int dwheel = org.lwjglx.input.Mouse.getEventDWheel(); + if (dwheel != 0) { + event.set(getWheel(), dwheel, nanos); + return true; + } + break; + case EVENT_BUTTON: + event_state = EVENT_DONE; + int lwjgl_button = org.lwjglx.input.Mouse.getEventButton(); + if (lwjgl_button != -1) { + Button button = map(lwjgl_button); + if (button != null) { + event.set(button, org.lwjglx.input.Mouse.getEventButtonState() ? 1f : 0f, nanos); + return true; + } + } + break; + case EVENT_DONE: + if (!org.lwjglx.input.Mouse.next()) return false; + event_state = EVENT_X; + break; + default: + break; + } + } + } + + static final class Axis extends AbstractComponent { + + Axis(Identifier.Axis axis_id) { + super(axis_id.getName(), axis_id); + } + + public boolean isRelative() { + return true; + } + + protected float poll() throws IOException { + return 0; + } + + public boolean isAnalog() { + return true; + } + } + + static final class Button extends AbstractComponent { + + private float value; + + Button(Identifier.Button button_id) { + super(button_id.getName(), button_id); + } + + void setValue(float value) { + this.value = value; + } + + protected float poll() throws IOException { + return value; + } + + public boolean isRelative() { + return false; + } + + public boolean isAnalog() { + return false; + } + } +} diff --git a/src/main/java/org/lwjglx/util/mapped/CacheLinePad.java b/src/main/java/org/lwjglx/util/mapped/CacheLinePad.java new file mode 100644 index 0000000..088fcbc --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/CacheLinePad.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * 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 'LWJGL' 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 org.lwjglx.util.mapped; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * When this annotation is used on a field, automatic cache-line-sized padding + * will be inserted around the field. This is useful in multi-threaded algorithms + * to avoid cache line false sharing. The annotation defaults to padding after + * the field, but can be changed to before or both before and after. It can be + * applied to both mapped object fields and POJO primitive fields. + * + * @author Spasi + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface CacheLinePad { + + /** + * When true, cache-line padding will be inserted before the field. + * + * @return true if cache-line padding will be inserted before the field + */ + boolean before() default false; + + /** + * When true, cache-line padding will be inserted after the field. + * + * @return true if cache-line padding will be inserted after the field + */ + boolean after() default true; + +} diff --git a/src/main/java/org/lwjglx/util/mapped/CacheLineSize.java b/src/main/java/org/lwjglx/util/mapped/CacheLineSize.java new file mode 100644 index 0000000..3fe5c9d --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/CacheLineSize.java @@ -0,0 +1,146 @@ +package org.lwjglx.util.mapped; + +import static org.lwjglx.util.mapped.MappedHelper.ivget; +import static org.lwjglx.util.mapped.MappedHelper.ivput; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.IntBuffer; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorCompletionService; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.lwjglx.LWJGLUtil; +import org.lwjglx.MemoryUtil; + +/** + * This micro-benchmark tries to detect the CPU's cache line size. This is + * done by exploiting cache line false sharing in multi-threaded code: + * When 2 threads simultaneously access the same cache line (and at least + * 1 access is a write), performance drops considerably. We detect this + * performance drop while decreasing the memory padding in every test step. + * + * @author Spasi + */ +final class CacheLineSize { + + private CacheLineSize() {} + + static int getCacheLineSize() { + final int THREADS = 2; + final int REPEATS = 100000 * THREADS; + final int LOCAL_REPEATS = REPEATS / THREADS; + + // Detection will start from CacheLineMaxSize bytes. + final int MAX_SIZE = LWJGLUtil.getPrivilegedInteger("org.lwjglx.util.mapped.CacheLineMaxSize", 1024) / 4; // in + // # + // of + // integers + // Detection will stop when the execution time increases by more than CacheLineTimeThreshold %. + final double TIME_THRESHOLD = 1.0 + + LWJGLUtil.getPrivilegedInteger("org.lwjglx.util.mapped.CacheLineTimeThreshold", 50) / 100.0; + + final ExecutorService executorService = Executors.newFixedThreadPool(THREADS); + final ExecutorCompletionService completionService = new ExecutorCompletionService(executorService); + + try { + // We need to use a NIO buffer in order to guarantee memory alignment. + final IntBuffer memory = getMemory(MAX_SIZE); + + // -- WARMUP -- + + final int WARMUP = 10; + for (int i = 0; i < WARMUP; i++) doTest(THREADS, LOCAL_REPEATS, 0, memory, completionService); + + // -- CACHE LINE SIZE DETECTION -- + + long totalTime = 0; + int count = 0; + int cacheLineSize = 64; // fallback to the most common size these days + boolean found = false; + for (int i = MAX_SIZE; i >= 1; i >>= 1) { + final long time = doTest(THREADS, LOCAL_REPEATS, i, memory, completionService); + if (totalTime > 0) { // Ignore first run + final long avgTime = totalTime / count; + if ((double) time / (double) avgTime > TIME_THRESHOLD) { // Try to detect a noticeable jump in + // execution time + cacheLineSize = (i << 1) * 4; + found = true; + break; + } + } + totalTime += time; + count++; + } + + if (LWJGLUtil.DEBUG) { + if (found) LWJGLUtil.log("Cache line size detected: " + cacheLineSize + " bytes"); + else LWJGLUtil.log("Failed to detect cache line size, assuming " + cacheLineSize + " bytes"); + } + + return cacheLineSize; + } finally { + executorService.shutdown(); + } + } + + public static void main(String[] args) { + CacheUtil.getCacheLineSize(); + } + + static long memoryLoop(final int index, final int repeats, final IntBuffer memory, final int padding) { + final long address = MemoryUtil.getAddress(memory) + (index * padding * 4); + + final long time = System.nanoTime(); + for (int i = 0; i < repeats; i++) { + // Use volatile access to avoid server VM optimizations. + ivput(ivget(address) + 1, address); + } + + return System.nanoTime() - time; + } + + private static IntBuffer getMemory(final int START_SIZE) { + final int PAGE_SIZE = MappedObjectUnsafe.INSTANCE.pageSize(); + + final ByteBuffer buffer = ByteBuffer.allocateDirect((START_SIZE * 4) + PAGE_SIZE) + .order(ByteOrder.nativeOrder()); + + // Align to page and, consequently, to cache line. Otherwise results will be inconsistent. + if (MemoryUtil.getAddress(buffer) % PAGE_SIZE != 0) { + // Round up to page boundary + buffer.position(PAGE_SIZE - (int) (MemoryUtil.getAddress(buffer) & (PAGE_SIZE - 1))); + } + + return buffer.asIntBuffer(); + } + + private static long doTest(final int threads, final int repeats, final int padding, final IntBuffer memory, + final ExecutorCompletionService completionService) { + for (int i = 0; i < threads; i++) submitTest(completionService, i, repeats, memory, padding); + return waitForResults(threads, completionService); + } + + private static void submitTest(final ExecutorCompletionService completionService, final int index, + final int repeats, final IntBuffer memory, final int padding) { + completionService.submit(new Callable() { + + public Long call() throws Exception { + return memoryLoop(index, repeats, memory, padding); + } + }); + } + + private static long waitForResults(final int count, final ExecutorCompletionService completionService) { + try { + long totalTime = 0; + for (int i = 0; i < count; i++) totalTime += completionService.take() + .get(); + return totalTime; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} diff --git a/src/main/java/org/lwjglx/util/mapped/CacheUtil.java b/src/main/java/org/lwjglx/util/mapped/CacheUtil.java new file mode 100644 index 0000000..46d023f --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/CacheUtil.java @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * 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 'LWJGL' 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 org.lwjglx.util.mapped; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.CharBuffer; +import java.nio.DoubleBuffer; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; +import java.nio.LongBuffer; +import java.nio.ShortBuffer; + +import org.lwjglx.LWJGLUtil; +import org.lwjglx.MemoryUtil; +import org.lwjglx.PointerBuffer; + +/** + * This class provides utility methods for allocating cache-line-aligned + * NIO buffers. The CPU cache line size is detected using a micro-benchmark + * that exploits the performation degredation that occurs when different + * threads write to different locations of the same cache line. The detection + * should be reasonably robust on both the server and client VM, but there + * are a few system properties that can be used to tune it. + * + * @author Spasi + */ +public final class CacheUtil { + + private static final int CACHE_LINE_SIZE; + + static { + final Integer size = LWJGLUtil.getPrivilegedInteger("org.lwjglx.util.mapped.CacheLineSize"); // forces a + // specific cache + // line size + + if (size != null) { + if (size < 1) throw new IllegalStateException("Invalid CacheLineSize specified: " + size); + CACHE_LINE_SIZE = size; + } else if (Runtime.getRuntime() + .availableProcessors() == 1) { // We cannot use false sharing to detect it + /* + * Spasi: + * I have implemented a single-threaded benchmark for this, but it requires + * lots of memory allocations and could not tune it for both the client and + * server VM. It's not a big deal anyway, 64 bytes should be ok for any + * single-core CPU. + */ + if (LWJGLUtil.DEBUG) + LWJGLUtil.log("Cannot detect cache line size on single-core CPUs, assuming 64 bytes."); + CACHE_LINE_SIZE = 64; + } else CACHE_LINE_SIZE = CacheLineSize.getCacheLineSize(); + } + + private CacheUtil() {} + + /** + * Returns the CPU cache line size, in number of bytes. + * + * @return the cache line size + */ + public static int getCacheLineSize() { + return CACHE_LINE_SIZE; + } + + /** + * Construct a direct, native-ordered and cache-line-aligned bytebuffer with the specified size. + * + * @param size The size, in bytes + * + * @return a ByteBuffer + */ + public static ByteBuffer createByteBuffer(int size) { + ByteBuffer buffer = ByteBuffer.allocateDirect(size + CACHE_LINE_SIZE); + + // Align to cache line. + if (MemoryUtil.getAddress(buffer) % CACHE_LINE_SIZE != 0) { + // Round up to cache line boundary + buffer.position(CACHE_LINE_SIZE - (int) (MemoryUtil.getAddress(buffer) & (CACHE_LINE_SIZE - 1))); + } + + buffer.limit(buffer.position() + size); + return buffer.slice() + .order(ByteOrder.nativeOrder()); + } + + /** + * Construct a direct, native-ordered and cache-line-aligned shortbuffer with the specified number + * of elements. + * + * @param size The size, in shorts + * + * @return a ShortBuffer + */ + public static ShortBuffer createShortBuffer(int size) { + return createByteBuffer(size << 1).asShortBuffer(); + } + + /** + * Construct a direct, native-ordered and cache-line-aligned charbuffer with the specified number + * of elements. + * + * @param size The size, in chars + * + * @return an CharBuffer + */ + public static CharBuffer createCharBuffer(int size) { + return createByteBuffer(size << 1).asCharBuffer(); + } + + /** + * Construct a direct, native-ordered and cache-line-aligned intbuffer with the specified number + * of elements. + * + * @param size The size, in ints + * + * @return an IntBuffer + */ + public static IntBuffer createIntBuffer(int size) { + return createByteBuffer(size << 2).asIntBuffer(); + } + + /** + * Construct a direct, native-ordered and cache-line-aligned longbuffer with the specified number + * of elements. + * + * @param size The size, in longs + * + * @return an LongBuffer + */ + public static LongBuffer createLongBuffer(int size) { + return createByteBuffer(size << 3).asLongBuffer(); + } + + /** + * Construct a direct, native-ordered and cache-line-aligned floatbuffer with the specified number + * of elements. + * + * @param size The size, in floats + * + * @return a FloatBuffer + */ + public static FloatBuffer createFloatBuffer(int size) { + return createByteBuffer(size << 2).asFloatBuffer(); + } + + /** + * Construct a direct, native-ordered and cache-line-aligned doublebuffer with the specified number + * of elements. + * + * @param size The size, in floats + * + * @return a FloatBuffer + */ + public static DoubleBuffer createDoubleBuffer(int size) { + return createByteBuffer(size << 3).asDoubleBuffer(); + } + + /** + * Construct a cache-line-aligned PointerBuffer with the specified number + * of elements. + * + * @param size The size, in memory addresses + * + * @return a PointerBuffer + */ + public static PointerBuffer createPointerBuffer(int size) { + return new PointerBuffer(createByteBuffer(size * PointerBuffer.getPointerSize())); + } + +} diff --git a/src/main/java/org/lwjglx/util/mapped/MappedField.java b/src/main/java/org/lwjglx/util/mapped/MappedField.java new file mode 100644 index 0000000..6792102 --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/MappedField.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * 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 'LWJGL' 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 org.lwjglx.util.mapped; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * This annotation can be used on fields of {@link MappedObject} subclasses, + * to manually specify byte offsets and lengths. This is useful when the + * mapped fields require custom alignment. {@link java.nio.ByteBuffer} + * fields are required to have this annotation with a hardcoded byte length. + * + * @author Riven + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface MappedField { + + /** + * Specifies the field byte offset within the mapped object. + * + * @return the field byte offset + */ + long byteOffset() default -1; + + /** + * Specifies the field byte length. Required for {@link java.nio.ByteBuffer} fields. + * + * @return the field byte length + */ + long byteLength() default -1; + +} diff --git a/src/main/java/org/lwjglx/util/mapped/MappedForeach.java b/src/main/java/org/lwjglx/util/mapped/MappedForeach.java new file mode 100644 index 0000000..ce24455 --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/MappedForeach.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * 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 'LWJGL' 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 org.lwjglx.util.mapped; + +import java.util.Iterator; + +/** + * Iterable implementation for {@link MappedObject}. + * + * @author Riven + */ +final class MappedForeach implements Iterable { + + final T mapped; + final int elementCount; + + MappedForeach(T mapped, int elementCount) { + this.mapped = mapped; + this.elementCount = elementCount; + } + + public Iterator iterator() { + return new Iterator() { + + private int index; + + public boolean hasNext() { + return this.index < (MappedForeach.this.elementCount); + } + + public T next() { + mapped.setViewAddress(mapped.getViewAddress(this.index++)); + return mapped; + } + + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } + +} diff --git a/src/main/java/org/lwjglx/util/mapped/MappedHelper.java b/src/main/java/org/lwjglx/util/mapped/MappedHelper.java new file mode 100644 index 0000000..a9743c0 --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/MappedHelper.java @@ -0,0 +1,385 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * 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 'LWJGL' 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 org.lwjglx.util.mapped; + +import static org.lwjglx.util.mapped.MappedObjectUnsafe.*; + +import java.nio.ByteBuffer; + +import org.lwjglx.LWJGLUtil; +import org.lwjglx.MemoryUtil; + +/** + * [INTERNAL USE ONLY] + *

+ * Helper class used by the bytecode transformer. + * + * @author Riven + */ +public class MappedHelper { + + public static void setup(MappedObject mo, ByteBuffer buffer, int align, int sizeof) { + if (LWJGLUtil.CHECKS && mo.baseAddress != 0L) + throw new IllegalStateException("this method should not be called by user-code"); + + if (LWJGLUtil.CHECKS && !buffer.isDirect()) throw new IllegalArgumentException("bytebuffer must be direct"); + mo.preventGC = buffer; + + if (LWJGLUtil.CHECKS && align <= 0) throw new IllegalArgumentException("invalid alignment"); + + if (LWJGLUtil.CHECKS && (sizeof <= 0 || sizeof % align != 0)) + throw new IllegalStateException("sizeof not a multiple of alignment"); + + long addr = MemoryUtil.getAddress(buffer); + if (LWJGLUtil.CHECKS && addr % align != 0) + throw new IllegalStateException("buffer address not aligned on " + align + " bytes"); + + mo.baseAddress = mo.viewAddress = addr; + } + + public static void checkAddress(long viewAddress, MappedObject mapped) { + mapped.checkAddress(viewAddress); + } + + public static void put_views(MappedSet2 set, int view) { + set.view(view); + } + + public static void put_views(MappedSet3 set, int view) { + set.view(view); + } + + public static void put_views(MappedSet4 set, int view) { + set.view(view); + } + + public static void put_view(MappedObject mapped, int view, int sizeof) { + mapped.setViewAddress(mapped.baseAddress + view * sizeof); + } + + public static int get_view(MappedObject mapped, int sizeof) { + return (int) (mapped.viewAddress - mapped.baseAddress) / sizeof; + } + + public static void put_view_shift(MappedObject mapped, int view, int sizeof_shift) { + mapped.setViewAddress(mapped.baseAddress + (view << sizeof_shift)); + } + + public static int get_view_shift(MappedObject mapped, int sizeof_shift) { + return ((int) (mapped.viewAddress - mapped.baseAddress)) >> sizeof_shift; + } + + public static void put_view_next(MappedObject mapped, int sizeof) { + mapped.setViewAddress(mapped.viewAddress + sizeof); + } + + public static MappedObject dup(MappedObject src, MappedObject dst) { + dst.baseAddress = src.baseAddress; + dst.viewAddress = src.viewAddress; + dst.preventGC = src.preventGC; + return dst; + } + + public static MappedObject slice(MappedObject src, MappedObject dst) { + dst.baseAddress = src.viewAddress; // ! + dst.viewAddress = src.viewAddress; + dst.preventGC = src.preventGC; + return dst; + } + + public static void copy(MappedObject src, MappedObject dst, int bytes) { + if (MappedObject.CHECKS) { + src.checkRange(bytes); + dst.checkRange(bytes); + } + + INSTANCE.copyMemory(src.viewAddress, dst.viewAddress, bytes); + } + + public static ByteBuffer newBuffer(long address, int capacity) { + return MappedObjectUnsafe.newBuffer(address, capacity); + } + + // ---- primitive fields read/write + + // byte + + public static void bput(byte value, long addr) { + INSTANCE.putByte(addr, value); + } + + public static void bput(MappedObject mapped, byte value, int fieldOffset) { + INSTANCE.putByte(mapped.viewAddress + fieldOffset, value); + } + + public static byte bget(long addr) { + return INSTANCE.getByte(addr); + } + + public static byte bget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getByte(mapped.viewAddress + fieldOffset); + } + + public static void bvput(byte value, long addr) { + INSTANCE.putByteVolatile(null, addr, value); + } + + public static void bvput(MappedObject mapped, byte value, int fieldOffset) { + INSTANCE.putByteVolatile(null, mapped.viewAddress + fieldOffset, value); + } + + public static byte bvget(long addr) { + return INSTANCE.getByteVolatile(null, addr); + } + + public static byte bvget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getByteVolatile(null, mapped.viewAddress + fieldOffset); + } + + // short + + public static void sput(short value, long addr) { + INSTANCE.putShort(addr, value); + } + + public static void sput(MappedObject mapped, short value, int fieldOffset) { + INSTANCE.putShort(mapped.viewAddress + fieldOffset, value); + } + + public static short sget(long addr) { + return INSTANCE.getShort(addr); + } + + public static short sget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getShort(mapped.viewAddress + fieldOffset); + } + + public static void svput(short value, long addr) { + INSTANCE.putShortVolatile(null, addr, value); + } + + public static void svput(MappedObject mapped, short value, int fieldOffset) { + INSTANCE.putShortVolatile(null, mapped.viewAddress + fieldOffset, value); + } + + public static short svget(long addr) { + return INSTANCE.getShortVolatile(null, addr); + } + + public static short svget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getShortVolatile(null, mapped.viewAddress + fieldOffset); + } + + // char + + public static void cput(char value, long addr) { + INSTANCE.putChar(addr, value); + } + + public static void cput(MappedObject mapped, char value, int fieldOffset) { + INSTANCE.putChar(mapped.viewAddress + fieldOffset, value); + } + + public static char cget(long addr) { + return INSTANCE.getChar(addr); + } + + public static char cget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getChar(mapped.viewAddress + fieldOffset); + } + + public static void cvput(char value, long addr) { + INSTANCE.putCharVolatile(null, addr, value); + } + + public static void cvput(MappedObject mapped, char value, int fieldOffset) { + INSTANCE.putCharVolatile(null, mapped.viewAddress + fieldOffset, value); + } + + public static char cvget(long addr) { + return INSTANCE.getCharVolatile(null, addr); + } + + public static char cvget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getCharVolatile(null, mapped.viewAddress + fieldOffset); + } + + // int + + public static void iput(int value, long addr) { + INSTANCE.putInt(addr, value); + } + + public static void iput(MappedObject mapped, int value, int fieldOffset) { + INSTANCE.putInt(mapped.viewAddress + fieldOffset, value); + } + + public static int iget(long address) { + return INSTANCE.getInt(address); + } + + public static int iget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getInt(mapped.viewAddress + fieldOffset); + } + + public static void ivput(int value, long addr) { + INSTANCE.putIntVolatile(null, addr, value); + } + + public static void ivput(MappedObject mapped, int value, int fieldOffset) { + INSTANCE.putIntVolatile(null, mapped.viewAddress + fieldOffset, value); + } + + public static int ivget(long address) { + return INSTANCE.getIntVolatile(null, address); + } + + public static int ivget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getIntVolatile(null, mapped.viewAddress + fieldOffset); + } + + // float + + public static void fput(float value, long addr) { + INSTANCE.putFloat(addr, value); + } + + public static void fput(MappedObject mapped, float value, int fieldOffset) { + INSTANCE.putFloat(mapped.viewAddress + fieldOffset, value); + } + + public static float fget(long addr) { + return INSTANCE.getFloat(addr); + } + + public static float fget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getFloat(mapped.viewAddress + fieldOffset); + } + + public static void fvput(float value, long addr) { + INSTANCE.putFloatVolatile(null, addr, value); + } + + public static void fvput(MappedObject mapped, float value, int fieldOffset) { + INSTANCE.putFloatVolatile(null, mapped.viewAddress + fieldOffset, value); + } + + public static float fvget(long addr) { + return INSTANCE.getFloatVolatile(null, addr); + } + + public static float fvget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getFloatVolatile(null, mapped.viewAddress + fieldOffset); + } + + // long + + public static void jput(long value, long addr) { + INSTANCE.putLong(addr, value); + } + + public static void jput(MappedObject mapped, long value, int fieldOffset) { + INSTANCE.putLong(mapped.viewAddress + fieldOffset, value); + } + + public static long jget(long addr) { + return INSTANCE.getLong(addr); + } + + public static long jget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getLong(mapped.viewAddress + fieldOffset); + } + + public static void jvput(long value, long addr) { + INSTANCE.putLongVolatile(null, addr, value); + } + + public static void jvput(MappedObject mapped, long value, int fieldOffset) { + INSTANCE.putLongVolatile(null, mapped.viewAddress + fieldOffset, value); + } + + public static long jvget(long addr) { + return INSTANCE.getLongVolatile(null, addr); + } + + public static long jvget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getLongVolatile(null, mapped.viewAddress + fieldOffset); + } + + // address + + public static void aput(long value, long addr) { + INSTANCE.putAddress(addr, value); + } + + public static void aput(MappedObject mapped, long value, int fieldOffset) { + INSTANCE.putAddress(mapped.viewAddress + fieldOffset, value); + } + + public static long aget(long addr) { + return INSTANCE.getAddress(addr); + } + + public static long aget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getAddress(mapped.viewAddress + fieldOffset); + } + + // double + + public static void dput(double value, long addr) { + INSTANCE.putDouble(addr, value); + } + + public static void dput(MappedObject mapped, double value, int fieldOffset) { + INSTANCE.putDouble(mapped.viewAddress + fieldOffset, value); + } + + public static double dget(long addr) { + return INSTANCE.getDouble(addr); + } + + public static double dget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getDouble(mapped.viewAddress + fieldOffset); + } + + public static void dvput(double value, long addr) { + INSTANCE.putDoubleVolatile(null, addr, value); + } + + public static void dvput(MappedObject mapped, double value, int fieldOffset) { + INSTANCE.putDoubleVolatile(null, mapped.viewAddress + fieldOffset, value); + } + + public static double dvget(long addr) { + return INSTANCE.getDoubleVolatile(null, addr); + } + + public static double dvget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getDoubleVolatile(null, mapped.viewAddress + fieldOffset); + } + +} diff --git a/src/main/java/org/lwjglx/util/mapped/MappedObject.java b/src/main/java/org/lwjglx/util/mapped/MappedObject.java new file mode 100644 index 0000000..c3b9512 --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/MappedObject.java @@ -0,0 +1,286 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * 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 'LWJGL' 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 org.lwjglx.util.mapped; + +import java.nio.BufferOverflowException; +import java.nio.ByteBuffer; + +import org.lwjglx.LWJGLUtil; +import org.lwjglx.MemoryUtil; + +/** + * Base superclass of all mapped objects. Classes that require + * data mapping should extend this class and registered with + * {@link MappedObjectTransformer#register(Class)}. + *

+ * Subclasses may only specify the default constructor. Any code + * inside that constructor is optional, but will not run when the + * view is instantiated, see {@link #runViewConstructor()}. + *

+ * Bounds checking may be enabled through a JVM system property: org.lwjglx.util.mapped.Checks=true + * + * @author Riven + */ +public abstract class MappedObject { + + static final boolean CHECKS = LWJGLUtil.getPrivilegedBoolean("org.lwjglx.util.mapped.Checks"); + + protected MappedObject() { + // + } + + /** The mapped object base memory address, in bytes. Read-only. */ + public long baseAddress; + + /** The mapped object view memory address, in bytes. Read-only. */ + public long viewAddress; + + /** The mapped buffer. */ + ByteBuffer preventGC; + + /** + * Holds the value of sizeof of the sub-type of this MappedObject
+ *
+ * The behavior of this (transformed) method does not follow the normal Java behavior.
+ * Vec2.SIZEOF will yield 8 (2 floats)
+ * Vec3.SIZEOF will yield 12 (3 floats)
+ * This (required) notation might cause compiler warnings, which can be suppressed + * with @SuppressWarnings("static-access").
+ * Using Java 5.0's static-import on this method will break functionality. + */ + public static int SIZEOF = -1; // any method that calls these field will have its call-site modified ('final' per + // subtype) + + /** + * The mapped object view offset, in elements. Read/write. + * This is a virtual field, used as a convenient getter/setter for {@see viewAddress}. + */ + public int view; + + protected final long getViewAddress(final int view) { + // No call-site modification for this, we override in every subclass instead, + // so that we can use it in MappedForeach. + throw new InternalError("type not registered"); + } + + public final void setViewAddress(final long address) { + if (CHECKS) checkAddress(address); + this.viewAddress = address; + } + + final void checkAddress(final long address) { + final long base = MemoryUtil.getAddress0(preventGC); + final int offset = (int) (address - base); + if (address < base || preventGC.capacity() < (offset + getSizeof())) + throw new IndexOutOfBoundsException(Integer.toString(offset / getSizeof())); + } + + final void checkRange(final int bytes) { + if (bytes < 0) throw new IllegalArgumentException(); + + if (preventGC.capacity() < (viewAddress - MemoryUtil.getAddress0(preventGC) + bytes)) + throw new BufferOverflowException(); + } + + /** The mapped object memory alignment, in bytes. Read-only. */ + /** + * Returns the mapped object memory alignment, in bytes. + * + * @return the memory alignment + */ + public final int getAlign() { + // No call-site modification for this, we override in every subclass instead. + throw new InternalError("type not registered"); + } + + /** + * Returns the mapped object memory sizeof, in bytes. + * + * @return the sizeof value + */ + public final int getSizeof() { + // No call-site modification for this, we override in every subclass instead. + throw new InternalError("type not registered"); + } + + /** + * Returns the number of mapped objects that fit in the mapped buffer. + * + * @return the mapped object capacity + */ + public final int capacity() { + // No call-site modification for this, we override in every subclass instead. + throw new InternalError("type not registered"); + } + + /** + * Creates a MappedObject instance, mapping the memory region of the specified direct ByteBuffer. + *

+ * The behavior of this (transformed) method does not follow the normal Java behavior.
+ * Vec2.map(buffer) will return a mapped Vec2 instance.
+ * Vec3.map(buffer) will return a mapped Vec3 instance.
+ * This (required) notation might cause compiler warnings, which can be suppressed + * with @SuppressWarnings("static-access").
+ * Using Java 5.0's static-import on this method will break functionality. + */ + @SuppressWarnings("unused") + public static T map(ByteBuffer bb) { + // any method that calls this method will have its call-site modified + throw new InternalError("type not registered"); + } + + /** + * Creates a MappedObject instance, mapping the memory region specified. This is useful for mapping + * arbitrary regions in memory, e.g. OpenCL CLMem objects, without creating a ByteBuffer first. + *

+ * The behavior of this (transformed) method does not follow the normal Java behavior.
+ * Vec2.map(buffer) will return a mapped Vec2 instance.
+ * Vec3.map(buffer) will return a mapped Vec3 instance.
+ * This (required) notation might cause compiler warnings, which can be suppressed + * with @SuppressWarnings("static-access").
+ * Using Java 5.0's static-import on this method will break functionality. + */ + @SuppressWarnings("unused") + public static T map(long address, int capacity) { + // any method that calls this method will have its call-site modified + throw new InternalError("type not registered"); + } + + /** + * Creates a MappedObject instance, mapping the memory region of an allocated direct ByteBuffer with a capacity of + * elementCount*SIZEOF + *

+ * The behavior of this (transformed) method does not follow the normal Java behavior.
+ * Vec2.malloc(int) will return a mapped Vec2 instance.
+ * Vec3.malloc(int) will return a mapped Vec3 instance.
+ * This (required) notation might cause compiler warnings, which can be suppressed + * with @SuppressWarnings("static-access").
+ * Using Java 5.0's static-import on this method will break functionality. + */ + @SuppressWarnings("unused") + public static T malloc(int elementCount) { + // any method that calls this method will have its call-site modified + throw new InternalError("type not registered"); + } + + /** + * Creates an identical new MappedObject instance, comparable to the + * contract of {@link ByteBuffer#duplicate}. This is useful when more than one + * views of the mapped object are required at the same time, e.g. in + * multithreaded access. + */ + public final T dup() { + // any method that calls this method will have its call-site modified + throw new InternalError("type not registered"); + } + + /** + * Creates a new MappedObject instance, with a base offset equal to + * the offset of the current view, comparable to the contract of {@link ByteBuffer#slice}. + */ + public final T slice() { + // any method that calls this method will have its call-site modified + throw new InternalError("type not registered"); + } + + /** + * Any code in the default constructor will not run automatically. This method + * can be used to execute that code on the current view. + */ + public final void runViewConstructor() { + // any method that calls this method will have its call-site modified + throw new InternalError("type not registered"); + } + + /** Moves the current view to the next element. */ + public final void next() { + // No call-site modification for this, we override in every subclass instead, + // so that we can use it in MappedSetX. + throw new InternalError("type not registered"); + } + + /** + * Copies and amount of SIZEOF - padding bytes, from the current + * mapped object, to the specified mapped object. + */ + @SuppressWarnings("unused") + public final void copyTo(T target) { + // any method that calls this method will have its call-site modified + throw new InternalError("type not registered"); + } + + /** + * Copies and amount of SIZEOF * instances bytes, from the + * current mapped object, to the specified mapped object. Note that + * this includes any padding bytes that are part of SIZEOF. + */ + @SuppressWarnings("unused") + public final void copyRange(T target, int instances) { + // any method that calls this method will have its call-site modified + throw new InternalError("type not registered"); + } + + /** + * Creates an {@link Iterable} that will step through + * capacity() views, leaving the view at + * the last valid value.
+ *

+ * For convenience you are encouraged to static-import this specific method: + * import static org.lwjglx.util.mapped.MappedObject.foreach; + */ + public static Iterable foreach(T mapped) { + return foreach(mapped, mapped.capacity()); + } + + /** + * Creates an {@link Iterable} that will step through + * elementCount views, leaving the view at + * the last valid value.
+ *

+ * For convenience you are encouraged to static-import this specific method: + * import static org.lwjglx.util.mapped.MappedObject.foreach; + */ + public static Iterable foreach(T mapped, int elementCount) { + return new MappedForeach(mapped, elementCount); + } + + @SuppressWarnings("unused") + public final T[] asArray() { + // any method that calls this method will have its call-site modified + throw new InternalError("type not registered"); + } + + /** + * Returns the {@link ByteBuffer} that backs this mapped object. + * + * @return the backing buffer + */ + public final ByteBuffer backingByteBuffer() { + return this.preventGC; + } + +} diff --git a/src/main/java/org/lwjglx/util/mapped/MappedObjectClassLoader.java b/src/main/java/org/lwjglx/util/mapped/MappedObjectClassLoader.java new file mode 100644 index 0000000..2435d3a --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/MappedObjectClassLoader.java @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * 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 'LWJGL' 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 org.lwjglx.util.mapped; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URLClassLoader; + +import org.lwjglx.LWJGLUtil; + +/** + * This classloader is responsible for applying the bytecode transformation to mapped objects. + * The transformation can either be applied using a Java agent, or with the convenient {@link #fork} method. + * + * @author Riven + */ +public class MappedObjectClassLoader extends URLClassLoader { + + static final String MAPPEDOBJECT_PACKAGE_PREFIX = MappedObjectClassLoader.class.getPackage() + .getName() + "."; + + static boolean FORKED; + + /** + * Forks the specified class containing a main method, passing the specified arguments. See + * org.lwjglx.test.mapped.TestMappedObject for example usage. + * + * @param mainClass the class containing the main method + * @param args the arguments to pass + * + * @return true if the fork was successful. + */ + public static boolean fork(Class mainClass, String[] args) { + if (FORKED) { + return false; + } + + FORKED = true; + + try { + MappedObjectClassLoader loader = new MappedObjectClassLoader(mainClass); + loader.loadMappedObject(); + + Class replacedMainClass = loader.loadClass(mainClass.getName()); + Method mainMethod = replacedMainClass.getMethod("main", String[].class); + mainMethod.invoke(null, new Object[] { args }); + } catch (InvocationTargetException exc) { + Thread.currentThread() + .getUncaughtExceptionHandler() + .uncaughtException(Thread.currentThread(), exc.getCause()); + } catch (Throwable cause) { + throw new Error("failed to fork", cause); + } + + return true; + } + + private MappedObjectClassLoader(Class mainClass) { + super(((URLClassLoader) mainClass.getClassLoader()).getURLs()); + } + + protected synchronized Class loadMappedObject() throws ClassNotFoundException { + final String name = MappedObject.class.getName(); + String className = name.replace('.', '/'); + + byte[] bytecode = readStream(this.getResourceAsStream(className.concat(".class"))); + + long t0 = System.nanoTime(); + bytecode = MappedObjectTransformer.transformMappedObject(bytecode); + long t1 = System.nanoTime(); + total_time_transforming += (t1 - t0); + + if (MappedObjectTransformer.PRINT_ACTIVITY) printActivity(className, t0, t1); + + Class clazz = super.defineClass(name, bytecode, 0, bytecode.length); + resolveClass(clazz); + return clazz; + } + + private static long total_time_transforming; + + @Override + protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if (name.startsWith("java.") || name.startsWith("javax.") + || name.startsWith("sun.") + || name.startsWith("sunw.") + || name.startsWith("org.objectweb.asm.")) return super.loadClass(name, resolve); + + final String className = name.replace('.', '/'); + final boolean inThisPackage = name.startsWith(MAPPEDOBJECT_PACKAGE_PREFIX); + + if (inThisPackage && (name.equals(MappedObjectClassLoader.class.getName()) + || name.equals((MappedObjectTransformer.class.getName())) + || name.equals((CacheUtil.class.getName())))) return super.loadClass(name, resolve); + + byte[] bytecode = readStream(this.getResourceAsStream(className.concat(".class"))); + + // Classes in this package do not get transformed, but need to go through here because we have transformed + // MappedObject. + if (!(inThisPackage && name.substring(MAPPEDOBJECT_PACKAGE_PREFIX.length()) + .indexOf('.') == -1)) { + long t0 = System.nanoTime(); + final byte[] newBytecode = MappedObjectTransformer.transformMappedAPI(className, bytecode); + long t1 = System.nanoTime(); + + total_time_transforming += (t1 - t0); + + if (bytecode != newBytecode) { + bytecode = newBytecode; + if (MappedObjectTransformer.PRINT_ACTIVITY) printActivity(className, t0, t1); + } + } + + Class clazz = super.defineClass(name, bytecode, 0, bytecode.length); + if (resolve) resolveClass(clazz); + return clazz; + } + + private static void printActivity(final String className, final long t0, final long t1) { + final StringBuilder msg = new StringBuilder(MappedObjectClassLoader.class.getSimpleName() + ": " + className); + + if (MappedObjectTransformer.PRINT_TIMING) msg.append( + "\n\ttransforming took " + (t1 - t0) / 1000 + + " micros (total: " + + (total_time_transforming / 1000 / 1000) + + "ms)"); + + LWJGLUtil.log(msg); + } + + private static byte[] readStream(InputStream in) { + byte[] bytecode = new byte[256]; + int len = 0; + try { + while (true) { + if (bytecode.length == len) bytecode = copyOf(bytecode, len * 2); + int got = in.read(bytecode, len, bytecode.length - len); + if (got == -1) break; + len += got; + } + } catch (IOException exc) { + // stop! + } finally { + try { + in.close(); + } catch (IOException exc) { + // ignore... + } + } + return copyOf(bytecode, len); + } + + private static byte[] copyOf(byte[] original, int newLength) { + byte[] copy = new byte[newLength]; + System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); + return copy; + } + +} diff --git a/src/main/java/org/lwjglx/util/mapped/MappedObjectTransformer.java b/src/main/java/org/lwjglx/util/mapped/MappedObjectTransformer.java new file mode 100644 index 0000000..f73d513 --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/MappedObjectTransformer.java @@ -0,0 +1,1530 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * 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 'LWJGL' 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 org.lwjglx.util.mapped; + +import static org.objectweb.asm.ClassWriter.COMPUTE_FRAMES; +import static org.objectweb.asm.Opcodes.*; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.nio.Buffer; +import java.nio.ByteBuffer; +import java.util.HashMap; +import java.util.Map; + +import org.lwjglx.BufferUtils; +import org.lwjglx.LWJGLUtil; +import org.lwjglx.MemoryUtil; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.FieldVisitor; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.FieldInsnNode; +import org.objectweb.asm.tree.FieldNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.IntInsnNode; +import org.objectweb.asm.tree.LdcInsnNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.tree.TypeInsnNode; +import org.objectweb.asm.tree.VarInsnNode; +import org.objectweb.asm.tree.analysis.Analyzer; +import org.objectweb.asm.tree.analysis.AnalyzerException; +import org.objectweb.asm.tree.analysis.BasicValue; +import org.objectweb.asm.tree.analysis.Frame; +import org.objectweb.asm.tree.analysis.SimpleVerifier; +import org.objectweb.asm.util.TraceClassVisitor; + +import com.gtnewhorizons.retrofuturabootstrap.api.RetroFuturaBootstrap; + +/** + * This class implements the bytecode transformation that mapped object go through. + * Mapped object classes need to first be registered with the transformer, see {@link #register(Class)}. + *

+ * The transformer supports some debugging tools, enabled through JVM system properties:
+ * org.lwjglx.util.mapped.PrintTiming=true, prints timing information for the transformation step.
+ * org.lwjglx.util.mapped.PrintActivity=true, prints activity information.
+ * org.lwjglx.util.mapped.PrintBytecode=true, prints the transformed bytecode.
+ * org.lwjglx.util.Debug must also be set to true for the above to work. + * + * @author Riven + */ +public class MappedObjectTransformer { + + static final boolean PRINT_ACTIVITY = LWJGLUtil.DEBUG + && LWJGLUtil.getPrivilegedBoolean("org.lwjglx.util.mapped.PrintActivity"); + static final boolean PRINT_TIMING = PRINT_ACTIVITY + && LWJGLUtil.getPrivilegedBoolean("org.lwjglx.util.mapped.PrintTiming"); + static final boolean PRINT_BYTECODE = LWJGLUtil.DEBUG + && LWJGLUtil.getPrivilegedBoolean("org.lwjglx.util.mapped.PrintBytecode"); + + static final Map className_to_subtype; + + static final String MAPPED_OBJECT_JVM = jvmClassName(MappedObject.class); + static final String MAPPED_HELPER_JVM = jvmClassName(MappedHelper.class); + + static final String MAPPEDSET_PREFIX = jvmClassName(MappedSet.class); + static final String MAPPED_SET2_JVM = jvmClassName(MappedSet2.class); + static final String MAPPED_SET3_JVM = jvmClassName(MappedSet3.class); + static final String MAPPED_SET4_JVM = jvmClassName(MappedSet4.class); + + static final String CACHE_LINE_PAD_JVM = "L" + jvmClassName(CacheLinePad.class) + ";"; + + // Public methods + static final String VIEWADDRESS_METHOD_NAME = "getViewAddress"; + static final String NEXT_METHOD_NAME = "next"; + static final String ALIGN_METHOD_NAME = "getAlign"; + static final String SIZEOF_METHOD_NAME = "getSizeof"; + static final String CAPACITY_METHOD_NAME = "capacity"; // Used for .asArray().length + + // Internal methods + static final String VIEW_CONSTRUCTOR_NAME = "constructView$LWJGL"; // Used by runViewConstructor + + static final Map OPCODE_TO_NAME = new HashMap(); + static final Map INSNTYPE_TO_NAME = new HashMap(); + + static boolean is_currently_computing_frames; + + static { + getClassEnums(Opcodes.class, OPCODE_TO_NAME, "V1_", "ACC_", "T_", "F_", "MH_"); + getClassEnums(AbstractInsnNode.class, INSNTYPE_TO_NAME); + + className_to_subtype = new HashMap(); + + { + // HACK: required for mapped.view++ + // + // because the compiler generates: + // => GETFIELD MappedObject.view + // => ICONST_1 + // => IADD + // => PUTFIELD MyMappedType.view + // + // instead of: + // => GETFIELD MyMappedType.view + // => ICONST_1 + // => IADD + // => PUTFIELD MyMappedType.view + // + className_to_subtype + .put(MAPPED_OBJECT_JVM, new MappedSubtypeInfo(MAPPED_OBJECT_JVM, null, -1, -1, -1, false)); + } + + final String vmName = System.getProperty("java.vm.name"); + if (vmName != null && !vmName.contains("Server")) { + System.err.println( + "Warning: " + MappedObject.class.getSimpleName() + + "s have inferiour performance on Client VMs, please consider switching to a Server VM."); + } + } + + /** + * Registers a class as a mapped object. + * The class must extend {@link MappedObject} and be annotated with {@link MappedField}. + * + * @param type the mapped object class. + */ + public static void register(Class type) { + if (MappedObjectClassLoader.FORKED) return; + + final MappedType mapped = type.getAnnotation(MappedType.class); + + if (mapped != null && mapped.padding() < 0) + throw new ClassFormatError("Invalid mapped type padding: " + mapped.padding()); + + if (type.getEnclosingClass() != null && !Modifier.isStatic(type.getModifiers())) + throw new InternalError("only top-level or static inner classes are allowed"); + + final String className = jvmClassName(type); + final Map fields = new HashMap(); + + long sizeof = 0; + for (Field field : type.getDeclaredFields()) { + FieldInfo fieldInfo = registerField( + mapped == null || mapped.autoGenerateOffsets(), + className, + sizeof, + field); + if (fieldInfo == null) continue; + + fields.put(field.getName(), fieldInfo); + + sizeof = Math.max(sizeof, fieldInfo.offset + fieldInfo.lengthPadded); + } + + int align = 4; + int padding = 0; + boolean cacheLinePadded = false; + + if (mapped != null) { + align = mapped.align(); + if (mapped.cacheLinePadding()) { + if (mapped.padding() != 0) throw new ClassFormatError( + "Mapped type padding cannot be specified together with cacheLinePadding."); + + final int cacheLineMod = (int) (sizeof % CacheUtil.getCacheLineSize()); + if (cacheLineMod != 0) padding = CacheUtil.getCacheLineSize() - cacheLineMod; + + cacheLinePadded = true; + } else padding = mapped.padding(); + } + + sizeof += padding; + + final MappedSubtypeInfo mappedType = new MappedSubtypeInfo( + className, + fields, + (int) sizeof, + align, + padding, + cacheLinePadded); + if (className_to_subtype.put(className, mappedType) != null) + throw new InternalError("duplicate mapped type: " + mappedType.className); + } + + private static FieldInfo registerField(final boolean autoGenerateOffsets, final String className, + long advancingOffset, final Field field) { + if (Modifier.isStatic(field.getModifiers())) // static fields are never mapped + return null; + + // we only support primitives and ByteBuffers + if (!field.getType() + .isPrimitive() && field.getType() != ByteBuffer.class) + throw new ClassFormatError( + "field '" + className + "." + field.getName() + "' not supported: " + field.getType()); + + MappedField meta = field.getAnnotation(MappedField.class); + if (meta == null && !autoGenerateOffsets) throw new ClassFormatError( + "field '" + className + + "." + + field.getName() + + "' missing annotation " + + MappedField.class.getName() + + ": " + + className); + + Pointer pointer = field.getAnnotation(Pointer.class); + if (pointer != null && field.getType() != long.class) throw new ClassFormatError( + "The @Pointer annotation can only be used on long fields. @Pointer field found: " + className + + "." + + field.getName() + + ": " + + field.getType()); + + if (Modifier.isVolatile(field.getModifiers()) && (pointer != null || field.getType() == ByteBuffer.class)) + throw new ClassFormatError( + "The volatile keyword is not supported for @Pointer or ByteBuffer fields. Volatile field found: " + + className + + "." + + field.getName() + + ": " + + field.getType()); + + // quick hack + long byteLength; + if (field.getType() == long.class || field.getType() == double.class) { + if (pointer == null) byteLength = 8; + else byteLength = MappedObjectUnsafe.INSTANCE.addressSize(); + } else if (field.getType() == double.class) byteLength = 8; + else if (field.getType() == int.class || field.getType() == float.class) byteLength = 4; + else if (field.getType() == char.class || field.getType() == short.class) byteLength = 2; + else if (field.getType() == byte.class) byteLength = 1; + else if (field.getType() == ByteBuffer.class) { + byteLength = meta.byteLength(); + if (byteLength < 0) throw new IllegalStateException( + "invalid byte length for mapped ByteBuffer field: " + className + + "." + + field.getName() + + " [length=" + + byteLength + + "]"); + } else throw new ClassFormatError( + field.getType() + .getName()); + + if (field.getType() != ByteBuffer.class && (advancingOffset % byteLength) != 0) + throw new IllegalStateException("misaligned mapped type: " + className + "." + field.getName()); + + CacheLinePad pad = field.getAnnotation(CacheLinePad.class); + + long byteOffset = advancingOffset; + if (meta != null && meta.byteOffset() != -1) { + if (meta.byteOffset() < 0) throw new ClassFormatError( + "Invalid field byte offset: " + className + + "." + + field.getName() + + " [byteOffset=" + + meta.byteOffset() + + "]"); + if (pad != null) throw new ClassFormatError( + "A field byte offset cannot be specified together with cache-line padding: " + className + + "." + + field.getName()); + + byteOffset = meta.byteOffset(); + } + + long byteLengthPadded = byteLength; + if (pad != null) { + // Pad before + if (pad.before() && byteOffset % CacheUtil.getCacheLineSize() != 0) + byteOffset += CacheUtil.getCacheLineSize() - (byteOffset & (CacheUtil.getCacheLineSize() - 1)); + + // Pad after + if (pad.after() && (byteOffset + byteLength) % CacheUtil.getCacheLineSize() != 0) + byteLengthPadded += CacheUtil.getCacheLineSize() + - (byteOffset + byteLength) % CacheUtil.getCacheLineSize(); + + assert !pad.before() || (byteOffset % CacheUtil.getCacheLineSize() == 0); + assert !pad.after() || ((byteOffset + byteLengthPadded) % CacheUtil.getCacheLineSize() == 0); + } + + if (PRINT_ACTIVITY) LWJGLUtil.log( + MappedObjectTransformer.class.getSimpleName() + ": " + + className + + "." + + field.getName() + + " [type=" + + field.getType() + .getSimpleName() + + ", offset=" + + byteOffset + + "]"); + + return new FieldInfo( + byteOffset, + byteLength, + byteLengthPadded, + Type.getType(field.getType()), + Modifier.isVolatile(field.getModifiers()), + pointer != null); + } + + /** Removes final from methods that will be overriden by subclasses. */ + static byte[] transformMappedObject(byte[] bytecode) { + final ClassWriter cw = new ClassWriter(0); + + ClassVisitor cv = new ClassVisitor(RetroFuturaBootstrap.API.newestAsmVersion(), cw) { + + private final String[] DEFINALIZE_LIST = { VIEWADDRESS_METHOD_NAME, NEXT_METHOD_NAME, ALIGN_METHOD_NAME, + SIZEOF_METHOD_NAME, CAPACITY_METHOD_NAME, }; + + public MethodVisitor visitMethod(int access, final String name, final String desc, final String signature, + final String[] exceptions) { + for (String method : DEFINALIZE_LIST) { + if (name.equals(method)) { + access &= ~ACC_FINAL; + break; + } + } + return super.visitMethod(access, name, desc, signature, exceptions); + } + }; + + new ClassReader(bytecode).accept(cv, 0); + return cw.toByteArray(); + } + + static byte[] transformMappedAPI(final String className, byte[] bytecode) { + final ClassWriter cw = new ClassWriter(COMPUTE_FRAMES) { + + @Override + protected String getCommonSuperClass(String a, String b) { + // HACK: prevent user-code static-initialization-blocks to be executed + if (is_currently_computing_frames && !a.startsWith("java/") || !b.startsWith("java/")) + return "java/lang/Object"; + + return super.getCommonSuperClass(a, b); + } + + }; + + final TransformationAdapter ta = new TransformationAdapter(cw, className); + + ClassVisitor cv = ta; + if (className_to_subtype.containsKey(className)) // Do a first pass to generate address getters + cv = getMethodGenAdapter(className, cv); + + new ClassReader(bytecode).accept(cv, ClassReader.SKIP_FRAMES); + + if (!ta.transformed) return bytecode; + + bytecode = cw.toByteArray(); + if (PRINT_BYTECODE) printBytecode(bytecode); + + return bytecode; + } + + private static ClassVisitor getMethodGenAdapter(final String className, final ClassVisitor cv) { + return new ClassVisitor(RetroFuturaBootstrap.API.newestAsmVersion(), cv) { + + @Override + public void visitEnd() { + final MappedSubtypeInfo mappedSubtype = className_to_subtype.get(className); + + generateViewAddressGetter(); + generateCapacity(); + generateAlignGetter(mappedSubtype); + generateSizeofGetter(); + generateNext(); + + for (String fieldName : mappedSubtype.fields.keySet()) { + final FieldInfo field = mappedSubtype.fields.get(fieldName); + + if (field.type.getDescriptor() + .length() > 1) { // ByteBuffer, getter only + generateByteBufferGetter(fieldName, field); + } else { + generateFieldGetter(fieldName, field); + generateFieldSetter(fieldName, field); + } + } + + super.visitEnd(); + } + + private void generateViewAddressGetter() { + MethodVisitor mv = super.visitMethod(ACC_PUBLIC, VIEWADDRESS_METHOD_NAME, "(I)J", null, null); + mv.visitCode(); + mv.visitVarInsn(ALOAD, 0); + mv.visitFieldInsn(GETFIELD, MAPPED_OBJECT_JVM, "baseAddress", "J"); + mv.visitVarInsn(ILOAD, 1); + mv.visitFieldInsn(GETSTATIC, className, "SIZEOF", "I"); + mv.visitInsn(IMUL); + mv.visitInsn(I2L); + mv.visitInsn(LADD); + if (MappedObject.CHECKS) { + mv.visitInsn(DUP2); + mv.visitVarInsn(ALOAD, 0); + mv.visitMethodInsn( + INVOKESTATIC, + MAPPED_HELPER_JVM, + "checkAddress", + "(JL" + MAPPED_OBJECT_JVM + ";)V"); + } + mv.visitInsn(LRETURN); + mv.visitMaxs(3, 2); + mv.visitEnd(); + } + + private void generateCapacity() { + // return (backingByteBuffer().capacity() + (int)(MemoryUtil.getAddress0(backingByteBuffer()) - + // baseAddress)) / SIZEOF; + MethodVisitor mv = super.visitMethod(ACC_PUBLIC, CAPACITY_METHOD_NAME, "()I", null, null); + mv.visitCode(); + mv.visitVarInsn(ALOAD, 0); + mv.visitMethodInsn( + INVOKEVIRTUAL, + MAPPED_OBJECT_JVM, + "backingByteBuffer", + "()L" + jvmClassName(ByteBuffer.class) + ";"); + mv.visitInsn(DUP); + mv.visitMethodInsn(INVOKEVIRTUAL, jvmClassName(ByteBuffer.class), "capacity", "()I"); + mv.visitInsn(SWAP); + mv.visitMethodInsn( + INVOKESTATIC, + jvmClassName(MemoryUtil.class), + "getAddress0", + "(L" + jvmClassName(Buffer.class) + ";)J"); + mv.visitVarInsn(ALOAD, 0); + mv.visitFieldInsn(GETFIELD, MAPPED_OBJECT_JVM, "baseAddress", "J"); + mv.visitInsn(LSUB); + mv.visitInsn(L2I); + mv.visitInsn(IADD); + mv.visitFieldInsn(GETSTATIC, className, "SIZEOF", "I"); + mv.visitInsn(IDIV); + mv.visitInsn(IRETURN); + mv.visitMaxs(3, 1); + mv.visitEnd(); + } + + private void generateAlignGetter(final MappedSubtypeInfo mappedSubtype) { + MethodVisitor mv = super.visitMethod(ACC_PUBLIC, ALIGN_METHOD_NAME, "()I", null, null); + mv.visitCode(); + visitIntNode(mv, mappedSubtype.sizeof); + mv.visitInsn(IRETURN); + mv.visitMaxs(1, 1); + mv.visitEnd(); + } + + private void generateSizeofGetter() { + MethodVisitor mv = super.visitMethod(ACC_PUBLIC, SIZEOF_METHOD_NAME, "()I", null, null); + mv.visitCode(); + mv.visitFieldInsn(GETSTATIC, className, "SIZEOF", "I"); + mv.visitInsn(IRETURN); + mv.visitMaxs(1, 1); + mv.visitEnd(); + } + + private void generateNext() { + MethodVisitor mv = super.visitMethod(ACC_PUBLIC, NEXT_METHOD_NAME, "()V", null, null); + mv.visitCode(); + mv.visitVarInsn(ALOAD, 0); + mv.visitInsn(DUP); + mv.visitFieldInsn(GETFIELD, MAPPED_OBJECT_JVM, "viewAddress", "J"); + mv.visitFieldInsn(GETSTATIC, className, "SIZEOF", "I"); + mv.visitInsn(I2L); + mv.visitInsn(LADD); + mv.visitMethodInsn(INVOKEVIRTUAL, className, "setViewAddress", "(J)V"); + mv.visitInsn(RETURN); + mv.visitMaxs(3, 1); + mv.visitEnd(); + } + + private void generateByteBufferGetter(final String fieldName, final FieldInfo field) { + MethodVisitor mv = super.visitMethod( + ACC_PUBLIC | ACC_STATIC, + getterName(fieldName), + "(L" + className + ";I)" + field.type.getDescriptor(), + null, + null); + mv.visitCode(); + mv.visitVarInsn(ALOAD, 0); + mv.visitVarInsn(ILOAD, 1); + mv.visitMethodInsn(INVOKEVIRTUAL, className, VIEWADDRESS_METHOD_NAME, "(I)J"); + visitIntNode(mv, (int) field.offset); + mv.visitInsn(I2L); + mv.visitInsn(LADD); + visitIntNode(mv, (int) field.length); + mv.visitMethodInsn( + INVOKESTATIC, + MAPPED_HELPER_JVM, + "newBuffer", + "(JI)L" + jvmClassName(ByteBuffer.class) + ";"); + mv.visitInsn(ARETURN); + mv.visitMaxs(3, 2); + mv.visitEnd(); + } + + private void generateFieldGetter(final String fieldName, final FieldInfo field) { + MethodVisitor mv = super.visitMethod( + ACC_PUBLIC | ACC_STATIC, + getterName(fieldName), + "(L" + className + ";I)" + field.type.getDescriptor(), + null, + null); + mv.visitCode(); + mv.visitVarInsn(ALOAD, 0); + mv.visitVarInsn(ILOAD, 1); + mv.visitMethodInsn(INVOKEVIRTUAL, className, VIEWADDRESS_METHOD_NAME, "(I)J"); + visitIntNode(mv, (int) field.offset); + mv.visitInsn(I2L); + mv.visitInsn(LADD); + mv.visitMethodInsn( + INVOKESTATIC, + MAPPED_HELPER_JVM, + field.getAccessType() + "get", + "(J)" + field.type.getDescriptor()); + mv.visitInsn(field.type.getOpcode(IRETURN)); + mv.visitMaxs(3, 2); + mv.visitEnd(); + } + + private void generateFieldSetter(final String fieldName, final FieldInfo field) { + MethodVisitor mv = super.visitMethod( + ACC_PUBLIC | ACC_STATIC, + setterName(fieldName), + "(L" + className + ";I" + field.type.getDescriptor() + ")V", + null, + null); + mv.visitCode(); + int load = 0; + switch (field.type.getSort()) { + case Type.BOOLEAN: + case Type.CHAR: + case Type.BYTE: + case Type.SHORT: + case Type.INT: + load = ILOAD; + break; + case Type.FLOAT: + load = FLOAD; + break; + case Type.LONG: + load = LLOAD; + break; + case Type.DOUBLE: + load = DLOAD; + break; + } + mv.visitVarInsn(load, 2); + mv.visitVarInsn(ALOAD, 0); + mv.visitVarInsn(ILOAD, 1); + mv.visitMethodInsn(INVOKEVIRTUAL, className, VIEWADDRESS_METHOD_NAME, "(I)J"); + visitIntNode(mv, (int) field.offset); + mv.visitInsn(I2L); + mv.visitInsn(LADD); + mv.visitMethodInsn( + INVOKESTATIC, + MAPPED_HELPER_JVM, + field.getAccessType() + "put", + "(" + field.type.getDescriptor() + "J)V"); + mv.visitInsn(RETURN); + mv.visitMaxs(4, 4); + mv.visitEnd(); + } + + }; + } + + private static class TransformationAdapter extends ClassVisitor { + + final String className; + + boolean transformed; + + TransformationAdapter(final ClassVisitor cv, final String className) { + super(RetroFuturaBootstrap.API.newestAsmVersion(), cv); + this.className = className; + } + + @Override + public FieldVisitor visitField(final int access, final String name, final String desc, final String signature, + final Object value) { + // remove redirected fields + final MappedSubtypeInfo mappedSubtype = className_to_subtype.get(className); + if (mappedSubtype != null && mappedSubtype.fields.containsKey(name)) { + if (PRINT_ACTIVITY) LWJGLUtil.log( + MappedObjectTransformer.class + .getSimpleName() + ": discarding field: " + className + "." + name + ":" + desc); + return null; + } + + if ((access & ACC_STATIC) == 0) { + return new FieldNode(access, name, desc, signature, value) { + + public void visitEnd() { + if (visibleAnnotations == null) { // early-out + accept(cv); + return; + } + + boolean before = false; + boolean after = false; + int byteLength = 0; + for (AnnotationNode pad : visibleAnnotations) { + if (CACHE_LINE_PAD_JVM.equals(pad.desc)) { + if ("J".equals(desc) || "D".equals(desc)) byteLength = 8; + else if ("I".equals(desc) || "F".equals(desc)) byteLength = 4; + else if ("S".equals(desc) || "C".equals(desc)) byteLength = 2; + else if ("B".equals(desc) || "Z".equals(desc)) byteLength = 1; + else throw new ClassFormatError( + "The @CacheLinePad annotation cannot be used on non-primitive fields: " + className + + "." + + name); + + transformed = true; + + after = true; + if (pad.values != null) { + for (int i = 0; i < pad.values.size(); i += 2) { + final boolean value = pad.values.get(i + 1) + .equals(Boolean.TRUE); + if ("before".equals(pad.values.get(i))) before = value; + else after = value; + } + } + break; + } + } + + /* + * We make the fields public to force the JVM to keep the fields in the object. + * Instead of using only longs or integers, we use the same type as the original + * field. That's because modern JVMs usually reorder fields by type: + * longs, then doubles, then integers, then booleans, etc. This way it's more + * likely that the padding will work as expected. + */ + + if (before) { + final int count = CacheUtil.getCacheLineSize() / byteLength - 1; + for (int i = count; i >= 1; i--) cv.visitField( + access | ACC_PUBLIC | ACC_SYNTHETIC, + name + "$PAD_" + i, + desc, + signature, + null); + } + + accept(cv); + + if (after) { + final int count = CacheUtil.getCacheLineSize() / byteLength - 1; + for (int i = 1; i <= count; i++) cv.visitField( + access | ACC_PUBLIC | ACC_SYNTHETIC, + name + "$PAD" + i, + desc, + signature, + null); + } + } + }; + } else return super.visitField(access, name, desc, signature, value); + } + + @Override + public MethodVisitor visitMethod(final int access, String name, final String desc, final String signature, + final String[] exceptions) { + // Move MappedSubtype constructors to another method + if ("".equals(name)) { + final MappedSubtypeInfo mappedSubtype = className_to_subtype.get(className); + if (mappedSubtype != null) { + if (!"()V".equals(desc)) + throw new ClassFormatError(className + " can only have a default constructor, found: " + desc); + + final MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); + mv.visitVarInsn(ALOAD, 0); + mv.visitMethodInsn(INVOKESPECIAL, MAPPED_OBJECT_JVM, "", "()V"); + mv.visitInsn(RETURN); + mv.visitMaxs(0, 0); + + // put the method body in another method + name = VIEW_CONSTRUCTOR_NAME; + } + } + + final MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); + return new MethodNode(access, name, desc, signature, exceptions) { + + /** + * When true, the method has touched a mapped object and needs to be transformed. We track this + * so we can skip the expensive frame analysis and tree API usage. + */ + boolean needsTransformation; + + @Override + public void visitMaxs(int a, int b) { + try { + is_currently_computing_frames = true; + super.visitMaxs(a, b); + } finally { + is_currently_computing_frames = false; + } + } + + @Override + public void visitFieldInsn(final int opcode, final String owner, final String name, final String desc) { + if (className_to_subtype.containsKey(owner) || owner.startsWith(MAPPEDSET_PREFIX)) + needsTransformation = true; + + super.visitFieldInsn(opcode, owner, name, desc); + } + + @Override + public void visitMethodInsn(final int opcode, final String owner, final String name, + final String desc) { + if (className_to_subtype.containsKey(owner)) needsTransformation = true; + + super.visitMethodInsn(opcode, owner, name, desc); + } + + @Override + public void visitEnd() { + if (needsTransformation) { // Early-out for methods that do not touch a mapped object. + // System.err.println("\nTRANSFORMING: " + className + "." + name + desc); + transformed = true; + try { + transformMethod(analyse()); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + // Pass the instruction stream to the adapter's MethodVisitor + accept(mv); + } + + private Frame[] analyse() throws AnalyzerException { + final Analyzer a = new Analyzer(new SimpleVerifier()); + a.analyze(className, this); + return a.getFrames(); + } + + private void transformMethod(final Frame[] frames) { + final InsnList instructions = this.instructions; + + final Map arrayVars = new HashMap(); + + /* + * We need this map because we insert/remove instructions from the stream and we need a way + * to match each original instruction with the corresponding frame. + * TODO: Can we keep track of everything more efficiently without a map? + */ + final Map> frameMap = new HashMap>(); + for (int i = 0; i < frames.length; i++) frameMap.put(instructions.get(i), frames[i]); + + for (int i = 0; i < instructions.size(); i++) { // f is a separate cursor for frames + final AbstractInsnNode instruction = instructions.get(i); + + // System.out.println("MAIN LOOP #" + i + " - " + getOpcodeName(instruction)); + + switch (instruction.getType()) { + case AbstractInsnNode.VAR_INSN: + if (instruction.getOpcode() == ALOAD) { + VarInsnNode varInsn = (VarInsnNode) instruction; + final MappedSubtypeInfo mappedSubtype = arrayVars.get(varInsn.var); + if (mappedSubtype != null) i = transformArrayAccess( + instructions, + i, + frameMap, + varInsn, + mappedSubtype, + varInsn.var); + } + break; + case AbstractInsnNode.FIELD_INSN: + FieldInsnNode fieldInsn = (FieldInsnNode) instruction; + + final InsnList list = transformFieldAccess(fieldInsn); + if (list != null) i = replace(instructions, i, instruction, list); + + break; + case AbstractInsnNode.METHOD_INSN: + MethodInsnNode methodInsn = (MethodInsnNode) instruction; + final MappedSubtypeInfo mappedType = className_to_subtype.get(methodInsn.owner); + if (mappedType != null) i = transformMethodCall( + instructions, + i, + frameMap, + methodInsn, + mappedType, + arrayVars); + break; + } + } + } + }; + } + } + + static int transformMethodCall(final InsnList instructions, int i, + final Map> frameMap, final MethodInsnNode methodInsn, + final MappedSubtypeInfo mappedType, final Map arrayVars) { + switch (methodInsn.getOpcode()) { + case INVOKEVIRTUAL: + if ("asArray".equals(methodInsn.name) && methodInsn.desc.equals("()[L" + MAPPED_OBJECT_JVM + ";")) { + // Go forward and store the local variable index. + // We only allow this pattern: INVOKEVIRTUAL -> CHECKCAST -> ASTORE. + // We remove the first two and store the target MappedSubtype in the ASTORE variable + AbstractInsnNode nextInstruction; + checkInsnAfterIsArray(nextInstruction = methodInsn.getNext(), CHECKCAST); + checkInsnAfterIsArray(nextInstruction = nextInstruction.getNext(), ASTORE); + + final Frame frame = frameMap.get(nextInstruction); + final String targetType = frame.getStack(frame.getStackSize() - 1) + .getType() + .getElementType() + .getInternalName(); + if (!methodInsn.owner.equals(targetType)) { + /* + * This may happen with the current API, like so: + * MappedA foo = MappedA.malloc(...); + * MappedB[] cursor = foo.asArray(); + * We have to parameterize MappedObject to avoid this. + */ + throw new ClassCastException("Source: " + methodInsn.owner + " - Target: " + targetType); + } + + final VarInsnNode varInstruction = (VarInsnNode) nextInstruction; + + arrayVars.put(varInstruction.var, mappedType); + + instructions.remove(methodInsn.getNext()); // Remove CHECKCAST + instructions.remove(methodInsn); // Remove INVOKEVIRTUAL + } + + if ("dup".equals(methodInsn.name) && methodInsn.desc.equals("()L" + MAPPED_OBJECT_JVM + ";")) { + i = replace(instructions, i, methodInsn, generateDupInstructions(methodInsn)); + break; + } + + if ("slice".equals(methodInsn.name) && methodInsn.desc.equals("()L" + MAPPED_OBJECT_JVM + ";")) { + i = replace(instructions, i, methodInsn, generateSliceInstructions(methodInsn)); + break; + } + + if ("runViewConstructor".equals(methodInsn.name) && "()V".equals(methodInsn.desc)) { + i = replace(instructions, i, methodInsn, generateRunViewConstructorInstructions(methodInsn)); + break; + } + + if ("copyTo".equals(methodInsn.name) && methodInsn.desc.equals("(L" + MAPPED_OBJECT_JVM + ";)V")) { + i = replace(instructions, i, methodInsn, generateCopyToInstructions(mappedType)); + break; + } + + if ("copyRange".equals(methodInsn.name) && methodInsn.desc.equals("(L" + MAPPED_OBJECT_JVM + ";I)V")) { + i = replace(instructions, i, methodInsn, generateCopyRangeInstructions(mappedType)); + break; + } + + break; + case INVOKESPECIAL: + // super() in VIEW_CONSTRUCTOR_NAME, remove + if (methodInsn.owner.equals(MAPPED_OBJECT_JVM) && "".equals(methodInsn.name) + && "()V".equals(methodInsn.desc)) { + instructions.remove(methodInsn.getPrevious()); // ALOAD + instructions.remove(methodInsn); // INVOKESPECIAL + + i -= 2; + } + break; + case INVOKESTATIC: + boolean isMapDirectMethod = "map".equals(methodInsn.name) + && methodInsn.desc.equals("(JI)L" + MAPPED_OBJECT_JVM + ";"); + boolean isMapBufferMethod = "map".equals(methodInsn.name) + && methodInsn.desc.equals("(Ljava/nio/ByteBuffer;)L" + MAPPED_OBJECT_JVM + ";"); + boolean isMallocMethod = "malloc".equals(methodInsn.name) + && methodInsn.desc.equals("(I)L" + MAPPED_OBJECT_JVM + ";"); + + if ((isMapDirectMethod || isMapBufferMethod) || isMallocMethod) i = replace( + instructions, + i, + methodInsn, + generateMapInstructions(mappedType, methodInsn.owner, isMapDirectMethod, isMallocMethod)); + break; + } + + return i; + } + + private static InsnList generateCopyRangeInstructions(final MappedSubtypeInfo mappedType) { + final InsnList list = new InsnList(); + + // stack: instances, target, this + list.add(getIntNode(mappedType.sizeof)); + // stack: sizeof, instances, target, this + list.add(new InsnNode(IMUL)); + // stack: bytes, target, this + list.add( + new MethodInsnNode( + INVOKESTATIC, + MAPPED_HELPER_JVM, + "copy", + "(L" + MAPPED_OBJECT_JVM + ";L" + MAPPED_OBJECT_JVM + ";I)V")); + // stack: - + + return list; + } + + private static InsnList generateCopyToInstructions(final MappedSubtypeInfo mappedType) { + final InsnList list = new InsnList(); + + // stack: target, this + list.add(getIntNode(mappedType.sizeof - mappedType.padding)); + // stack: sizeof, target, this + list.add( + new MethodInsnNode( + INVOKESTATIC, + MAPPED_HELPER_JVM, + "copy", + "(L" + MAPPED_OBJECT_JVM + ";L" + MAPPED_OBJECT_JVM + ";I)V")); + // stack: - + + return list; + } + + private static InsnList generateRunViewConstructorInstructions(final MethodInsnNode methodInsn) { + final InsnList list = new InsnList(); + + // stack: this + list.add(new InsnNode(DUP)); + // stack: this, this + list.add(new MethodInsnNode(INVOKEVIRTUAL, methodInsn.owner, VIEW_CONSTRUCTOR_NAME, "()V")); + // stack: this + + return list; + } + + private static InsnList generateSliceInstructions(final MethodInsnNode methodInsn) { + final InsnList list = new InsnList(); + + // stack: this + list.add(new TypeInsnNode(NEW, methodInsn.owner)); + // stack: new, this + list.add(new InsnNode(DUP)); + // stack: new, new, this + list.add(new MethodInsnNode(INVOKESPECIAL, methodInsn.owner, "", "()V")); + // stack: new, this + list.add( + new MethodInsnNode( + INVOKESTATIC, + MAPPED_HELPER_JVM, + "slice", + "(L" + MAPPED_OBJECT_JVM + ";L" + MAPPED_OBJECT_JVM + ";)L" + MAPPED_OBJECT_JVM + ";")); + // stack: new + + return list; + } + + private static InsnList generateDupInstructions(final MethodInsnNode methodInsn) { + final InsnList list = new InsnList(); + + // stack: this + list.add(new TypeInsnNode(NEW, methodInsn.owner)); + // stack: new, this + list.add(new InsnNode(DUP)); + // stack: new, new, this + list.add(new MethodInsnNode(INVOKESPECIAL, methodInsn.owner, "", "()V")); + // stack: new, this + list.add( + new MethodInsnNode( + INVOKESTATIC, + MAPPED_HELPER_JVM, + "dup", + "(L" + MAPPED_OBJECT_JVM + ";L" + MAPPED_OBJECT_JVM + ";)L" + MAPPED_OBJECT_JVM + ";")); + // stack: new + + return list; + } + + private static InsnList generateMapInstructions(final MappedSubtypeInfo mappedType, final String className, + final boolean mapDirectMethod, final boolean mallocMethod) { + final InsnList trg = new InsnList(); + + if (mallocMethod) { + // stack: count + trg.add(getIntNode(mappedType.sizeof)); + // stack: sizeof, count + trg.add(new InsnNode(IMUL)); + // stack: bytes + trg.add( + new MethodInsnNode( + INVOKESTATIC, + mappedType.cacheLinePadded ? jvmClassName(CacheUtil.class) : jvmClassName(BufferUtils.class), + "createByteBuffer", + "(I)L" + jvmClassName(ByteBuffer.class) + ";")); + // stack: buffer + } else if (mapDirectMethod) { + // stack: capacity, address + trg.add( + new MethodInsnNode( + INVOKESTATIC, + MAPPED_HELPER_JVM, + "newBuffer", + "(JI)L" + jvmClassName(ByteBuffer.class) + ";")); + // stack: buffer + } + + // stack: buffer + trg.add(new TypeInsnNode(NEW, className)); + // stack: new, buffer + trg.add(new InsnNode(DUP)); + // stack: new, new, buffer + trg.add(new MethodInsnNode(INVOKESPECIAL, className, "", "()V")); + // stack: new, buffer + trg.add(new InsnNode(DUP_X1)); + // stack: new, buffer, new + trg.add(new InsnNode(SWAP)); + // stack: buffer, new, new + trg.add(getIntNode(mappedType.align)); + // stack: int, buffer, new, new + trg.add(getIntNode(mappedType.sizeof)); + // stack: int, int, buffer, new, new + trg.add( + new MethodInsnNode( + INVOKESTATIC, + MAPPED_HELPER_JVM, + "setup", + "(L" + MAPPED_OBJECT_JVM + ";Ljava/nio/ByteBuffer;II)V")); + // stack: new + + return trg; + } + + static InsnList transformFieldAccess(final FieldInsnNode fieldInsn) { + final MappedSubtypeInfo mappedSubtype; + mappedSubtype = className_to_subtype.get(fieldInsn.owner); + if (mappedSubtype == null) { // early out + // MappedSet.view + outer: if ("view".equals(fieldInsn.name) && fieldInsn.owner.startsWith(MAPPEDSET_PREFIX)) + return generateSetViewInstructions(fieldInsn); + + return null; // early out + } + + if ("SIZEOF".equals(fieldInsn.name)) return generateSIZEOFInstructions(fieldInsn, mappedSubtype); + + if ("view".equals(fieldInsn.name)) return generateViewInstructions(fieldInsn, mappedSubtype); + + if ("baseAddress".equals(fieldInsn.name) || "viewAddress".equals(fieldInsn.name)) { + return generateAddressInstructions(fieldInsn); + } + + final FieldInfo field = mappedSubtype.fields.get(fieldInsn.name); + if (field == null) // early out + return null; + + // now we're going to transform ByteBuffer-typed field access + if (fieldInsn.desc.equals("L" + jvmClassName(ByteBuffer.class) + ";")) + return generateByteBufferInstructions(fieldInsn, mappedSubtype, field.offset); + + // we're now going to transform the field access + return generateFieldInstructions(fieldInsn, field); + } + + private static InsnList generateSetViewInstructions(final FieldInsnNode fieldInsn) { + if (fieldInsn.getOpcode() == GETFIELD) throwAccessErrorOnReadOnlyField(fieldInsn.owner, fieldInsn.name); + if (fieldInsn.getOpcode() != PUTFIELD) throw new InternalError(); + + final InsnList list = new InsnList(); + + // stack: index, this + if (MAPPED_SET2_JVM.equals(fieldInsn.owner)) + list.add(new MethodInsnNode(INVOKESTATIC, MAPPED_HELPER_JVM, "put_views", "(L" + MAPPED_SET2_JVM + ";I)V")); + else if (MAPPED_SET3_JVM.equals(fieldInsn.owner)) + list.add(new MethodInsnNode(INVOKESTATIC, MAPPED_HELPER_JVM, "put_views", "(L" + MAPPED_SET3_JVM + ";I)V")); + else if (MAPPED_SET4_JVM.equals(fieldInsn.owner)) + list.add(new MethodInsnNode(INVOKESTATIC, MAPPED_HELPER_JVM, "put_views", "(L" + MAPPED_SET4_JVM + ";I)V")); + else throw new InternalError(); + // stack: - + + return list; + } + + private static InsnList generateSIZEOFInstructions(final FieldInsnNode fieldInsn, + final MappedSubtypeInfo mappedSubtype) { + if (!"I".equals(fieldInsn.desc)) throw new InternalError(); + + final InsnList list = new InsnList(); + + if (fieldInsn.getOpcode() == GETSTATIC) { + list.add(getIntNode(mappedSubtype.sizeof)); + return list; + } + + if (fieldInsn.getOpcode() == PUTSTATIC) throwAccessErrorOnReadOnlyField(fieldInsn.owner, fieldInsn.name); + + throw new InternalError(); + } + + private static InsnList generateViewInstructions(final FieldInsnNode fieldInsn, + final MappedSubtypeInfo mappedSubtype) { + if (!"I".equals(fieldInsn.desc)) throw new InternalError(); + + final InsnList list = new InsnList(); + + if (fieldInsn.getOpcode() == GETFIELD) { + if (mappedSubtype.sizeof_shift != 0) { + // stack: instance + list.add(getIntNode(mappedSubtype.sizeof_shift)); + // stack: sizeof, instance + list.add( + new MethodInsnNode( + INVOKESTATIC, + MAPPED_HELPER_JVM, + "get_view_shift", + "(L" + MAPPED_OBJECT_JVM + ";I)I")); + // stack: view + } else { + // stack: instance + list.add(getIntNode(mappedSubtype.sizeof)); + // stack: sizeof, instance + list.add( + new MethodInsnNode(INVOKESTATIC, MAPPED_HELPER_JVM, "get_view", "(L" + MAPPED_OBJECT_JVM + ";I)I")); + // stack: view + } + return list; + } + + if (fieldInsn.getOpcode() == PUTFIELD) { + if (mappedSubtype.sizeof_shift != 0) { + // stack: view, instance + list.add(getIntNode(mappedSubtype.sizeof_shift)); + // stack: sizeof, view, instance + list.add( + new MethodInsnNode( + INVOKESTATIC, + MAPPED_HELPER_JVM, + "put_view_shift", + "(L" + MAPPED_OBJECT_JVM + ";II)V")); + // stack: - + } else { + // stack: view, instance + list.add(getIntNode(mappedSubtype.sizeof)); + // stack: sizeof, view, instance + list.add( + new MethodInsnNode( + INVOKESTATIC, + MAPPED_HELPER_JVM, + "put_view", + "(L" + MAPPED_OBJECT_JVM + ";II)V")); + // stack: - + } + return list; + } + + throw new InternalError(); + } + + private static InsnList generateAddressInstructions(final FieldInsnNode fieldInsn) { + if (!"J".equals(fieldInsn.desc)) throw new IllegalStateException(); + + if (fieldInsn.getOpcode() == GETFIELD) // do not change a thing + return null; + + if (fieldInsn.getOpcode() == PUTFIELD) throwAccessErrorOnReadOnlyField(fieldInsn.owner, fieldInsn.name); + + throw new InternalError(); + } + + private static InsnList generateByteBufferInstructions(final FieldInsnNode fieldInsn, + final MappedSubtypeInfo mappedSubtype, final long fieldOffset) { + if (fieldInsn.getOpcode() == PUTFIELD) throwAccessErrorOnReadOnlyField(fieldInsn.owner, fieldInsn.name); + + if (fieldInsn.getOpcode() == GETFIELD) { + final InsnList list = new InsnList(); + + // stack: ref + list.add(new FieldInsnNode(GETFIELD, mappedSubtype.className, "viewAddress", "J")); + // stack: long + list.add(new LdcInsnNode(fieldOffset)); + // stack: long, long + list.add(new InsnNode(LADD)); + // stack: long + list.add(new LdcInsnNode(mappedSubtype.fields.get(fieldInsn.name).length)); + // stack: long, long + list.add(new InsnNode(L2I)); + // stack: int, long + list.add( + new MethodInsnNode( + INVOKESTATIC, + MAPPED_HELPER_JVM, + "newBuffer", + "(JI)L" + jvmClassName(ByteBuffer.class) + ";")); + // stack: buffer + + return list; + } + + throw new InternalError(); + } + + private static InsnList generateFieldInstructions(final FieldInsnNode fieldInsn, final FieldInfo field) { + final InsnList list = new InsnList(); + + if (fieldInsn.getOpcode() == PUTFIELD) { + // stack: value, ref + list.add(getIntNode((int) field.offset)); + // stack: fieldOffset, value, ref + list.add( + new MethodInsnNode( + INVOKESTATIC, + MAPPED_HELPER_JVM, + field.getAccessType() + "put", + "(L" + MAPPED_OBJECT_JVM + ";" + fieldInsn.desc + "I)V")); + // stack - + return list; + } + + if (fieldInsn.getOpcode() == GETFIELD) { + // stack: ref + list.add(getIntNode((int) field.offset)); + // stack: fieldOffset, ref + list.add( + new MethodInsnNode( + INVOKESTATIC, + MAPPED_HELPER_JVM, + field.getAccessType() + "get", + "(L" + MAPPED_OBJECT_JVM + ";I)" + fieldInsn.desc)); + // stack: - + return list; + } + + throw new InternalError(); + } + + static int transformArrayAccess(final InsnList instructions, int i, + final Map> frameMap, final VarInsnNode loadInsn, + final MappedSubtypeInfo mappedSubtype, final int var) { + // We need to go forward in time to find how we use the array var + final int loadStackSize = frameMap.get(loadInsn) + .getStackSize() + 1; + + AbstractInsnNode nextInsn = loadInsn; + + while (true) { + nextInsn = nextInsn.getNext(); + if (nextInsn == null) throw new InternalError(); + + Frame frame = frameMap.get(nextInsn); + if (frame == null) continue; + + int stackSize = frame.getStackSize(); + + if (stackSize == loadStackSize + 1 && nextInsn.getOpcode() == AALOAD) { + final AbstractInsnNode aaLoadInsn = nextInsn; + + while (true) { + nextInsn = nextInsn.getNext(); + if (nextInsn == null) break; + + frame = frameMap.get(nextInsn); + if (frame == null) continue; + stackSize = frame.getStackSize(); + + if (stackSize == loadStackSize + 1 && nextInsn.getOpcode() == PUTFIELD) { + final FieldInsnNode fieldInsn = (FieldInsnNode) nextInsn; + + // stack: value, view, ref + instructions.insert( + nextInsn, + new MethodInsnNode( + INVOKESTATIC, + mappedSubtype.className, + setterName(fieldInsn.name), + "(L" + mappedSubtype.className + ";I" + fieldInsn.desc + ")V")); + // stack: - + instructions.remove(nextInsn); + + break; + } else if (stackSize == loadStackSize && nextInsn.getOpcode() == GETFIELD) { + final FieldInsnNode fieldInsn = (FieldInsnNode) nextInsn; + + // stack: view, ref + instructions.insert( + nextInsn, + new MethodInsnNode( + INVOKESTATIC, + mappedSubtype.className, + getterName(fieldInsn.name), + "(L" + mappedSubtype.className + ";I)" + fieldInsn.desc)); + // stack: value + instructions.remove(nextInsn); + + break; + } else if (stackSize == loadStackSize && nextInsn.getOpcode() == DUP + && nextInsn.getNext() + .getOpcode() == GETFIELD) { + // May happen with operator+assignment (e.g. cursor[i].value += 10) + final FieldInsnNode fieldInsn = (FieldInsnNode) nextInsn.getNext(); + + final MethodInsnNode getter = new MethodInsnNode( + INVOKESTATIC, + mappedSubtype.className, + getterName(fieldInsn.name), + "(L" + mappedSubtype.className + ";I)" + fieldInsn.desc); + + // stack: view, ref + instructions.insert(nextInsn, new InsnNode(DUP2)); + // stack: view, ref, view, ref + instructions.insert(nextInsn.getNext(), getter); + // stack: value, view, ref + + instructions.remove(nextInsn); + instructions.remove(fieldInsn); + + nextInsn = getter; + continue; + } else + if (stackSize < loadStackSize) throw new ClassFormatError( + "Invalid " + mappedSubtype.className + + " view array usage detected: " + + getOpcodeName(nextInsn)); + } + + instructions.remove(aaLoadInsn); + + return i; + } else if (stackSize == loadStackSize && nextInsn.getOpcode() == ARRAYLENGTH) { + if (LWJGLUtil.DEBUG && loadInsn.getNext() != nextInsn) throw new InternalError(); + + instructions.remove(nextInsn); + loadInsn.var = var; + instructions.insert( + loadInsn, + new MethodInsnNode(INVOKEVIRTUAL, mappedSubtype.className, CAPACITY_METHOD_NAME, "()I")); + + return i + 1; + } else if (stackSize < loadStackSize) // Consumed by something other than AALOAD or ARRAYLENGTH + throw new ClassFormatError( + "Invalid " + mappedSubtype.className + " view array usage detected: " + getOpcodeName(nextInsn)); + } + } + + private static class FieldInfo { + + final long offset; + final long length; + final long lengthPadded; + final Type type; + final boolean isVolatile; + final boolean isPointer; + + FieldInfo(final long offset, final long length, final long lengthPadded, final Type type, + final boolean isVolatile, final boolean isPointer) { + this.offset = offset; + this.length = length; + this.lengthPadded = lengthPadded; + this.type = type; + this.isVolatile = isVolatile; + this.isPointer = isPointer; + } + + String getAccessType() { + return isPointer ? "a" + : type.getDescriptor() + .toLowerCase() + (isVolatile ? "v" : ""); + } + + } + + private static class MappedSubtypeInfo { + + final String className; + + final int sizeof; + final int sizeof_shift; + final int align; + final int padding; + final boolean cacheLinePadded; + + final Map fields; + + MappedSubtypeInfo(String className, Map fields, int sizeof, int align, int padding, + final boolean cacheLinePadded) { + this.className = className; + + this.sizeof = sizeof; + if (((sizeof - 1) & sizeof) == 0) this.sizeof_shift = getPoT(sizeof); + else this.sizeof_shift = 0; + this.align = align; + this.padding = padding; + this.cacheLinePadded = cacheLinePadded; + + this.fields = fields; + } + + private static int getPoT(int value) { + int pot = -1; + while (value > 0) { + pot++; + value >>= 1; + } + return pot; + } + + } + + // ------------------------------------------------------- + // -------------------[ MACROS & UTILS ]------------------ + // ------------------------------------------------------- + + private static void getClassEnums(final Class clazz, final Map map, + final String... prefixFilters) { + try { + OUTER: for (Field field : clazz.getFields()) { + if (!Modifier.isStatic(field.getModifiers()) || field.getType() != int.class) continue; + + for (String filter : prefixFilters) { + if (field.getName() + .startsWith(filter)) continue OUTER; + } + + if (map.put((Integer) field.get(null), field.getName()) != null) throw new IllegalStateException(); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + static String getOpcodeName(final AbstractInsnNode insn) { + final String op = OPCODE_TO_NAME.get(insn.getOpcode()); + return INSNTYPE_TO_NAME.get(insn.getType()) + ": " + + insn.getOpcode() + + (op == null ? "" : " [" + OPCODE_TO_NAME.get(insn.getOpcode()) + "]"); + } + + static String jvmClassName(Class type) { + return type.getName() + .replace('.', '/'); + } + + static String getterName(final String fieldName) { + return "get$" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1) + "$LWJGL"; + } + + static String setterName(final String fieldName) { + return "set$" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1) + "$LWJGL"; + } + + private static void checkInsnAfterIsArray(final AbstractInsnNode instruction, final int opcode) { + if (instruction == null) throw new ClassFormatError("Unexpected end of instructions after .asArray() method."); + + if (instruction.getOpcode() != opcode) throw new ClassFormatError( + "The result of .asArray() must be stored to a local variable. Found: " + getOpcodeName(instruction)); + } + + static AbstractInsnNode getIntNode(final int value) { + if (value <= 5 && -1 <= value) return new InsnNode(ICONST_M1 + value + 1); + + if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) return new IntInsnNode(BIPUSH, value); + + if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE) return new IntInsnNode(SIPUSH, value); + + return new LdcInsnNode(value); + } + + static void visitIntNode(final MethodVisitor mv, final int value) { + if (value <= 5 && -1 <= value) mv.visitInsn(ICONST_M1 + value + 1); + else if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) mv.visitIntInsn(BIPUSH, value); + else if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE) mv.visitIntInsn(SIPUSH, value); + else mv.visitLdcInsn(value); + } + + /** Replace an instruction with a list of instructions. */ + static int replace(final InsnList instructions, final int i, final AbstractInsnNode location, final InsnList list) { + final int size = list.size(); + + instructions.insert(location, list); + instructions.remove(location); + + return i + (size - 1); + } + + private static void throwAccessErrorOnReadOnlyField(String className, String fieldName) { + throw new IllegalAccessError("The " + className + "." + fieldName + " field is final."); + } + + private static void printBytecode(byte[] bytecode) { + StringWriter sw = new StringWriter(); + ClassVisitor tracer = new TraceClassVisitor(new ClassWriter(0), new PrintWriter(sw)); + new ClassReader(bytecode).accept(tracer, 0); + String dump = sw.toString(); + + LWJGLUtil.log(dump); + } + +} diff --git a/src/main/java/org/lwjglx/util/mapped/MappedObjectUnsafe.java b/src/main/java/org/lwjglx/util/mapped/MappedObjectUnsafe.java new file mode 100644 index 0000000..4bb7fbf --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/MappedObjectUnsafe.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * 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 'LWJGL' 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 org.lwjglx.util.mapped; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import sun.misc.Unsafe; + +/** + * [INTERNAL USE ONLY] + * + * @author Riven + */ +final class MappedObjectUnsafe { + + static final Unsafe INSTANCE = getUnsafeInstance(); + + private static final long BUFFER_ADDRESS_OFFSET = getObjectFieldOffset(ByteBuffer.class, "address"); + private static final long BUFFER_CAPACITY_OFFSET = getObjectFieldOffset(ByteBuffer.class, "capacity"); + + private static final ByteBuffer global = ByteBuffer.allocateDirect(4 * 1024); + + static ByteBuffer newBuffer(long address, int capacity) { + if (address <= 0L || capacity < 0) throw new IllegalStateException("you almost crashed the jvm"); + + ByteBuffer buffer = global.duplicate() + .order(ByteOrder.nativeOrder()); + INSTANCE.putLong(buffer, BUFFER_ADDRESS_OFFSET, address); + INSTANCE.putInt(buffer, BUFFER_CAPACITY_OFFSET, capacity); + buffer.position(0); + buffer.limit(capacity); + return buffer; + } + + private static long getObjectFieldOffset(Class type, String fieldName) { + while (type != null) { + try { + return INSTANCE.objectFieldOffset(type.getDeclaredField(fieldName)); + } catch (Throwable t) { + type = type.getSuperclass(); + } + } + + throw new UnsupportedOperationException(); + } + + private static Unsafe getUnsafeInstance() { + final Field[] fields = Unsafe.class.getDeclaredFields(); + + /* + * Different runtimes use different names for the Unsafe singleton, + * so we cannot use .getDeclaredField and we scan instead. For example: + * Oracle: theUnsafe + * PERC : m_unsafe_instance + * Android: THE_ONE + */ + for (Field field : fields) { + if (!field.getType() + .equals(Unsafe.class)) continue; + + final int modifiers = field.getModifiers(); + if (!(Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers))) continue; + + field.setAccessible(true); + try { + return (Unsafe) field.get(null); + } catch (IllegalAccessException e) { + // ignore + } + break; + } + + throw new UnsupportedOperationException(); + } + +} diff --git a/src/main/java/org/lwjglx/util/mapped/MappedSet.java b/src/main/java/org/lwjglx/util/mapped/MappedSet.java new file mode 100644 index 0000000..6324bd7 --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/MappedSet.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * 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 'LWJGL' 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 org.lwjglx.util.mapped; + +/** + * Factory for mapped sets. A mapped set can be used as a Structure of Arrays by + * linking together the view of two or more mapped objects. Changing the view + * of the mapped set, changes the corresponding view of all the mapped objects in + * the set. + */ +public class MappedSet { + + /** + * Creates a MappedSet by linking the specified MappedObjects. + * + * @return the mapped set. + */ + public static MappedSet2 create(MappedObject a, MappedObject b) { + return new MappedSet2(a, b); + } + + /** + * Creates a MappedSet by linking the specified MappedObjects. + * + * @return the mapped set. + */ + public static MappedSet3 create(MappedObject a, MappedObject b, MappedObject c) { + return new MappedSet3(a, b, c); + } + + /** + * Creates a MappedSet by linking the specified MappedObjects. + * + * @return the mapped set. + */ + public static MappedSet4 create(MappedObject a, MappedObject b, MappedObject c, MappedObject d) { + return new MappedSet4(a, b, c, d); + } + +} diff --git a/src/main/java/org/lwjglx/util/mapped/MappedSet2.java b/src/main/java/org/lwjglx/util/mapped/MappedSet2.java new file mode 100644 index 0000000..117d04f --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/MappedSet2.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * 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 'LWJGL' 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 org.lwjglx.util.mapped; + +/** MappedSet implementation for two MappedObjects. */ +public class MappedSet2 { + + private final MappedObject a, b; + + MappedSet2(MappedObject a, MappedObject b) { + this.a = a; + this.b = b; + } + + public int view; + + void view(int view) { + a.setViewAddress(a.getViewAddress(view)); + b.setViewAddress(b.getViewAddress(view)); + } + + public void next() { + this.a.next(); + this.b.next(); + } + +} diff --git a/src/main/java/org/lwjglx/util/mapped/MappedSet3.java b/src/main/java/org/lwjglx/util/mapped/MappedSet3.java new file mode 100644 index 0000000..c004af0 --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/MappedSet3.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * 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 'LWJGL' 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 org.lwjglx.util.mapped; + +/** MappedSet implementation for three MappedObjects. */ +public class MappedSet3 { + + private final MappedObject a, b, c; + + MappedSet3(MappedObject a, MappedObject b, MappedObject c) { + this.a = a; + this.b = b; + this.c = c; + } + + public int view; + + void view(int view) { + a.setViewAddress(a.getViewAddress(view)); + b.setViewAddress(b.getViewAddress(view)); + c.setViewAddress(c.getViewAddress(view)); + } + + public void next() { + this.a.next(); + this.b.next(); + this.c.next(); + } + +} diff --git a/src/main/java/org/lwjglx/util/mapped/MappedSet4.java b/src/main/java/org/lwjglx/util/mapped/MappedSet4.java new file mode 100644 index 0000000..e2d219b --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/MappedSet4.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * 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 'LWJGL' 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 org.lwjglx.util.mapped; + +/** MappedSet implementation for four MappedObjects. */ +public class MappedSet4 { + + private final MappedObject a, b, c, d; + + MappedSet4(MappedObject a, MappedObject b, MappedObject c, MappedObject d) { + this.a = a; + this.b = b; + this.c = c; + this.d = d; + } + + public int view; + + void view(int view) { + a.setViewAddress(a.getViewAddress(view)); + b.setViewAddress(b.getViewAddress(view)); + c.setViewAddress(c.getViewAddress(view)); + d.setViewAddress(d.getViewAddress(view)); + } + + public void next() { + this.a.next(); + this.b.next(); + this.c.next(); + this.d.next(); + } +} diff --git a/src/main/java/org/lwjglx/util/mapped/MappedType.java b/src/main/java/org/lwjglx/util/mapped/MappedType.java new file mode 100644 index 0000000..f84682b --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/MappedType.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * 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 'LWJGL' 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 org.lwjglx.util.mapped; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * This annotation marks a class as a mapped object, which will go under bytecode + * transformation at runtime. Mapped objects cannot be instantiated directly; a data + * buffer must be mapped first and the mapped object instance will then be used as a + * view on top of the buffer. Instead of a separate instance per "element" in the buffer, + * only a single instance is used to manage everything. See {@link MappedObject} + * for API details and org.lwjgl.test.mapped.TestMappedObject for examples. + *

+ * The instance fields of the annotated class should only be limited to primitive types or + * {@link java.nio.ByteBuffer}. Static fields are supported and they can have any type. + *

+ * The purpose of mapped objects is to reduce the memory requirements required for the type + * of data that are often used in OpenGL/OpenCL programming, while at the same time enabling + * clean Java code. There are also performance benefits related to not having to copy data + * between buffers and Java objects and the removal of bounds checking when accessing + * buffer data. + * + * @author Riven + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface MappedType { + + /** + * The number of bytes to add to the total byte size. + * SIZEOF will be calculated as SIZEOF = max(field_offset + field_length) + padding. + *

+ * Cannot be used with {@link #cacheLinePadding()}. + * + * @return the padding amount + */ + int padding() default 0; + + /** + * When true, SIZEOF will be increased (if necessary) so that it's a multiple of the CPU cache line size. + * Additionally, {@link MappedObject#malloc(int)} on the mapped object type will automatically use + * {@link CacheUtil#createByteBuffer(int)} instead of the unaligned + * {@link org.lwjgl.BufferUtils#createByteBuffer(int)}. + *

+ * Cannot be used with {@link #padding()}. + * + * @return if cache-line padding should be applied + * + * @see CacheUtil + */ + boolean cacheLinePadding() default false; + + /** + * The mapped data memory alignment, in bytes. + * + * @return the memory alignment + */ + int align() default 4; + + /** + * When autoGenerateOffsets is true, byte offsets of the mapped fields will + * be generated automatically. This is convenient for packed data. For manually + * aligned data, autoGenerateOffsets must be set to false and the user needs + * to manually specify byte offsets using the {@link MappedField} annotation. + * + * @return true if automatic byte offset generation is required. + */ + boolean autoGenerateOffsets() default true; + +} diff --git a/src/main/java/org/lwjglx/util/mapped/Pointer.java b/src/main/java/org/lwjglx/util/mapped/Pointer.java new file mode 100644 index 0000000..f7c8982 --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/Pointer.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * 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 'LWJGL' 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 org.lwjglx.util.mapped; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * This annotation can be used on long fields of {@link MappedObject} subclasses, + * to specify that the long value should be interpreted as a pointer. This + * will determine the actual byte size of the field at runtime (4 or 8 bytes). + * + * @author Spasi + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface Pointer { + +}