From 30597377f5f74e1e402481d423a8ecc933e65ed2 Mon Sep 17 00:00:00 2001 From: "nathan.sweet" Date: Sun, 24 Oct 2010 00:11:08 +0000 Subject: [PATCH] [changed] Applied Eclipse source formatter. --- .../gdx/backends/android/AndroidApplication.java | 431 +- .../gdx/backends/android/AndroidAudio.java | 161 +- .../gdx/backends/android/AndroidAudioDevice.java | 91 +- .../gdx/backends/android/AndroidAudioRecorder.java | 50 +- .../gdx/backends/android/AndroidFileHandle.java | 55 +- .../gdx/backends/android/AndroidFiles.java | 232 +- .../badlogic/gdx/backends/android/AndroidFont.java | 112 +- .../badlogic/gdx/backends/android/AndroidGL10.java | 779 +-- .../badlogic/gdx/backends/android/AndroidGL11.java | 445 +- .../badlogic/gdx/backends/android/AndroidGL20.java | 329 +- .../gdx/backends/android/AndroidGraphics.java | 267 +- .../gdx/backends/android/AndroidInput.java | 389 +- .../backends/android/AndroidMultiTouchHandler.java | 123 +- .../gdx/backends/android/AndroidMusic.java | 86 +- .../gdx/backends/android/AndroidPixmap.java | 192 +- .../android/AndroidSingleTouchHandler.java | 72 +- .../gdx/backends/android/AndroidSound.java | 46 +- .../gdx/backends/android/AndroidTexture.java | 284 +- .../gdx/backends/android/AndroidTouchHandler.java | 21 +- .../android/surfaceview/EGLLogWrapper.java | 1061 ++-- .../android/surfaceview/GLBaseSurfaceView.java | 2318 ++++---- .../android/surfaceview/GLDebugHelper.java | 153 +- .../android/surfaceview/GLErrorWrapper.java | 1859 +++--- .../backends/android/surfaceview/GLException.java | 64 +- .../backends/android/surfaceview/GLLogWrapper.java | 6019 ++++++++++---------- .../android/surfaceview/GLSurfaceView20.java | 517 +- .../android/surfaceview/GLSurfaceViewCupcake.java | 1875 +++--- .../android/surfaceview/GLWrapperBase.java | 700 ++- .../gdx/backends/applet/AppletApplication.java | 93 +- .../badlogic/gdx/backends/applet/AppletAudio.java | 217 +- .../gdx/backends/applet/AppletAudioDevice.java | 121 +- .../gdx/backends/applet/AppletAudioRecorder.java | 83 +- .../gdx/backends/applet/AppletFileHandle.java | 35 +- .../badlogic/gdx/backends/applet/AppletFiles.java | 56 +- .../badlogic/gdx/backends/applet/AppletFont.java | 145 +- .../badlogic/gdx/backends/applet/AppletGL10.java | 969 ++-- .../badlogic/gdx/backends/applet/AppletGL11.java | 472 +- .../badlogic/gdx/backends/applet/AppletGL20.java | 934 +-- .../gdx/backends/applet/AppletGraphics.java | 267 +- .../badlogic/gdx/backends/applet/AppletInput.java | 150 +- .../backends/applet/AppletInputMultiplexer.java | 461 +- .../badlogic/gdx/backends/applet/AppletMusic.java | 223 +- .../badlogic/gdx/backends/applet/AppletPanel.java | 363 +- .../badlogic/gdx/backends/applet/AppletPixmap.java | 177 +- .../badlogic/gdx/backends/applet/AppletSound.java | 192 +- .../gdx/backends/applet/AppletTexture.java | 158 +- .../gdx/backends/desktop/JoglApplication.java | 101 +- .../badlogic/gdx/backends/desktop/JoglAudio.java | 227 +- .../gdx/backends/desktop/JoglAudioDevice.java | 123 +- .../gdx/backends/desktop/JoglAudioRecorder.java | 81 +- .../gdx/backends/desktop/JoglFileHandle.java | 38 +- .../badlogic/gdx/backends/desktop/JoglFiles.java | 149 +- .../badlogic/gdx/backends/desktop/JoglFont.java | 145 +- .../badlogic/gdx/backends/desktop/JoglGL10.java | 959 ++-- .../badlogic/gdx/backends/desktop/JoglGL11.java | 472 +- .../badlogic/gdx/backends/desktop/JoglGL20.java | 934 +-- .../gdx/backends/desktop/JoglGraphics.java | 338 +- .../badlogic/gdx/backends/desktop/JoglInput.java | 151 +- .../gdx/backends/desktop/JoglInputMultiplexer.java | 461 +- .../badlogic/gdx/backends/desktop/JoglMusic.java | 223 +- .../badlogic/gdx/backends/desktop/JoglPanel.java | 478 +- .../badlogic/gdx/backends/desktop/JoglPixmap.java | 177 +- .../badlogic/gdx/backends/desktop/JoglSound.java | 192 +- .../badlogic/gdx/backends/desktop/JoglTexture.java | 161 +- .../gdx/backends/desktop/BitmapDecoder.java | 13 +- .../gdx/backends/desktop/LwjglApplication.java | 163 +- .../badlogic/gdx/backends/desktop/LwjglGL10.java | 169 +- .../badlogic/gdx/backends/desktop/LwjglGL11.java | 11 +- .../badlogic/gdx/backends/desktop/LwjglGL20.java | 79 +- .../gdx/backends/desktop/LwjglGraphics.java | 9 +- .../badlogic/gdx/backends/desktop/LwjglInput.java | 16 +- .../badlogic/gdx/backends/desktop/LwjglPixmap.java | 29 +- .../gdx/backends/desktop/LwjglTexture.java | 90 +- .../badlogic/gdx/backends/desktop/PNGDecoder.java | 5 +- .../gdx/backends/desktop/TextureDataSource.java | 111 +- .../com/badlogic/gdx/backends/desktop/VBOTest.java | 124 +- .../src/com/badlogic/gdx/GDXHelloWorld.java | 30 +- .../com/badlogic/gdx/helloworld/HelloWorld.java | 85 +- .../badlogic/gdx/helloworld/HelloWorldDesktop.java | 26 +- .../badlogic/gdxinvaders/GdxInvadersAndroid.java | 19 +- .../badlogic/gdxinvaders/GdxInvadersApplet.java | 28 +- .../src/com/badlogic/gdxinvaders/GdxInvaders.java | 70 +- .../badlogic/gdxinvaders/GdxInvadersDesktop.java | 31 +- .../src/com/badlogic/gdxinvaders/Renderer.java | 341 +- .../com/badlogic/gdxinvaders/screens/GameLoop.java | 88 +- .../com/badlogic/gdxinvaders/screens/GameOver.java | 86 +- .../com/badlogic/gdxinvaders/screens/MainMenu.java | 89 +- .../com/badlogic/gdxinvaders/screens/Screen.java | 41 +- .../com/badlogic/gdxinvaders/simulation/Block.java | 30 +- .../badlogic/gdxinvaders/simulation/Explosion.java | 35 +- .../badlogic/gdxinvaders/simulation/Invader.java | 59 +- .../com/badlogic/gdxinvaders/simulation/Ship.java | 34 +- .../com/badlogic/gdxinvaders/simulation/Shot.java | 39 +- .../gdxinvaders/simulation/Simulation.java | 305 +- .../gdxinvaders/simulation/SimulationListener.java | 24 +- .../src/com/badlogic/gdx/twl/TextAreaTest.java | 26 +- .../src/com/badlogic/gdx/twl/renderer/GdxFont.java | 1 - .../com/badlogic/gdx/twl/renderer/GdxTexture.java | 4 +- .../com/badlogic/gdx/twl/renderer/TextureArea.java | 1 - gdx/src/com/badlogic/gdx/Application.java | 134 +- gdx/src/com/badlogic/gdx/ApplicationListener.java | 68 +- gdx/src/com/badlogic/gdx/Audio.java | 70 +- gdx/src/com/badlogic/gdx/Files.java | 146 +- gdx/src/com/badlogic/gdx/Gdx.java | 45 +- gdx/src/com/badlogic/gdx/GdxRuntimeException.java | 42 +- gdx/src/com/badlogic/gdx/Graphics.java | 253 +- gdx/src/com/badlogic/gdx/Input.java | 372 +- gdx/src/com/badlogic/gdx/InputListener.java | 65 +- gdx/src/com/badlogic/gdx/RenderListener.java | 75 +- gdx/src/com/badlogic/gdx/Version.java | 28 +- gdx/src/com/badlogic/gdx/audio/AudioDevice.java | 55 +- gdx/src/com/badlogic/gdx/audio/AudioRecorder.java | 37 +- gdx/src/com/badlogic/gdx/audio/Music.java | 83 +- gdx/src/com/badlogic/gdx/audio/Sound.java | 44 +- .../badlogic/gdx/audio/analysis/AudioTools.java | 139 +- gdx/src/com/badlogic/gdx/audio/analysis/DFT.java | 215 +- gdx/src/com/badlogic/gdx/audio/analysis/FFT.java | 472 +- .../gdx/audio/analysis/FourierTransform.java | 1157 ++-- .../com/badlogic/gdx/audio/analysis/KissFFT.java | 116 +- .../com/badlogic/gdx/audio/analysis/NativeFFT.java | 60 +- .../gdx/audio/analysis/ThresholdFunction.java | 63 +- gdx/src/com/badlogic/gdx/audio/io/Decoder.java | 55 +- .../com/badlogic/gdx/audio/io/Mpg123Decoder.java | 144 +- .../com/badlogic/gdx/audio/io/VorbisDecoder.java | 136 +- gdx/src/com/badlogic/gdx/files/FileHandle.java | 26 +- gdx/src/com/badlogic/gdx/graphics/BitmapFont.java | 100 +- .../com/badlogic/gdx/graphics/BitmapFontCache.java | 22 +- gdx/src/com/badlogic/gdx/graphics/Color.java | 264 +- gdx/src/com/badlogic/gdx/graphics/Font.java | 208 +- gdx/src/com/badlogic/gdx/graphics/FrameBuffer.java | 218 +- gdx/src/com/badlogic/gdx/graphics/GL10.java | 218 +- gdx/src/com/badlogic/gdx/graphics/GL11.java | 227 +- gdx/src/com/badlogic/gdx/graphics/GL20.java | 232 +- gdx/src/com/badlogic/gdx/graphics/GLCommon.java | 116 +- .../gdx/graphics/ImmediateModeRenderer.java | 207 +- gdx/src/com/badlogic/gdx/graphics/Mesh.java | 1011 ++-- gdx/src/com/badlogic/gdx/graphics/ModelLoader.java | 108 +- gdx/src/com/badlogic/gdx/graphics/ModelWriter.java | 105 +- .../badlogic/gdx/graphics/OrthographicCamera.java | 317 +- .../badlogic/gdx/graphics/PerspectiveCamera.java | 219 +- gdx/src/com/badlogic/gdx/graphics/Pixmap.java | 125 +- .../com/badlogic/gdx/graphics/ShaderProgram.java | 483 +- gdx/src/com/badlogic/gdx/graphics/SpriteBatch.java | 820 ++- gdx/src/com/badlogic/gdx/graphics/Texture.java | 93 +- .../com/badlogic/gdx/graphics/TextureAtlas.java | 60 +- .../com/badlogic/gdx/graphics/TextureRegion.java | 19 +- .../com/badlogic/gdx/graphics/VertexAttribute.java | 40 +- .../badlogic/gdx/graphics/VertexAttributes.java | 123 +- .../badlogic/gdx/graphics/loaders/ObjLoader.java | 210 +- .../badlogic/gdx/graphics/loaders/OctLoader.java | 184 +- .../gdx/graphics/loaders/md5/MD5Animation.java | 78 +- .../gdx/graphics/loaders/md5/MD5AnimationInfo.java | 60 +- .../badlogic/gdx/graphics/loaders/md5/MD5Jni.java | 8 +- .../gdx/graphics/loaders/md5/MD5Joints.java | 6 +- .../gdx/graphics/loaders/md5/MD5Loader.java | 606 +- .../badlogic/gdx/graphics/loaders/md5/MD5Mesh.java | 105 +- .../gdx/graphics/loaders/md5/MD5Model.java | 26 +- .../gdx/graphics/loaders/md5/MD5Quaternion.java | 168 +- .../gdx/graphics/loaders/md5/MD5Renderer.java | 76 +- .../com/badlogic/gdx/math/CatmullRomSpline.java | 304 +- .../com/badlogic/gdx/math/EarCutTriangulator.java | 383 +- gdx/src/com/badlogic/gdx/math/Frustum.java | 263 +- gdx/src/com/badlogic/gdx/math/Intersector.java | 587 +- gdx/src/com/badlogic/gdx/math/Matrix3.java | 175 +- gdx/src/com/badlogic/gdx/math/Matrix4.java | 1282 +++-- gdx/src/com/badlogic/gdx/math/Plane.java | 173 +- gdx/src/com/badlogic/gdx/math/Quaternion.java | 305 +- gdx/src/com/badlogic/gdx/math/Rectangle.java | 84 +- gdx/src/com/badlogic/gdx/math/Vector2.java | 153 +- gdx/src/com/badlogic/gdx/math/Vector3.java | 939 ++- gdx/src/com/badlogic/gdx/math/WindowedMean.java | 135 +- .../badlogic/gdx/math/collision/BoundingBox.java | 613 +- gdx/src/com/badlogic/gdx/math/collision/Ray.java | 98 +- .../com/badlogic/gdx/math/collision/Segment.java | 45 +- .../com/badlogic/gdx/math/collision/Sphere.java | 30 +- gdx/src/com/badlogic/gdx/physics/box2d/Body.java | 731 ++- .../com/badlogic/gdx/physics/box2d/BodyDef.java | 90 +- .../gdx/physics/box2d/Box2DDebugRenderer.java | 264 +- .../badlogic/gdx/physics/box2d/CircleShape.java | 69 +- .../com/badlogic/gdx/physics/box2d/Contact.java | 130 +- .../badlogic/gdx/physics/box2d/ContactFilter.java | 27 +- .../gdx/physics/box2d/ContactListener.java | 25 +- .../gdx/physics/box2d/DestructionListener.java | 16 +- gdx/src/com/badlogic/gdx/physics/box2d/Filter.java | 35 +- .../com/badlogic/gdx/physics/box2d/Fixture.java | 250 +- .../com/badlogic/gdx/physics/box2d/FixtureDef.java | 41 +- gdx/src/com/badlogic/gdx/physics/box2d/Joint.java | 160 +- .../com/badlogic/gdx/physics/box2d/JointDef.java | 61 +- .../com/badlogic/gdx/physics/box2d/JointEdge.java | 32 +- .../com/badlogic/gdx/physics/box2d/MassData.java | 21 +- .../badlogic/gdx/physics/box2d/PolygonShape.java | 115 +- .../badlogic/gdx/physics/box2d/QueryCallback.java | 25 +- gdx/src/com/badlogic/gdx/physics/box2d/Shape.java | 121 +- .../com/badlogic/gdx/physics/box2d/Transform.java | 77 +- gdx/src/com/badlogic/gdx/physics/box2d/World.java | 716 +-- .../badlogic/gdx/physics/box2d/WorldManifold.java | 51 +- .../gdx/physics/box2d/joints/DistanceJoint.java | 99 +- .../gdx/physics/box2d/joints/DistanceJointDef.java | 60 +- .../gdx/physics/box2d/joints/FrictionJoint.java | 69 +- .../gdx/physics/box2d/joints/FrictionJointDef.java | 45 +- .../gdx/physics/box2d/joints/GearJoint.java | 64 +- .../gdx/physics/box2d/joints/GearJointDef.java | 35 +- .../gdx/physics/box2d/joints/LineJoint.java | 181 +- .../gdx/physics/box2d/joints/LineJointDef.java | 70 +- .../gdx/physics/box2d/joints/MouseJoint.java | 129 +- .../gdx/physics/box2d/joints/MouseJointDef.java | 41 +- .../gdx/physics/box2d/joints/PrismaticJoint.java | 169 +- .../physics/box2d/joints/PrismaticJointDef.java | 70 +- .../gdx/physics/box2d/joints/PulleyJoint.java | 93 +- .../gdx/physics/box2d/joints/PulleyJointDef.java | 74 +- .../gdx/physics/box2d/joints/RevoluteJoint.java | 171 +- .../gdx/physics/box2d/joints/RevoluteJointDef.java | 73 +- .../gdx/physics/box2d/joints/WeldJoint.java | 28 +- .../gdx/physics/box2d/joints/WeldJointDef.java | 41 +- .../com/badlogic/gdx/scenes/scene2d/Action.java | 37 +- gdx/src/com/badlogic/gdx/scenes/scene2d/Actor.java | 149 +- gdx/src/com/badlogic/gdx/scenes/scene2d/Group.java | 438 +- gdx/src/com/badlogic/gdx/scenes/scene2d/Stage.java | 302 +- .../badlogic/gdx/scenes/scene2d/actions/Delay.java | 53 +- .../gdx/scenes/scene2d/actions/FadeIn.java | 49 +- .../gdx/scenes/scene2d/actions/FadeOut.java | 49 +- .../gdx/scenes/scene2d/actions/FadeTo.java | 54 +- .../gdx/scenes/scene2d/actions/Forever.java | 56 +- .../gdx/scenes/scene2d/actions/MoveBy.java | 54 +- .../gdx/scenes/scene2d/actions/MoveTo.java | 52 +- .../gdx/scenes/scene2d/actions/Parallel.java | 68 +- .../gdx/scenes/scene2d/actions/Repeat.java | 61 +- .../gdx/scenes/scene2d/actions/RotateBy.java | 55 +- .../gdx/scenes/scene2d/actions/RotateTo.java | 52 +- .../gdx/scenes/scene2d/actions/ScaleTo.java | 59 +- .../gdx/scenes/scene2d/actions/Sequence.java | 76 +- .../gdx/scenes/scene2d/actors/BoundGroup.java | 72 +- .../badlogic/gdx/scenes/scene2d/actors/Button.java | 102 +- .../badlogic/gdx/scenes/scene2d/actors/Image.java | 80 +- .../badlogic/gdx/scenes/scene2d/actors/Label.java | 45 +- .../gdx/scenes/scene2d/actors/LinearGroup.java | 54 +- gdx/src/com/badlogic/gdx/utils/BufferUtils.java | 93 +- gdx/src/com/badlogic/gdx/utils/IntHashMap.java | 351 +- .../gdx/utils/LittleEndianInputStream.java | 302 +- gdx/src/com/badlogic/gdx/utils/LongHashMap.java | 357 +- .../com/badlogic/gdx/utils/PauseableThread.java | 70 +- gdx/src/com/badlogic/gdx/utils/Pool.java | 67 +- .../com/badlogic/gdx/utils/PooledLinkedList.java | 133 +- gdx/src/com/badlogic/gdx/utils/json/JSONArray.java | 1645 +++--- .../com/badlogic/gdx/utils/json/JSONException.java | 31 +- .../com/badlogic/gdx/utils/json/JSONObject.java | 2890 +++++----- .../com/badlogic/gdx/utils/json/JSONString.java | 17 +- .../com/badlogic/gdx/utils/json/JSONStringer.java | 112 +- .../com/badlogic/gdx/utils/json/JSONTokener.java | 799 ++- .../com/badlogic/gdx/utils/json/JSONWriter.java | 544 +- .../src/com/badlogic/gdx/AlphaTest.java | 13 +- .../src/com/badlogic/gdx/AudioDeviceTest.java | 28 +- .../src/com/badlogic/gdx/AudioRecorderTest.java | 28 +- .../src/com/badlogic/gdx/BitmapFontTest.java | 28 +- .../src/com/badlogic/gdx/Box2DTest.java | 26 +- .../src/com/badlogic/gdx/BufferUtilsTest.java | 30 +- .../src/com/badlogic/gdx/FillrateTest.java | 15 +- .../badlogic/gdx/FixedPointMeshRendererTest.java | 28 +- .../src/com/badlogic/gdx/FixedPointTest.java | 28 +- .../src/com/badlogic/gdx/FloatTest.java | 26 +- .../src/com/badlogic/gdx/FrameBufferTest.java | 28 +- .../src/com/badlogic/gdx/GDXTester.java | 173 +- .../src/com/badlogic/gdx/InputTest.java | 28 +- .../src/com/badlogic/gdx/LagTest.java | 54 +- .../src/com/badlogic/gdx/LifeCycleTest.java | 32 +- .../src/com/badlogic/gdx/MD5Test.java | 19 +- .../src/com/badlogic/gdx/ManagedTest.java | 28 +- .../src/com/badlogic/gdx/MeshRendererTest.java | 32 +- .../src/com/badlogic/gdx/MeshShaderTest.java | 28 +- .../src/com/badlogic/gdx/MicroBenchmarks.java | 122 +- .../src/com/badlogic/gdx/Mpg123Test.java | 24 +- .../src/com/badlogic/gdx/MultitouchTest.java | 11 +- .../src/com/badlogic/gdx/ObjTest.java | 28 +- .../src/com/badlogic/gdx/PerformanceTest.java | 28 +- .../src/com/badlogic/gdx/Pong.java | 28 +- .../src/com/badlogic/gdx/ResourcesTest.java | 63 +- .../src/com/badlogic/gdx/SimpleTest.java | 28 +- .../src/com/badlogic/gdx/SoundTest.java | 28 +- .../com/badlogic/gdx/SpriteBatchRotationTest.java | 26 +- .../com/badlogic/gdx/SpriteBatchShaderTest.java | 28 +- .../src/com/badlogic/gdx/SpriteBatchTest.java | 28 +- .../src/com/badlogic/gdx/StageTest.java | 28 +- .../src/com/badlogic/gdx/TerrainTest.java | 13 +- .../src/com/badlogic/gdx/TextTest.java | 28 +- .../src/com/badlogic/gdx/VertexArrayTest.java | 28 +- .../com/badlogic/gdx/VertexBufferObjectTest.java | 28 +- .../src/com/badlogic/gdx/VorbisTest.java | 28 +- .../src/com/badlogic/gdx/WaterRipples.java | 13 +- .../src/com/badlogic/gdx/WindowedTest.java | 107 +- .../src/com/badlogic/gdx/box2d/TestCollection.java | 28 +- .../src/com/badlogic/gdx/SimpleTestApplet.java | 137 +- .../com/badlogic/gdx/tests/desktop/AlphaTest.java | 12 +- .../gdx/tests/desktop/AudioDeviceTest.java | 26 +- .../gdx/tests/desktop/AudioRecorderTest.java | 26 +- .../badlogic/gdx/tests/desktop/BitmapFontTest.java | 26 +- .../com/badlogic/gdx/tests/desktop/Box2DTest.java | 26 +- .../badlogic/gdx/tests/desktop/DualThreadTest.java | 13 +- .../badlogic/gdx/tests/desktop/FillrateTest.java | 11 +- .../gdx/tests/desktop/FixedPointMeshTest.java | 26 +- .../badlogic/gdx/tests/desktop/FixedPointTest.java | 26 +- .../com/badlogic/gdx/tests/desktop/FloatTest.java | 26 +- .../gdx/tests/desktop/FrameBufferTest.java | 26 +- .../tests/desktop/ImmediateModeRendererTest.java | 26 +- .../com/badlogic/gdx/tests/desktop/InputTest.java | 26 +- .../badlogic/gdx/tests/desktop/LifeCycleTest.java | 35 +- .../com/badlogic/gdx/tests/desktop/MD5Test.java | 11 +- .../badlogic/gdx/tests/desktop/ManagedTest.java | 26 +- .../gdx/tests/desktop/MeshMultitextureTest.java | 11 +- .../badlogic/gdx/tests/desktop/MeshShaderTest.java | 26 +- .../com/badlogic/gdx/tests/desktop/MeshTest.java | 26 +- .../gdx/tests/desktop/MicroBenchmarks.java | 84 +- .../com/badlogic/gdx/tests/desktop/Mpg123Test.java | 26 +- .../badlogic/gdx/tests/desktop/MultitouchTest.java | 11 +- .../com/badlogic/gdx/tests/desktop/ObjTest.java | 26 +- .../gdx/tests/desktop/PerformanceTest.java | 26 +- .../src/com/badlogic/gdx/tests/desktop/Pong.java | 31 +- .../gdx/tests/desktop/SimpleAudioRecorder.java | 42 +- .../com/badlogic/gdx/tests/desktop/SimpleTest.java | 28 +- .../com/badlogic/gdx/tests/desktop/SkipTest.java | 52 +- .../com/badlogic/gdx/tests/desktop/SoundTest.java | 26 +- .../gdx/tests/desktop/SpriteBatchRotationTest.java | 26 +- .../gdx/tests/desktop/SpriteBatchShaderTest.java | 26 +- .../gdx/tests/desktop/SpriteBatchTest.java | 26 +- .../com/badlogic/gdx/tests/desktop/StageTest.java | 26 +- .../badlogic/gdx/tests/desktop/TerrainTest.java | 8 +- .../com/badlogic/gdx/tests/desktop/TextTest.java | 28 +- .../gdx/tests/desktop/TextureRenderTest.java | 220 +- .../src/com/badlogic/gdx/tests/desktop/UITest.java | 11 +- .../gdx/tests/desktop/VertexArrayTest.java | 26 +- .../gdx/tests/desktop/VertexBufferObjectTest.java | 26 +- .../com/badlogic/gdx/tests/desktop/VorbisTest.java | 26 +- .../badlogic/gdx/tests/desktop/WaterRipples.java | 11 +- .../gdx/tests/desktop/box2d/TestCollection.java | 26 +- .../com/badlogic/gdx/tests/lwjgl/AlphaTest.java | 11 +- .../badlogic/gdx/tests/lwjgl/BitmapFontTest.java | 28 +- .../badlogic/gdx/tests/lwjgl/FrameBufferTest.java | 26 +- .../src/com/badlogic/gdx/tests/lwjgl/MD5Test.java | 11 +- .../badlogic/gdx/tests/lwjgl/MeshShaderTest.java | 26 +- .../src/com/badlogic/gdx/tests/lwjgl/MeshTest.java | 26 +- .../src/com/badlogic/gdx/tests/lwjgl/ObjTest.java | 11 +- .../src/com/badlogic/gdx/tests/lwjgl/Pong.java | 11 +- .../com/badlogic/gdx/tests/lwjgl/SimpleTest.java | 28 +- .../gdx/tests/lwjgl/SpriteBatchRotationTest.java | 11 +- .../gdx/tests/lwjgl/SpriteBatchShaderTest.java | 26 +- .../badlogic/gdx/tests/lwjgl/SpriteBatchTest.java | 13 +- .../com/badlogic/gdx/tests/lwjgl/StageTest.java | 26 +- .../com/badlogic/gdx/tests/lwjgl/TerrainTest.java | 11 +- .../src/com/badlogic/gdx/tests/lwjgl/TextTest.java | 11 +- .../src/com/badlogic/gdx/tests/lwjgl/UITest.java | 11 +- .../badlogic/gdx/tests/lwjgl/VertexArrayTest.java | 26 +- .../gdx/tests/lwjgl/VertexBufferObjectTest.java | 26 +- .../com/badlogic/gdx/tests/lwjgl/WaterRipples.java | 11 +- .../gdx/tests/lwjgl/box2d/TestCollection.java | 27 +- .../src/com/badlogic/gdx/tests/AlphaTest.java | 45 +- .../com/badlogic/gdx/tests/AudioDeviceTest.java | 83 +- .../com/badlogic/gdx/tests/AudioRecorderTest.java | 108 +- .../src/com/badlogic/gdx/tests/BitmapFontTest.java | 11 +- .../src/com/badlogic/gdx/tests/Box2DTest.java | 332 +- .../src/com/badlogic/gdx/tests/DualThreadTest.java | 81 +- .../src/com/badlogic/gdx/tests/FFTTest.java | 129 +- .../src/com/badlogic/gdx/tests/FillrateTest.java | 146 +- .../com/badlogic/gdx/tests/FixedPointMeshTest.java | 112 +- .../src/com/badlogic/gdx/tests/FixedPointTest.java | 163 +- .../src/com/badlogic/gdx/tests/FloatTest.java | 150 +- .../com/badlogic/gdx/tests/FrameBufferTest.java | 156 +- .../gdx/tests/ImmediateModeRendererTest.java | 73 +- .../src/com/badlogic/gdx/tests/InputTest.java | 73 +- .../src/com/badlogic/gdx/tests/LifeCycleTest.java | 72 +- .../src/com/badlogic/gdx/tests/MD5Test.java | 164 +- .../src/com/badlogic/gdx/tests/ManagedTest.java | 83 +- .../badlogic/gdx/tests/MeshMultitextureTest.java | 96 +- .../src/com/badlogic/gdx/tests/MeshShaderTest.java | 149 +- .../src/com/badlogic/gdx/tests/MeshTest.java | 71 +- .../src/com/badlogic/gdx/tests/Mpg123Test.java | 95 +- .../src/com/badlogic/gdx/tests/MultitouchTest.java | 101 +- .../src/com/badlogic/gdx/tests/ObjTest.java | 132 +- .../com/badlogic/gdx/tests/PerformanceTest.java | 74 +- .../gdx-tests/src/com/badlogic/gdx/tests/Pong.java | 259 +- .../src/com/badlogic/gdx/tests/SimpleTest.java | 93 +- .../src/com/badlogic/gdx/tests/SoundTest.java | 90 +- .../gdx/tests/SpriteBatchRotationTest.java | 121 +- .../badlogic/gdx/tests/SpriteBatchShaderTest.java | 162 +- .../com/badlogic/gdx/tests/SpriteBatchTest.java | 310 +- .../src/com/badlogic/gdx/tests/StageTest.java | 272 +- .../src/com/badlogic/gdx/tests/TerrainTest.java | 209 +- .../src/com/badlogic/gdx/tests/TextTest.java | 66 +- .../com/badlogic/gdx/tests/TextureRenderTest.java | 243 +- .../src/com/badlogic/gdx/tests/UITest.java | 205 +- .../com/badlogic/gdx/tests/VertexArrayTest.java | 89 +- .../badlogic/gdx/tests/VertexBufferObjectTest.java | 103 +- .../src/com/badlogic/gdx/tests/VorbisTest.java | 63 +- .../src/com/badlogic/gdx/tests/WaterRipples.java | 278 +- .../com/badlogic/gdx/tests/box2d/ApplyForce.java | 209 +- .../com/badlogic/gdx/tests/box2d/BodyTypes.java | 166 +- .../com/badlogic/gdx/tests/box2d/Box2DTest.java | 196 +- .../src/com/badlogic/gdx/tests/box2d/Bridge.java | 124 +- .../com/badlogic/gdx/tests/box2d/Cantilever.java | 223 +- .../src/com/badlogic/gdx/tests/box2d/Chain.java | 70 +- .../gdx/tests/box2d/CharacterCollision.java | 178 +- .../gdx/tests/box2d/CollisionFiltering.java | 208 +- .../badlogic/gdx/tests/box2d/ContinuousTest.java | 97 +- .../gdx/tests/box2d/DebugRendererTest.java | 54 +- .../badlogic/gdx/tests/box2d/OneSidedPlatform.java | 101 +- .../com/badlogic/gdx/tests/box2d/Prismatic.java | 101 +- .../src/com/badlogic/gdx/tests/box2d/Pyramid.java | 77 +- .../com/badlogic/gdx/tests/box2d/SimpleTest.java | 83 +- .../com/badlogic/gdx/tests/box2d/SphereStack.java | 55 +- .../badlogic/gdx/tests/box2d/TestCollection.java | 90 +- .../gdx/tests/box2d/VaryingRestitution.java | 62 +- .../badlogic/gdx/tests/box2d/VerticalStack.java | 126 +- 410 files changed, 32009 insertions(+), 40767 deletions(-) diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidApplication.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidApplication.java index d6699f077..e4d96fe04 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidApplication.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidApplication.java @@ -1,22 +1,18 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ package com.badlogic.gdx.backends.android; - import android.app.Activity; import android.os.Build; import android.util.Log; @@ -37,255 +33,214 @@ import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.GL11; /** - * An implementation of the {@link Application} interface for Android. Create an {@link Activity} - * that derives from this class. In the {@link Activity.onCreate()} method call the {@link initialize()} - * method specifying the configuration for the GLSurfaceView. - * + * An implementation of the {@link Application} interface for Android. Create an {@link Activity} that derives from this class. In + * the {@link Activity.onCreate()} method call the {@link initialize()} method specifying the configuration for the GLSurfaceView. + * * @author mzechner */ public class AndroidApplication extends Activity implements Application { - - static - { + + static { Version.loadLibrary(); - } - - /** - * the android graphics instance * - */ - private AndroidGraphics graphics; - - /** - * the input instance * - */ - private AndroidInput input; - - /** - * the audio instance * - */ - private AndroidAudio audio; - - /** - * the resources instance * - */ - private AndroidFiles resources; - - /** - * the DestroyListener * - */ - private ApplicationListener listener; - - /** - * This method has to be called in the {@link Activity.onCreate()} - * method. It sets up all the things necessary to get input, render - * via OpenGL and so on. If useGL20IfAvailable is set the - * AndroidApplication will try to create an OpenGL ES 2.0 context - * which can then be used via {@link AndroidApplication.getGraphics().getGL20()}. The - * {@link GL10} and {@link GL11} interfaces should not be used when - * OpenGL ES 2.0 is enabled. To query whether enabling OpenGL ES 2.0 was - * successful use the {@link AndroidApplication.getGraphics().isGL20Available()} - * method. Sleep time in touch event handler is 0, so no sleeping is performed. - * - * @param useGL2IfAvailable whether to use OpenGL ES 2.0 if its available. - */ - public void initialize(boolean useGL2IfAvailable) { - initialize(useGL2IfAvailable, 0); - } - - /** - * This method has to be called in the {@link Activity.onCreate()} - * method. It sets up all the things necessary to get input, render - * via OpenGL and so on. If useGL20IfAvailable is set the - * AndroidApplication will try to create an OpenGL ES 2.0 context - * which can then be used via {@link AndroidApplication.getGraphics().getGL20()}. The - * {@link GL10} and {@link GL11} interfaces should not be used when - * OpenGL ES 2.0 is enabled. To query whether enabling OpenGL ES 2.0 was - * successful use the {@link AndroidApplication.getGraphics().isGL20Available()} - * method. sleepTime specifies the number of milliseconds to sleep in the touch - * event handler. This may be used on <= 1.6 Android devices. Note that it will not - * solve the CPU usage problem of the event handler of the Android system. Things will - * still slow down. - * - * @param useGL2IfAvailable whether to use OpenGL ES 2.0 if its available. - * @param sleepTime specifies the number of milliseconds to sleep in the touch event handler - */ - public void initialize(boolean useGL2IfAvailable, int sleepTime ) - { + } + + /** + * the android graphics instance * + */ + private AndroidGraphics graphics; + + /** + * the input instance * + */ + private AndroidInput input; + + /** + * the audio instance * + */ + private AndroidAudio audio; + + /** + * the resources instance * + */ + private AndroidFiles resources; + + /** + * the DestroyListener * + */ + private ApplicationListener listener; + + /** + * This method has to be called in the {@link Activity.onCreate()} method. It sets up all the things necessary to get input, + * render via OpenGL and so on. If useGL20IfAvailable is set the AndroidApplication will try to create an OpenGL ES 2.0 context + * which can then be used via {@link AndroidApplication.getGraphics().getGL20()}. The {@link GL10} and {@link GL11} interfaces + * should not be used when OpenGL ES 2.0 is enabled. To query whether enabling OpenGL ES 2.0 was successful use the {@link + * AndroidApplication.getGraphics().isGL20Available()} method. Sleep time in touch event handler is 0, so no sleeping is + * performed. + * + * @param useGL2IfAvailable whether to use OpenGL ES 2.0 if its available. + */ + public void initialize (boolean useGL2IfAvailable) { + initialize(useGL2IfAvailable, 0); + } + + /** + * This method has to be called in the {@link Activity.onCreate()} method. It sets up all the things necessary to get input, + * render via OpenGL and so on. If useGL20IfAvailable is set the AndroidApplication will try to create an OpenGL ES 2.0 context + * which can then be used via {@link AndroidApplication.getGraphics().getGL20()}. The {@link GL10} and {@link GL11} interfaces + * should not be used when OpenGL ES 2.0 is enabled. To query whether enabling OpenGL ES 2.0 was successful use the {@link + * AndroidApplication.getGraphics().isGL20Available()} method. sleepTime specifies the number of milliseconds to sleep in the + * touch event handler. This may be used on <= 1.6 Android devices. Note that it will not solve the CPU usage problem of the + * event handler of the Android system. Things will still slow down. + * + * @param useGL2IfAvailable whether to use OpenGL ES 2.0 if its available. + * @param sleepTime specifies the number of milliseconds to sleep in the touch event handler + */ + public void initialize (boolean useGL2IfAvailable, int sleepTime) { requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); - graphics = new AndroidGraphics(this, useGL2IfAvailable); - setContentView( graphics.getView() ); - input = new AndroidInput(this, graphics.view, sleepTime); - graphics.setInput(input); - audio = new AndroidAudio(this); - resources = new AndroidFiles(this.getAssets()); - - Gdx.app = this; + graphics = new AndroidGraphics(this, useGL2IfAvailable); + setContentView(graphics.getView()); + input = new AndroidInput(this, graphics.view, sleepTime); + graphics.setInput(input); + audio = new AndroidAudio(this); + resources = new AndroidFiles(this.getAssets()); + + Gdx.app = this; Gdx.input = this.getInput(); Gdx.audio = this.getAudio(); Gdx.files = this.getFiles(); Gdx.graphics = this.getGraphics(); - } - - /** - * This method has to be called in the {@link Activity.onCreate()} - * method. It sets up all the things necessary to get input, render - * via OpenGL and so on. If useGL20IfAvailable is set the - * AndroidApplication will try to create an OpenGL ES 2.0 context - * which can then be used via {@link AndroidApplication.getGraphics().getGL20()}. The - * {@link GL10} and {@link GL11} interfaces should not be used when - * OpenGL ES 2.0 is enabled. To query whether enabling OpenGL ES 2.0 was - * successful use the {@link AndroidApplication.getGraphics().isGL20Available()} - * method. sleepTime specifies the number of milliseconds to sleep in the touch - * event handler. This may be used on <= 1.6 Android devices. Note that it will not - * solve the CPU usage problem of the event handler of the Android system. Things will - * still slow down. - * - * Note: you have to add the returned view to your layout! - * - * @param useGL2IfAvailable whether to use OpenGL ES 2.0 if its available. - * @param sleepTime specifies the number of milliseconds to sleep in the touch event handler - * @return the GLSurfaceView of the application - */ - public View initializeForView( boolean useGL2IfAvailable, int sleepTime ) - { - graphics = new AndroidGraphics(this, useGL2IfAvailable ); - input = new AndroidInput(this, graphics.view, sleepTime); - graphics.setInput(input); - audio = new AndroidAudio(this); - resources = new AndroidFiles(this.getAssets()); - - Gdx.app = this; + } + + /** + * This method has to be called in the {@link Activity.onCreate()} method. It sets up all the things necessary to get input, + * render via OpenGL and so on. If useGL20IfAvailable is set the AndroidApplication will try to create an OpenGL ES 2.0 context + * which can then be used via {@link AndroidApplication.getGraphics().getGL20()}. The {@link GL10} and {@link GL11} interfaces + * should not be used when OpenGL ES 2.0 is enabled. To query whether enabling OpenGL ES 2.0 was successful use the {@link + * AndroidApplication.getGraphics().isGL20Available()} method. sleepTime specifies the number of milliseconds to sleep in the + * touch event handler. This may be used on <= 1.6 Android devices. Note that it will not solve the CPU usage problem of the + * event handler of the Android system. Things will still slow down. + * + * Note: you have to add the returned view to your layout! + * + * @param useGL2IfAvailable whether to use OpenGL ES 2.0 if its available. + * @param sleepTime specifies the number of milliseconds to sleep in the touch event handler + * @return the GLSurfaceView of the application + */ + public View initializeForView (boolean useGL2IfAvailable, int sleepTime) { + graphics = new AndroidGraphics(this, useGL2IfAvailable); + input = new AndroidInput(this, graphics.view, sleepTime); + graphics.setInput(input); + audio = new AndroidAudio(this); + resources = new AndroidFiles(this.getAssets()); + + Gdx.app = this; Gdx.input = this.getInput(); Gdx.audio = this.getAudio(); Gdx.files = this.getFiles(); Gdx.graphics = this.getGraphics(); - + return graphics.getView(); - } - - @Override - protected void onPause() { - super.onPause(); - - if (isFinishing()) - { - graphics.disposeRenderListener(); - graphics.clearManagedCaches(); - } - - if ( graphics != null && graphics.view != null) - { - if( graphics.view instanceof GLSurfaceViewCupcake ) - ((GLSurfaceViewCupcake)graphics.view).onPause(); - if( graphics.view instanceof android.opengl.GLSurfaceView ) - ((android.opengl.GLSurfaceView)graphics.view).onPause(); - } - - if( audio != null ) - audio.pause(); - - if (listener != null) - listener.pause(); - } - - @Override - protected void onResume() { - super.onResume(); - - Gdx.app = this; + } + + @Override protected void onPause () { + super.onPause(); + + if (isFinishing()) { + graphics.disposeRenderListener(); + graphics.clearManagedCaches(); + } + + if (graphics != null && graphics.view != null) { + if (graphics.view instanceof GLSurfaceViewCupcake) ((GLSurfaceViewCupcake)graphics.view).onPause(); + if (graphics.view instanceof android.opengl.GLSurfaceView) ((android.opengl.GLSurfaceView)graphics.view).onPause(); + } + + if (audio != null) audio.pause(); + + if (listener != null) listener.pause(); + } + + @Override protected void onResume () { + super.onResume(); + + Gdx.app = this; Gdx.input = this.getInput(); Gdx.audio = this.getAudio(); Gdx.files = this.getFiles(); Gdx.graphics = this.getGraphics(); - - if (listener != null) - listener.resume(); - - if ( graphics != null && graphics.view != null) - { - if( graphics.view instanceof GLSurfaceViewCupcake ) - ((GLSurfaceViewCupcake)graphics.view).onResume(); - if( graphics.view instanceof android.opengl.GLSurfaceView ) - ((android.opengl.GLSurfaceView)graphics.view).onResume(); - } - - if( audio != null ) - audio.resume(); - } - - @Override - protected void onDestroy() { - super.onDestroy(); - - if (listener != null) - listener.destroy(); - - audio.dispose(); - } - - /** - * {@inheritDoc} - */ - @Override - public Audio getAudio() { - return audio; - } - - /** - * {@inheritDoc} - */ - @Override - public Files getFiles() { - return resources; - } - - /** - * {@inheritDoc} - */ - @Override - public Graphics getGraphics() { - return graphics; - } - - /** - * {@inheritDoc} - */ - @Override - public Input getInput() { - return input; - } - - /** - * {@inheritDoc} - */ - @Override - public void setApplicationListener(ApplicationListener listener) { - this.listener = listener; - } - - /** - * {@inheritDoc} - */ - @Override - public void log(String tag, String message) { - Log.d(tag, message); - } - - /** - * {@inheritDoc} - */ - @Override - public ApplicationType getType() { - return ApplicationType.Android; + + if (listener != null) listener.resume(); + + if (graphics != null && graphics.view != null) { + if (graphics.view instanceof GLSurfaceViewCupcake) ((GLSurfaceViewCupcake)graphics.view).onResume(); + if (graphics.view instanceof android.opengl.GLSurfaceView) ((android.opengl.GLSurfaceView)graphics.view).onResume(); + } + + if (audio != null) audio.resume(); + } + + @Override protected void onDestroy () { + super.onDestroy(); + + if (listener != null) listener.destroy(); + + audio.dispose(); + } + + /** + * {@inheritDoc} + */ + @Override public Audio getAudio () { + return audio; + } + + /** + * {@inheritDoc} + */ + @Override public Files getFiles () { + return resources; + } + + /** + * {@inheritDoc} + */ + @Override public Graphics getGraphics () { + return graphics; + } + + /** + * {@inheritDoc} + */ + @Override public Input getInput () { + return input; + } + + /** + * {@inheritDoc} + */ + @Override public void setApplicationListener (ApplicationListener listener) { + this.listener = listener; + } + + /** + * {@inheritDoc} + */ + @Override public void log (String tag, String message) { + Log.d(tag, message); + } + + /** + * {@inheritDoc} + */ + @Override public ApplicationType getType () { + return ApplicationType.Android; } - /** - * {@inheritDoc} - */ - @Override - public int getVersion() - { + /** + * {@inheritDoc} + */ + @Override public int getVersion () { return Build.VERSION.SDK.charAt(0) - '0'; } } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidAudio.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidAudio.java index ebd587c70..878dbd94c 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidAudio.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidAudio.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import java.io.IOException; @@ -38,96 +36,73 @@ import com.badlogic.gdx.files.FileHandle; * An implementation of the {@link Audio} interface for Android. * * @author mzechner - * + * */ -final class AndroidAudio implements Audio -{ - private SoundPool soundPool; +final class AndroidAudio implements Audio { + private SoundPool soundPool; private final AudioManager manager; - protected final List musics = new ArrayList( ); - protected final List wasPlaying = new ArrayList( ); - - AndroidAudio( Activity context ) - { - soundPool = new SoundPool( 16, AudioManager.STREAM_MUSIC, 100); + protected final List musics = new ArrayList(); + protected final List wasPlaying = new ArrayList(); + + AndroidAudio (Activity context) { + soundPool = new SoundPool(16, AudioManager.STREAM_MUSIC, 100); manager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE); context.setVolumeControlStream(AudioManager.STREAM_MUSIC); } - - protected void pause( ) - { + + protected void pause () { wasPlaying.clear(); - for( AndroidMusic music: musics ) - { - if( music.isPlaying() ) - { + for (AndroidMusic music : musics) { + if (music.isPlaying()) { music.pause(); - wasPlaying.add( true ); - } - else - wasPlaying.add( false ); + wasPlaying.add(true); + } else + wasPlaying.add(false); } } - - protected void resume( ) - { - for( int i = 0; i < musics.size(); i++ ) - { - if( wasPlaying.get(i) ) - musics.get(i).play(); + + protected void resume () { + for (int i = 0; i < musics.size(); i++) { + if (wasPlaying.get(i)) musics.get(i).play(); } } - + /** * {@inheritDoc} */ - @Override - public AudioDevice newAudioDevice(boolean isMono) - { - return new AndroidAudioDevice( isMono ); + @Override public AudioDevice newAudioDevice (boolean isMono) { + return new AndroidAudioDevice(isMono); } /** * {@inheritDoc} */ - @Override - public Music newMusic(FileHandle file) - { + @Override public Music newMusic (FileHandle file) { AndroidFileHandle aHandle = (AndroidFileHandle)file; - - + MediaPlayer mediaPlayer = new MediaPlayer(); - - if( aHandle.isAsset() ) - { - try - { - AssetFileDescriptor descriptor = aHandle.getAssetManager().openFd( aHandle.getFileName() ); - mediaPlayer.setDataSource( descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength() ); + + if (aHandle.isAsset()) { + try { + AssetFileDescriptor descriptor = aHandle.getAssetManager().openFd(aHandle.getFileName()); + mediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength()); descriptor.close(); - mediaPlayer.prepare(); - AndroidMusic music = new AndroidMusic( this, mediaPlayer ); - musics.add( music ); + mediaPlayer.prepare(); + AndroidMusic music = new AndroidMusic(this, mediaPlayer); + musics.add(music); return music; + } catch (Exception ex) { + throw new GdxRuntimeException("Couldn't load Music from file '" + file + "'", ex); } - catch( Exception ex ) - { - throw new GdxRuntimeException( "Couldn't load Music from file '" + file + "'", ex ); - } - } - else - { - try - { - mediaPlayer.setDataSource( aHandle.getFileName() ); - mediaPlayer.prepare(); - AndroidMusic music = new AndroidMusic( this, mediaPlayer ); - musics.add( music ); + } else { + try { + mediaPlayer.setDataSource(aHandle.getFileName()); + mediaPlayer.prepare(); + AndroidMusic music = new AndroidMusic(this, mediaPlayer); + musics.add(music); return music; - } - catch( Exception ex ) - { - throw new GdxRuntimeException( "Couldn't load music from file '" + file + "'", ex ); + } catch (Exception ex) { + throw new GdxRuntimeException("Couldn't load music from file '" + file + "'", ex); } } @@ -136,47 +111,37 @@ final class AndroidAudio implements Audio /** * {@inheritDoc} */ - @Override - public Sound newSound(FileHandle file) - { + @Override public Sound newSound (FileHandle file) { AndroidFileHandle aHandle = (AndroidFileHandle)file; - if( aHandle.isAsset() ) - { + if (aHandle.isAsset()) { try { - AssetFileDescriptor descriptor = aHandle.getAssetManager().openFd( aHandle.getFileName() ); - AndroidSound sound = new AndroidSound( soundPool, manager, soundPool.load( descriptor, 1) ); + AssetFileDescriptor descriptor = aHandle.getAssetManager().openFd(aHandle.getFileName()); + AndroidSound sound = new AndroidSound(soundPool, manager, soundPool.load(descriptor, 1)); descriptor.close(); return sound; } catch (IOException e) { - throw new GdxRuntimeException( "Couldn't load Sound from file '" + file + "'", e ); + throw new GdxRuntimeException("Couldn't load Sound from file '" + file + "'", e); } - } - else - { - try - { - return new AndroidSound( soundPool, manager, soundPool.load(aHandle.getFileName(), 1) ); - } - catch( Exception e ) - { - throw new GdxRuntimeException( "Couldn't load Sound from file '" + file + "'", e ); + } else { + try { + return new AndroidSound(soundPool, manager, soundPool.load(aHandle.getFileName(), 1)); + } catch (Exception e) { + throw new GdxRuntimeException("Couldn't load Sound from file '" + file + "'", e); } - } + } } /** * {@inheritDoc} */ - @Override - public AudioRecorder newAudioRecoder(int samplingRate, boolean isMono) { - return new AndroidAudioRecorder( samplingRate, isMono ); + @Override public AudioRecorder newAudioRecoder (int samplingRate, boolean isMono) { + return new AndroidAudioRecorder(samplingRate, isMono); } /** * Kills the soundpool and all other resources */ - public void dispose() - { + public void dispose () { soundPool.release(); } } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidAudioDevice.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidAudioDevice.java index 856e96c0d..e51665e80 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidAudioDevice.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidAudioDevice.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import android.media.AudioFormat; @@ -22,75 +20,60 @@ import android.media.AudioTrack; import com.badlogic.gdx.audio.AudioDevice; /** - * Implementation of the {@link AudioDevice} interface for Android - * using the AudioTrack class. You will need to set the permission + * Implementation of the {@link AudioDevice} interface for Android using the AudioTrack class. You will need to set the permission * android.permission.RECORD_AUDIO in your manifest file. * @author mzechner - * + * */ -class AndroidAudioDevice implements AudioDevice -{ +class AndroidAudioDevice implements AudioDevice { /** the audio track **/ private final AudioTrack track; - + /** the mighty buffer **/ private short[] buffer = new short[1024]; /** whether this device is in mono or stereo mode **/ private final boolean isMono; - - AndroidAudioDevice( boolean isMono ) - { + + AndroidAudioDevice (boolean isMono) { this.isMono = isMono; - int minSize =AudioTrack.getMinBufferSize( 44100, isMono?AudioFormat.CHANNEL_CONFIGURATION_MONO:AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT ); - track = new AudioTrack( AudioManager.STREAM_MUSIC, 44100, - isMono?AudioFormat.CHANNEL_CONFIGURATION_MONO:AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT, - minSize, AudioTrack.MODE_STREAM); - track.play(); + int minSize = AudioTrack.getMinBufferSize(44100, isMono ? AudioFormat.CHANNEL_CONFIGURATION_MONO + : AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT); + track = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, isMono ? AudioFormat.CHANNEL_CONFIGURATION_MONO + : AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT, minSize, AudioTrack.MODE_STREAM); + track.play(); } - - @Override - public void dispose() - { + + @Override public void dispose () { track.stop(); track.release(); } - @Override - public boolean isMono() - { + @Override public boolean isMono () { return isMono; } - @Override - public void writeSamples(short[] samples, int offset, int numSamples) - { - int writtenSamples = track.write( samples, offset, numSamples ); - while( writtenSamples != numSamples ) - writtenSamples += track.write( samples, offset + writtenSamples, numSamples - writtenSamples ); + @Override public void writeSamples (short[] samples, int offset, int numSamples) { + int writtenSamples = track.write(samples, offset, numSamples); + while (writtenSamples != numSamples) + writtenSamples += track.write(samples, offset + writtenSamples, numSamples - writtenSamples); } - @Override - public void writeSamples(float[] samples, int offset, int numSamples) - { - if( buffer.length < samples.length ) - buffer = new short[samples.length]; - + @Override public void writeSamples (float[] samples, int offset, int numSamples) { + if (buffer.length < samples.length) buffer = new short[samples.length]; + int bound = offset + numSamples; - for( int i = offset, j = 0; i < bound; i++, j++ ) - { - float fValue = samples[i]; - if( fValue > 1 ) - fValue = 1; - if( fValue < -1 ) - fValue = -1; - short value = (short)( fValue * Short.MAX_VALUE); + for (int i = offset, j = 0; i < bound; i++, j++) { + float fValue = samples[i]; + if (fValue > 1) fValue = 1; + if (fValue < -1) fValue = -1; + short value = (short)(fValue * Short.MAX_VALUE); buffer[j] = value; } - - int writtenSamples = track.write( buffer, 0, numSamples ); - while( writtenSamples != numSamples ) - writtenSamples += track.write( buffer, writtenSamples, numSamples - writtenSamples ); + + int writtenSamples = track.write(buffer, 0, numSamples); + while (writtenSamples != numSamples) + writtenSamples += track.write(buffer, writtenSamples, numSamples - writtenSamples); } } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidAudioRecorder.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidAudioRecorder.java index 0aacd144a..0fd29db5c 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidAudioRecorder.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidAudioRecorder.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import android.media.AudioFormat; @@ -22,37 +20,31 @@ import android.media.MediaRecorder; import com.badlogic.gdx.audio.AudioRecorder; /** - * {@link AudioRecorder} implementation for the android system based - * on AudioRecord + * {@link AudioRecorder} implementation for the android system based on AudioRecord * @author badlogicgames@gmail.com - * + * */ -public class AndroidAudioRecorder implements AudioRecorder -{ +public class AndroidAudioRecorder implements AudioRecorder { /** the audio track we read samples from **/ private AudioRecord recorder; - - public AndroidAudioRecorder( int samplingRate, boolean isMono ) - { - int minBufferSize = AudioRecord.getMinBufferSize( samplingRate, isMono?AudioFormat.CHANNEL_CONFIGURATION_MONO:AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT); - recorder = new AudioRecord( MediaRecorder.AudioSource.MIC, samplingRate, isMono?AudioFormat.CHANNEL_CONFIGURATION_MONO:AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT, minBufferSize); + + public AndroidAudioRecorder (int samplingRate, boolean isMono) { + int minBufferSize = AudioRecord.getMinBufferSize(samplingRate, isMono ? AudioFormat.CHANNEL_CONFIGURATION_MONO + : AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT); + recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, samplingRate, isMono ? AudioFormat.CHANNEL_CONFIGURATION_MONO + : AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT, minBufferSize); recorder.startRecording(); } - - @Override - public void dispose() - { + + @Override public void dispose () { recorder.stop(); recorder.release(); } - @Override - public void read(short[] samples, int offset, int numSamples) - { + @Override public void read (short[] samples, int offset, int numSamples) { int read = 0; - while( read != numSamples ) - { - read += recorder.read( samples, offset + read, numSamples - read ); + while (read != numSamples) { + read += recorder.read(samples, offset + read, numSamples - read); } } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidFileHandle.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidFileHandle.java index 9578bb4fe..017238bd3 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidFileHandle.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidFileHandle.java @@ -1,72 +1,62 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; -import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; +import android.content.res.AssetManager; + import com.badlogic.gdx.GdxRuntimeException; import com.badlogic.gdx.files.FileHandle; -import android.content.res.AssetManager; - /** - * A {@link FileHandle} implementation for Android. Encapsulates - * assets and files on the external storage device. + * A {@link FileHandle} implementation for Android. Encapsulates assets and files on the external storage device. * * @author mzechner - * + * */ -public class AndroidFileHandle implements FileHandle -{ +public class AndroidFileHandle implements FileHandle { /** the asset manager or null if this is an external file **/ private final AssetManager manager; - + /** the filename **/ private final String filename; - - AndroidFileHandle( AssetManager manager, String filename ) - { + + AndroidFileHandle (AssetManager manager, String filename) { this.manager = manager; this.filename = filename; } - + /** * @return whether this is an asset file or an external file */ - public boolean isAsset( ) - { + public boolean isAsset () { return manager != null; } - + /** * @return the {@link AssetManager} or null */ - public AssetManager getAssetManager( ) - { + public AssetManager getAssetManager () { return manager; } - + /** * @return the filename */ - public String getFileName( ) - { + public String getFileName () { return filename; } @@ -78,8 +68,7 @@ public class AndroidFileHandle implements FileHandle } } - public String toString( ) - { + public String toString () { return filename; } } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidFiles.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidFiles.java index ec2a2be42..6d82e0796 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidFiles.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidFiles.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import java.io.File; @@ -30,95 +28,72 @@ import com.badlogic.gdx.GdxRuntimeException; import com.badlogic.gdx.files.FileHandle; /** - * An implementation of the {@link Files} interface for Android. External files are stored and accessed - * relative to Environment.getExternalStorageDirectory().getAbsolutePath(). Internal files are accessed - * relative to the assets directory. + * An implementation of the {@link Files} interface for Android. External files are stored and accessed relative to + * Environment.getExternalStorageDirectory().getAbsolutePath(). Internal files are accessed relative to the assets directory. * * @author mzechner - * + * */ -final class AndroidFiles implements Files -{ +final class AndroidFiles implements Files { /** external storage path **/ private final String sdcard = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"; /** asset manager **/ private final AssetManager assets; - AndroidFiles( AssetManager assets ) - { + AndroidFiles (AssetManager assets) { this.assets = assets; } /** * @return the asset manager. */ - protected AssetManager getAssetManager( ) - { + protected AssetManager getAssetManager () { return assets; } - - private InputStream readExternalFile(String fileName) - { + private InputStream readExternalFile (String fileName) { FileInputStream in = null; - try - { - in = new FileInputStream( sdcard + fileName ); - } - catch( FileNotFoundException ex ) - { - throw new GdxRuntimeException( "Couldn't open file '" + fileName + "'", ex ); + try { + in = new FileInputStream(sdcard + fileName); + } catch (FileNotFoundException ex) { + throw new GdxRuntimeException("Couldn't open file '" + fileName + "'", ex); } return in; } - - private InputStream readInternalFile(String fileName) - { + private InputStream readInternalFile (String fileName) { InputStream in = null; - try - { - in = assets.open( fileName ); - } - catch( Exception ex ) - { - throw new GdxRuntimeException( "Couldn't load file '" + fileName + "'", ex ); + try { + in = assets.open(fileName); + } catch (Exception ex) { + throw new GdxRuntimeException("Couldn't load file '" + fileName + "'", ex); } return in; } - private OutputStream writeExternalFile(String filename) - { + private OutputStream writeExternalFile (String filename) { FileOutputStream out = null; - try - { - out = new FileOutputStream( sdcard + filename ); - } - catch( FileNotFoundException ex ) - { - throw new GdxRuntimeException( "Couldn't open file '" + filename + "'", ex ); + try { + out = new FileOutputStream(sdcard + filename); + } catch (FileNotFoundException ex) { + throw new GdxRuntimeException("Couldn't open file '" + filename + "'", ex); } return out; } - - - private InputStream readAbsolutFile(String filename) - { + + private InputStream readAbsolutFile (String filename) { FileInputStream in = null; - try - { - in = new FileInputStream( filename ); - } - catch( FileNotFoundException ex ) - { - throw new GdxRuntimeException( "Couldn't open file '" + filename + "'", ex ); + try { + in = new FileInputStream(filename); + } catch (FileNotFoundException ex) { + throw new GdxRuntimeException("Couldn't open file '" + filename + "'", ex); } return in; @@ -127,129 +102,98 @@ final class AndroidFiles implements Files /** * {@inheritDoc} */ - @Override - public FileHandle getFileHandle(String filename, FileType type) - { - if( type == FileType.Internal ) - { + @Override public FileHandle getFileHandle (String filename, FileType type) { + if (type == FileType.Internal) { boolean exists = true; - - try - { - InputStream in = assets.open( filename ); + + try { + InputStream in = assets.open(filename); in.close(); - } - catch( Exception ex ) - { + } catch (Exception ex) { exists = false; } - - if( !exists ) - throw new GdxRuntimeException( "Couldn't open file '" + filename + "'" ); + + if (!exists) + throw new GdxRuntimeException("Couldn't open file '" + filename + "'"); else - return new AndroidFileHandle( assets, filename); + return new AndroidFileHandle(assets, filename); } - - if( type == FileType.External ) - { - if( new File( sdcard + filename ).exists() == false ) - throw new GdxRuntimeException( "Couldn't open file '" + filename + "'" ); + + if (type == FileType.External) { + if (new File(sdcard + filename).exists() == false) + throw new GdxRuntimeException("Couldn't open file '" + filename + "'"); else - return new AndroidFileHandle( null, sdcard + filename ); - } - else - { - if( new File( filename ).exists() == false ) - throw new GdxRuntimeException( "Couldn't open file '" + filename + "'" ); + return new AndroidFileHandle(null, sdcard + filename); + } else { + if (new File(filename).exists() == false) + throw new GdxRuntimeException("Couldn't open file '" + filename + "'"); else - return new AndroidFileHandle( null, filename ); + return new AndroidFileHandle(null, filename); } } /** * {@inheritDoc} */ - @Override - public String[] listDirectory(String directory, FileType type) - { - if( type == FileType.Internal ) - { - try - { - return assets.list( directory ); - } - catch( Exception ex ) - { - throw new GdxRuntimeException( "Couldn't open directory '" + directory + "'" ); + @Override public String[] listDirectory (String directory, FileType type) { + if (type == FileType.Internal) { + try { + return assets.list(directory); + } catch (Exception ex) { + throw new GdxRuntimeException("Couldn't open directory '" + directory + "'"); } } - - if( type == FileType.External ) - { - if( new File( sdcard + directory ).exists() == false ) - throw new GdxRuntimeException( "Couldn't open directory '" + directory + "'" ); + + if (type == FileType.External) { + if (new File(sdcard + directory).exists() == false) + throw new GdxRuntimeException("Couldn't open directory '" + directory + "'"); else - return new File( sdcard + directory ).list(); - } - else - { - if( new File( directory ).exists() == false ) - throw new GdxRuntimeException( "Couldn't open directory '" + directory + "'" ); + return new File(sdcard + directory).list(); + } else { + if (new File(directory).exists() == false) + throw new GdxRuntimeException("Couldn't open directory '" + directory + "'"); else - return new File( directory ).list(); + return new File(directory).list(); } } /** * {@inheritDoc} */ - @Override - public boolean makeDirectory(String directory, FileType type) - { - if( type == FileType.Internal ) - return false; - - if( type == FileType.External ) - return new File( sdcard + directory ).mkdirs(); + @Override public boolean makeDirectory (String directory, FileType type) { + if (type == FileType.Internal) return false; + + if (type == FileType.External) + return new File(sdcard + directory).mkdirs(); else - return new File( directory ).mkdirs(); + return new File(directory).mkdirs(); } /** * {@inheritDoc} */ - @Override - public InputStream readFile(String fileName, FileType type) - { - if( type == FileType.Internal ) - return readInternalFile( fileName ); - if( type == FileType.External ) - return readExternalFile( fileName ); + @Override public InputStream readFile (String fileName, FileType type) { + if (type == FileType.Internal) return readInternalFile(fileName); + if (type == FileType.External) + return readExternalFile(fileName); else - return readAbsolutFile( fileName ); + return readAbsolutFile(fileName); } /** * {@inheritDoc} */ - @Override - public OutputStream writeFile(String filename, FileType type) - { - if( type == FileType.Internal ) - return null; - if( type == FileType.External ) - return writeExternalFile( filename ); - else - { + @Override public OutputStream writeFile (String filename, FileType type) { + if (type == FileType.Internal) return null; + if (type == FileType.External) + return writeExternalFile(filename); + else { FileOutputStream out = null; - try - { - out = new FileOutputStream( filename ); - } - catch( FileNotFoundException ex ) - { - throw new GdxRuntimeException( "Couldn't open file '" + filename + "'", ex ); + try { + out = new FileOutputStream(filename); + } catch (FileNotFoundException ex) { + throw new GdxRuntimeException("Couldn't open file '" + filename + "'", ex); } return out; diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidFont.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidFont.java index 606a445fb..017fdf5a7 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidFont.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidFont.java @@ -1,126 +1,110 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; -import android.graphics.Rect; -import android.graphics.Typeface; import android.graphics.Paint.FontMetrics; import android.graphics.Paint.Style; +import android.graphics.Rect; +import android.graphics.Typeface; import com.badlogic.gdx.Graphics; import com.badlogic.gdx.graphics.Font; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.math.Rectangle; - - /** - * An implementation of {@link Font} for Android. + * An implementation of {@link Font} for Android. * * @author badlogicgames@gmail.com - * + * */ -final class AndroidFont extends Font -{ +final class AndroidFont extends Font { Typeface font; Paint paint; FontMetrics metrics; - AndroidFont(Graphics graphics, String fontName, int size, FontStyle style) - { - super( ); - font = Typeface.create( fontName, getFontStyle( style ) ); - paint = new Paint( ); + AndroidFont (Graphics graphics, String fontName, int size, FontStyle style) { + super(); + font = Typeface.create(fontName, getFontStyle(style)); + paint = new Paint(); paint.setTypeface(font); paint.setTextSize(size); paint.setAntiAlias(false); - metrics = paint.getFontMetrics(); + metrics = paint.getFontMetrics(); } - AndroidFont(Graphics graphics, AssetManager assets, String file, int size, FontStyle style) - { - super( ); - font = Typeface.createFromAsset( assets, file ); - paint = new Paint( ); + AndroidFont (Graphics graphics, AssetManager assets, String file, int size, FontStyle style) { + super(); + font = Typeface.createFromAsset(assets, file); + paint = new Paint(); paint.setTypeface(font); - paint.setTextSize(size); + paint.setTextSize(size); paint.setAntiAlias(false); metrics = paint.getFontMetrics(); } - private int getFontStyle( FontStyle style ) - { - if( style == FontStyle.Bold ) - return Typeface.BOLD; - if( style == FontStyle.BoldItalic ) - return Typeface.BOLD_ITALIC; - if( style == FontStyle.Italic ) - return Typeface.ITALIC; - if( style == FontStyle.Plain ) - return Typeface.NORMAL; - + private int getFontStyle (FontStyle style) { + if (style == FontStyle.Bold) return Typeface.BOLD; + if (style == FontStyle.BoldItalic) return Typeface.BOLD_ITALIC; + if (style == FontStyle.Italic) return Typeface.ITALIC; + if (style == FontStyle.Plain) return Typeface.NORMAL; + return Typeface.NORMAL; } - + /** * {@inheritDoc} */ - @Override - public int getGlyphAdvance(char character) { + @Override public int getGlyphAdvance (char character) { float[] width = new float[1]; - paint.getTextWidths( "" + character, width ); + paint.getTextWidths("" + character, width); return (int)(Math.ceil(width[0])); } /** * {@inheritDoc} */ - @Override - public Pixmap getGlyphBitmap(char character) { - Rect rect = new Rect(); - paint.getTextBounds( "" + character, 0, 1, rect ); - Bitmap bitmap = Bitmap.createBitmap( rect.width()==0?1:rect.width() + 5, getLineHeight(), AndroidPixmap.getInternalFormat(Font.pixelFormat) ); - Canvas g = new Canvas( bitmap ); + @Override public Pixmap getGlyphBitmap (char character) { + Rect rect = new Rect(); + paint.getTextBounds("" + character, 0, 1, rect); + Bitmap bitmap = Bitmap.createBitmap(rect.width() == 0 ? 1 : rect.width() + 5, getLineHeight(), + AndroidPixmap.getInternalFormat(Font.pixelFormat)); + Canvas g = new Canvas(bitmap); paint.setAntiAlias(true); paint.setColor(0x00000000); paint.setStyle(Style.FILL); - g.drawRect( new Rect( 0, 0, rect.width() + 5, getLineHeight()), paint); - paint.setColor(0xFFFFFFFF); - g.drawText( "" + character, 0, -metrics.ascent, paint ); - return new AndroidPixmap( bitmap ); + g.drawRect(new Rect(0, 0, rect.width() + 5, getLineHeight()), paint); + paint.setColor(0xFFFFFFFF); + g.drawText("" + character, 0, -metrics.ascent, paint); + return new AndroidPixmap(bitmap); } - /** * {@inheritDoc} */ - @Override - public int getLineGap() { + @Override public int getLineGap () { return (int)(Math.ceil(metrics.leading)); } /** * {@inheritDoc} */ - @Override - public int getLineHeight() { + @Override public int getLineHeight () { return (int)Math.ceil(Math.abs(metrics.ascent) + Math.abs(metrics.descent)); } @@ -128,9 +112,8 @@ final class AndroidFont extends Font * {@inheritDoc} */ Rect tmpRect = new Rect(); - @Override - public int getStringWidth(String text) - { + + @Override public int getStringWidth (String text) { paint.getTextBounds(text, 0, text.length(), tmpRect); return tmpRect.width(); } @@ -138,9 +121,8 @@ final class AndroidFont extends Font /** * {@inheritDoc} */ - @Override - public void getGlyphBounds(char character, Rectangle rect) { - paint.getTextBounds( "" + character, 0, 1, tmpRect ); + @Override public void getGlyphBounds (char character, Rectangle rect) { + paint.getTextBounds("" + character, 0, 1, tmpRect); rect.setWidth(tmpRect.width() + 5); rect.setHeight(getLineHeight()); } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGL10.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGL10.java index 037762f38..43918064b 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGL10.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGL10.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import java.nio.Buffer; @@ -24,771 +22,514 @@ import com.badlogic.gdx.graphics.GL10; /** * An implementation of the {@link GL10} interface for Android. * @author mzechner - * + * */ -class AndroidGL10 implements GL10 -{ +class AndroidGL10 implements GL10 { private final javax.microedition.khronos.opengles.GL10 gl; - - public AndroidGL10( javax.microedition.khronos.opengles.GL10 gl ) - { - this.gl = gl; + + public AndroidGL10 (javax.microedition.khronos.opengles.GL10 gl) { + this.gl = gl; } - @Override - public final void glActiveTexture(int texture) - { - gl.glActiveTexture( texture ); + @Override public final void glActiveTexture (int texture) { + gl.glActiveTexture(texture); } - @Override - public final void glAlphaFunc(int func, float ref) - { - gl.glAlphaFunc( func, ref ); + @Override public final void glAlphaFunc (int func, float ref) { + gl.glAlphaFunc(func, ref); } - @Override - public final void glAlphaFuncx(int func, int ref) { - gl.glAlphaFuncx( func, ref ); + @Override public final void glAlphaFuncx (int func, int ref) { + gl.glAlphaFuncx(func, ref); } - @Override - public final void glBindTexture(int target, int texture) - { - gl.glBindTexture( target, texture ); + @Override public final void glBindTexture (int target, int texture) { + gl.glBindTexture(target, texture); } - @Override - public final void glBlendFunc(int sfactor, int dfactor) - { - gl.glBlendFunc( sfactor, dfactor ); + @Override public final void glBlendFunc (int sfactor, int dfactor) { + gl.glBlendFunc(sfactor, dfactor); } - @Override - public final void glClear(int mask) - { - gl.glClear( mask ); + @Override public final void glClear (int mask) { + gl.glClear(mask); } - @Override - public final void glClearColor(float red, float green, float blue, float alpha) - { - gl.glClearColor( red, green, blue, alpha ); + @Override public final void glClearColor (float red, float green, float blue, float alpha) { + gl.glClearColor(red, green, blue, alpha); } - @Override - public final void glClearColorx(int red, int green, int blue, int alpha) - { - gl.glClearColorx( red, green, blue, alpha ); + @Override public final void glClearColorx (int red, int green, int blue, int alpha) { + gl.glClearColorx(red, green, blue, alpha); } - @Override - public final void glClearDepthf(float depth) - { - gl.glClearDepthf( depth ); + @Override public final void glClearDepthf (float depth) { + gl.glClearDepthf(depth); } - @Override - public final void glClearDepthx(int depth) - { - gl.glClearDepthx( depth ); + @Override public final void glClearDepthx (int depth) { + gl.glClearDepthx(depth); } - @Override - public final void glClearStencil(int s) - { - gl.glClearStencil( s ); + @Override public final void glClearStencil (int s) { + gl.glClearStencil(s); } - @Override - public final void glClientActiveTexture(int texture) - { - gl.glClientActiveTexture( texture ); + @Override public final void glClientActiveTexture (int texture) { + gl.glClientActiveTexture(texture); } - @Override - public final void glColor4f(float red, float green, float blue, float alpha) - { - gl.glColor4f( red, green, blue, alpha ); + @Override public final void glColor4f (float red, float green, float blue, float alpha) { + gl.glColor4f(red, green, blue, alpha); } - @Override - public final void glColor4x(int red, int green, int blue, int alpha) - { - gl.glColor4x( red, green, blue, alpha ); + @Override public final void glColor4x (int red, int green, int blue, int alpha) { + gl.glColor4x(red, green, blue, alpha); } - @Override - public final void glColorMask(boolean red, boolean green, boolean blue, boolean alpha) - { - gl.glColorMask( red, green, blue, alpha ); + @Override public final void glColorMask (boolean red, boolean green, boolean blue, boolean alpha) { + gl.glColorMask(red, green, blue, alpha); } - @Override - public final void glColorPointer(int size, int type, int stride, Buffer pointer) - { - gl.glColorPointer( size, type, stride, pointer ); + @Override public final void glColorPointer (int size, int type, int stride, Buffer pointer) { + gl.glColorPointer(size, type, stride, pointer); } - @Override - public final void glCompressedTexImage2D(int target, int level, - int internalformat, int width, int height, int border, - int imageSize, Buffer data) - { - gl.glCompressedTexImage2D( target, level, internalformat, width, height, border, imageSize, data ); + @Override public final void glCompressedTexImage2D (int target, int level, int internalformat, int width, int height, + int border, int imageSize, Buffer data) { + gl.glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); } - @Override - public final void glCompressedTexSubImage2D(int target, int level, int xoffset, - int yoffset, int width, int height, int format, int imageSize, - Buffer data) - { - gl.glCompressedTexSubImage2D( target, level, xoffset, yoffset, width, height, format, imageSize, data ); + @Override public final void glCompressedTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, + int format, int imageSize, Buffer data) { + gl.glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); } - @Override - public final void glCopyTexImage2D(int target, int level, int internalformat, - int x, int y, int width, int height, int border) - { - gl.glCopyTexImage2D( target, level, internalformat, x, y, width, height, border ); + @Override public final void glCopyTexImage2D (int target, int level, int internalformat, int x, int y, int width, int height, + int border) { + gl.glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); } - @Override - public final void glCopyTexSubImage2D(int target, int level, int xoffset, - int yoffset, int x, int y, int width, int height) - { - gl.glCopyTexSubImage2D( target, level, xoffset, yoffset, x, y, width, height ); + @Override public final void glCopyTexSubImage2D (int target, int level, int xoffset, int yoffset, int x, int y, int width, + int height) { + gl.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); } - @Override - public final void glCullFace(int mode) - { - gl.glCullFace( mode ); + @Override public final void glCullFace (int mode) { + gl.glCullFace(mode); } - @Override - public final void glDeleteTextures(int n, IntBuffer textures) - { - gl.glDeleteTextures( n, textures ); + @Override public final void glDeleteTextures (int n, IntBuffer textures) { + gl.glDeleteTextures(n, textures); } - @Override - public final void glDepthFunc(int func) - { - gl.glDepthFunc( func ); + @Override public final void glDepthFunc (int func) { + gl.glDepthFunc(func); } - @Override - public final void glDepthMask(boolean flag) - { - gl.glDepthMask( flag ); + @Override public final void glDepthMask (boolean flag) { + gl.glDepthMask(flag); } - @Override - public final void glDepthRangef(float zNear, float zFar) - { - gl.glDepthRangef( zNear, zFar ); + @Override public final void glDepthRangef (float zNear, float zFar) { + gl.glDepthRangef(zNear, zFar); } - @Override - public final void glDepthRangex(int zNear, int zFar) - { - gl.glDepthRangex( zNear, zFar ); + @Override public final void glDepthRangex (int zNear, int zFar) { + gl.glDepthRangex(zNear, zFar); } - @Override - public final void glDisable(int cap) - { - gl.glDisable( cap ); + @Override public final void glDisable (int cap) { + gl.glDisable(cap); } - @Override - public final void glDisableClientState(int array) - { - gl.glDisableClientState( array ); + @Override public final void glDisableClientState (int array) { + gl.glDisableClientState(array); } - @Override - public final void glDrawArrays(int mode, int first, int count) - { - gl.glDrawArrays( mode, first, count ); + @Override public final void glDrawArrays (int mode, int first, int count) { + gl.glDrawArrays(mode, first, count); } - @Override - public final void glDrawElements(int mode, int count, int type, Buffer indices) - { - gl.glDrawElements( mode, count, type, indices ); + @Override public final void glDrawElements (int mode, int count, int type, Buffer indices) { + gl.glDrawElements(mode, count, type, indices); } - @Override - public final void glEnable(int cap) - { - gl.glEnable( cap ); + @Override public final void glEnable (int cap) { + gl.glEnable(cap); } - @Override - public final void glEnableClientState(int array) - { - gl.glEnableClientState( array ); + @Override public final void glEnableClientState (int array) { + gl.glEnableClientState(array); } - @Override - public final void glFinish() - { + @Override public final void glFinish () { gl.glFinish(); } - @Override - public final void glFlush() - { + @Override public final void glFlush () { gl.glFlush(); } - @Override - public final void glFogf(int pname, float param) - { - gl.glFogf( pname, param ); + @Override public final void glFogf (int pname, float param) { + gl.glFogf(pname, param); } - @Override - public final void glFogfv(int pname, FloatBuffer params) - { - gl.glFogfv( pname, params ); + @Override public final void glFogfv (int pname, FloatBuffer params) { + gl.glFogfv(pname, params); } - @Override - public final void glFogx(int pname, int param) - { - gl.glFogx( pname, param ); + @Override public final void glFogx (int pname, int param) { + gl.glFogx(pname, param); } - @Override - public final void glFogxv(int pname, IntBuffer params) - { - gl.glFogxv( pname, params ); + @Override public final void glFogxv (int pname, IntBuffer params) { + gl.glFogxv(pname, params); } - @Override - public final void glFrontFace(int mode) - { - gl.glFrontFace( mode ); + @Override public final void glFrontFace (int mode) { + gl.glFrontFace(mode); } - @Override - public final void glFrustumf(float left, float right, float bottom, float top, - float zNear, float zFar) - { - gl.glFrustumf( left, right, bottom, top, zNear, zFar ); + @Override public final void glFrustumf (float left, float right, float bottom, float top, float zNear, float zFar) { + gl.glFrustumf(left, right, bottom, top, zNear, zFar); } - @Override - public final void glFrustumx(int left, int right, int bottom, int top, int zNear, - int zFar) - { - gl.glFrustumx( left, right, bottom, top, zNear, zFar ); + @Override public final void glFrustumx (int left, int right, int bottom, int top, int zNear, int zFar) { + gl.glFrustumx(left, right, bottom, top, zNear, zFar); } - @Override - public final void glGenTextures(int n, IntBuffer textures) - { - gl.glGenTextures( n, textures ); + @Override public final void glGenTextures (int n, IntBuffer textures) { + gl.glGenTextures(n, textures); } - @Override - public final int glGetError() - { + @Override public final int glGetError () { return gl.glGetError(); } - @Override - public final void glGetIntegerv(int pname, IntBuffer params) - { - gl.glGetIntegerv( pname, params ); + @Override public final void glGetIntegerv (int pname, IntBuffer params) { + gl.glGetIntegerv(pname, params); } - @Override - public final String glGetString(int name) - { - return gl.glGetString( name ); + @Override public final String glGetString (int name) { + return gl.glGetString(name); } - @Override - public final void glHint(int target, int mode) - { - gl.glHint( target, mode ); + @Override public final void glHint (int target, int mode) { + gl.glHint(target, mode); } - @Override - public final void glLightModelf(int pname, float param) - { - gl.glLightModelf( pname, param ); + @Override public final void glLightModelf (int pname, float param) { + gl.glLightModelf(pname, param); } - @Override - public final void glLightModelfv(int pname, FloatBuffer params) - { - gl.glLightModelfv( pname, params ); + @Override public final void glLightModelfv (int pname, FloatBuffer params) { + gl.glLightModelfv(pname, params); } - @Override - public final void glLightModelx(int pname, int param) - { - gl.glLightModelx( pname, param ); + @Override public final void glLightModelx (int pname, int param) { + gl.glLightModelx(pname, param); } - @Override - public final void glLightModelxv(int pname, IntBuffer params) - { - gl.glLightModelxv( pname, params ); + @Override public final void glLightModelxv (int pname, IntBuffer params) { + gl.glLightModelxv(pname, params); } - @Override - public final void glLightf(int light, int pname, float param) - { - gl.glLightf( light, pname, param ); + @Override public final void glLightf (int light, int pname, float param) { + gl.glLightf(light, pname, param); } - @Override - public final void glLightfv(int light, int pname, FloatBuffer params) - { - gl.glLightfv( light, pname, params ); + @Override public final void glLightfv (int light, int pname, FloatBuffer params) { + gl.glLightfv(light, pname, params); } - @Override - public final void glLightx(int light, int pname, int param) - { - gl.glLightx( light, pname, param ); + @Override public final void glLightx (int light, int pname, int param) { + gl.glLightx(light, pname, param); } - @Override - public final void glLightxv(int light, int pname, IntBuffer params) - { - gl.glLightxv( light, pname, params ); + @Override public final void glLightxv (int light, int pname, IntBuffer params) { + gl.glLightxv(light, pname, params); } - @Override - public final void glLineWidth(float width) - { - gl.glLineWidth( width ); + @Override public final void glLineWidth (float width) { + gl.glLineWidth(width); } - @Override - public final void glLineWidthx(int width) - { - gl.glLineWidthx( width ); + @Override public final void glLineWidthx (int width) { + gl.glLineWidthx(width); } - @Override - public final void glLoadIdentity() - { + @Override public final void glLoadIdentity () { gl.glLoadIdentity(); } - @Override - public final void glLoadMatrixf(FloatBuffer m) - { - gl.glLoadMatrixf( m ); + @Override public final void glLoadMatrixf (FloatBuffer m) { + gl.glLoadMatrixf(m); } - @Override - public final void glLoadMatrixx(IntBuffer m) - { - gl.glLoadMatrixx( m ); + @Override public final void glLoadMatrixx (IntBuffer m) { + gl.glLoadMatrixx(m); } - @Override - public final void glLogicOp(int opcode) - { - gl.glLogicOp( opcode ); + @Override public final void glLogicOp (int opcode) { + gl.glLogicOp(opcode); } - @Override - public final void glMaterialf(int face, int pname, float param) - { - gl.glMaterialf( face, pname, param ); + @Override public final void glMaterialf (int face, int pname, float param) { + gl.glMaterialf(face, pname, param); } - @Override - public final void glMaterialfv(int face, int pname, FloatBuffer params) - { - gl.glMaterialfv( face, pname, params ); + @Override public final void glMaterialfv (int face, int pname, FloatBuffer params) { + gl.glMaterialfv(face, pname, params); } - @Override - public final void glMaterialx(int face, int pname, int param) - { - gl.glMaterialx( face, pname, param ); + @Override public final void glMaterialx (int face, int pname, int param) { + gl.glMaterialx(face, pname, param); } - @Override - public final void glMaterialxv(int face, int pname, IntBuffer params) - { - gl.glMaterialxv( face, pname, params ); + @Override public final void glMaterialxv (int face, int pname, IntBuffer params) { + gl.glMaterialxv(face, pname, params); } - @Override - public final void glMatrixMode(int mode) - { - gl.glMatrixMode( mode ); + @Override public final void glMatrixMode (int mode) { + gl.glMatrixMode(mode); } - @Override - public final void glMultMatrixf(FloatBuffer m) - { - gl.glMultMatrixf( m ); + @Override public final void glMultMatrixf (FloatBuffer m) { + gl.glMultMatrixf(m); } - @Override - public final void glMultMatrixx(IntBuffer m) - { - gl.glMultMatrixx( m ); + @Override public final void glMultMatrixx (IntBuffer m) { + gl.glMultMatrixx(m); } - @Override - public final void glMultiTexCoord4f(int target, float s, float t, float r, float q) - { - gl.glMultiTexCoord4f( target, s, t, r, q ); + @Override public final void glMultiTexCoord4f (int target, float s, float t, float r, float q) { + gl.glMultiTexCoord4f(target, s, t, r, q); } - @Override - public final void glMultiTexCoord4x(int target, int s, int t, int r, int q) - { - gl.glMultiTexCoord4x( target, s, t, r, q ); + @Override public final void glMultiTexCoord4x (int target, int s, int t, int r, int q) { + gl.glMultiTexCoord4x(target, s, t, r, q); } - @Override - public final void glNormal3f(float nx, float ny, float nz) - { - gl.glNormal3f( nx, ny, nz ); + @Override public final void glNormal3f (float nx, float ny, float nz) { + gl.glNormal3f(nx, ny, nz); } - @Override - public final void glNormal3x(int nx, int ny, int nz) - { - gl.glNormal3x( nx, ny, nz ); + @Override public final void glNormal3x (int nx, int ny, int nz) { + gl.glNormal3x(nx, ny, nz); } - @Override - public final void glNormalPointer(int type, int stride, Buffer pointer) - { - gl.glNormalPointer( type, stride, pointer ); + @Override public final void glNormalPointer (int type, int stride, Buffer pointer) { + gl.glNormalPointer(type, stride, pointer); } - @Override - public final void glOrthof(float left, float right, float bottom, float top, - float zNear, float zFar) - { - gl.glOrthof( left, right, bottom, top, zNear, zFar ); + @Override public final void glOrthof (float left, float right, float bottom, float top, float zNear, float zFar) { + gl.glOrthof(left, right, bottom, top, zNear, zFar); } - @Override - public final void glOrthox(int left, int right, int bottom, int top, int zNear, - int zFar) - { - gl.glOrthox( left, right, bottom, top, zNear, zFar ); + @Override public final void glOrthox (int left, int right, int bottom, int top, int zNear, int zFar) { + gl.glOrthox(left, right, bottom, top, zNear, zFar); } - @Override - public final void glPixelStorei(int pname, int param) - { - gl.glPixelStorei( pname, param ); + @Override public final void glPixelStorei (int pname, int param) { + gl.glPixelStorei(pname, param); } - @Override - public final void glPointSize(float size) - { - gl.glPointSize( size ); + @Override public final void glPointSize (float size) { + gl.glPointSize(size); } - @Override - public final void glPointSizex(int size) - { - gl.glPointSizex( size ); + @Override public final void glPointSizex (int size) { + gl.glPointSizex(size); } - @Override - public final void glPolygonOffset(float factor, float units) - { - gl.glPolygonOffset( factor, units ); + @Override public final void glPolygonOffset (float factor, float units) { + gl.glPolygonOffset(factor, units); } - @Override - public final void glPolygonOffsetx(int factor, int units) - { - gl.glPolygonOffsetx( factor, units ); + @Override public final void glPolygonOffsetx (int factor, int units) { + gl.glPolygonOffsetx(factor, units); } - @Override - public final void glPopMatrix() - { + @Override public final void glPopMatrix () { gl.glPopMatrix(); } - @Override - public final void glPushMatrix() - { + @Override public final void glPushMatrix () { gl.glPushMatrix(); } - @Override - public final void glReadPixels(int x, int y, int width, int height, int format, - int type, Buffer pixels) - { - gl.glReadPixels( x, y, width, height, format, type, pixels ); + @Override public final void glReadPixels (int x, int y, int width, int height, int format, int type, Buffer pixels) { + gl.glReadPixels(x, y, width, height, format, type, pixels); } - @Override - public final void glRotatef(float angle, float x, float y, float z) - { - gl.glRotatef( angle, x, y, z ); + @Override public final void glRotatef (float angle, float x, float y, float z) { + gl.glRotatef(angle, x, y, z); } - @Override - public final void glRotatex(int angle, int x, int y, int z) - { - gl.glRotatex( angle, x, y, z ); + @Override public final void glRotatex (int angle, int x, int y, int z) { + gl.glRotatex(angle, x, y, z); } - @Override - public final void glSampleCoverage(float value, boolean invert) - { - gl.glSampleCoverage( value, invert ); + @Override public final void glSampleCoverage (float value, boolean invert) { + gl.glSampleCoverage(value, invert); } - @Override - public final void glSampleCoveragex(int value, boolean invert) - { - gl.glSampleCoveragex( value, invert ); + @Override public final void glSampleCoveragex (int value, boolean invert) { + gl.glSampleCoveragex(value, invert); } - @Override - public final void glScalef(float x, float y, float z) - { - gl.glScalef( x, y, z ); + @Override public final void glScalef (float x, float y, float z) { + gl.glScalef(x, y, z); } - @Override - public final void glScalex(int x, int y, int z) - { - gl.glScalex( x, y, z ); + @Override public final void glScalex (int x, int y, int z) { + gl.glScalex(x, y, z); } - @Override - public final void glScissor(int x, int y, int width, int height) - { - gl.glScissor( x, y, width, height ); + @Override public final void glScissor (int x, int y, int width, int height) { + gl.glScissor(x, y, width, height); } - @Override - public final void glShadeModel(int mode) - { + @Override public final void glShadeModel (int mode) { gl.glShadeModel(mode); } - @Override - public final void glStencilFunc(int func, int ref, int mask) - { - gl.glStencilFunc( func, ref, mask ); + @Override public final void glStencilFunc (int func, int ref, int mask) { + gl.glStencilFunc(func, ref, mask); } - @Override - public final void glStencilMask(int mask) - { - gl.glStencilMask( mask ); + @Override public final void glStencilMask (int mask) { + gl.glStencilMask(mask); } - @Override - public final void glStencilOp(int fail, int zfail, int zpass) - { - gl.glStencilOp( fail, zfail, zpass ); + @Override public final void glStencilOp (int fail, int zfail, int zpass) { + gl.glStencilOp(fail, zfail, zpass); } - @Override - public final void glTexCoordPointer(int size, int type, int stride, Buffer pointer) - { - gl.glTexCoordPointer( size, type, stride, pointer ); + @Override public final void glTexCoordPointer (int size, int type, int stride, Buffer pointer) { + gl.glTexCoordPointer(size, type, stride, pointer); } - @Override - public final void glTexEnvf(int target, int pname, float param) - { - gl.glTexEnvf( target, pname, param ); + @Override public final void glTexEnvf (int target, int pname, float param) { + gl.glTexEnvf(target, pname, param); } - @Override - public final void glTexEnvfv(int target, int pname, FloatBuffer params) - { - gl.glTexEnvfv( target, pname, params ); + @Override public final void glTexEnvfv (int target, int pname, FloatBuffer params) { + gl.glTexEnvfv(target, pname, params); } - @Override - public final void glTexEnvx(int target, int pname, int param) - { - gl.glTexEnvx( target, pname, param ); + @Override public final void glTexEnvx (int target, int pname, int param) { + gl.glTexEnvx(target, pname, param); } - @Override - public final void glTexEnvxv(int target, int pname, IntBuffer params) - { - gl.glTexEnvxv( target, pname, params ); + @Override public final void glTexEnvxv (int target, int pname, IntBuffer params) { + gl.glTexEnvxv(target, pname, params); } - @Override - public final void glTexImage2D(int target, int level, int internalformat, - int width, int height, int border, int format, int type, - Buffer pixels) - { - gl.glTexImage2D( target, level, internalformat, width, height, border, format, type, pixels ); + @Override public final void glTexImage2D (int target, int level, int internalformat, int width, int height, int border, + int format, int type, Buffer pixels) { + gl.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); } - @Override - public final void glTexParameterf(int target, int pname, float param) - { - gl.glTexParameterf( target, pname, param ); + @Override public final void glTexParameterf (int target, int pname, float param) { + gl.glTexParameterf(target, pname, param); } - @Override - public final void glTexParameterx(int target, int pname, int param) - { - gl.glTexParameterx( target, pname, param ); + @Override public final void glTexParameterx (int target, int pname, int param) { + gl.glTexParameterx(target, pname, param); } - @Override - public final void glTexSubImage2D(int target, int level, int xoffset, - int yoffset, int width, int height, int format, int type, - Buffer pixels) - { - gl.glTexSubImage2D( target, level, xoffset, yoffset, width, height, format, type, pixels ); + @Override public final void glTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, + int format, int type, Buffer pixels) { + gl.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); } - @Override - public final void glTranslatef(float x, float y, float z) - { - gl.glTranslatef( x, y, z ); + @Override public final void glTranslatef (float x, float y, float z) { + gl.glTranslatef(x, y, z); } - @Override - public final void glTranslatex(int x, int y, int z) - { - gl.glTranslatex( x, y, z ); + @Override public final void glTranslatex (int x, int y, int z) { + gl.glTranslatex(x, y, z); } - @Override - public final void glVertexPointer(int size, int type, int stride, Buffer pointer) - { - gl.glVertexPointer( size, type, stride, pointer ); + @Override public final void glVertexPointer (int size, int type, int stride, Buffer pointer) { + gl.glVertexPointer(size, type, stride, pointer); } - @Override - public final void glViewport(int x, int y, int width, int height) - { - gl.glViewport( x, y, width, height ); + @Override public final void glViewport (int x, int y, int width, int height) { + gl.glViewport(x, y, width, height); } - @Override - public final void glDeleteTextures(int n, int[] textures, int offset) - { - gl.glDeleteTextures( n, textures, offset ); + @Override public final void glDeleteTextures (int n, int[] textures, int offset) { + gl.glDeleteTextures(n, textures, offset); } - @Override - public final void glFogfv(int pname, float[] params, int offset) - { - gl.glFogfv( pname, params, offset ); + @Override public final void glFogfv (int pname, float[] params, int offset) { + gl.glFogfv(pname, params, offset); } - @Override - public final void glFogxv(int pname, int[] params, int offset) - { - gl.glFogxv( pname, params, offset ); + @Override public final void glFogxv (int pname, int[] params, int offset) { + gl.glFogxv(pname, params, offset); } - @Override - public final void glGenTextures(int n, int[] textures, int offset) - { - gl.glGenTextures( n, textures, offset ); + @Override public final void glGenTextures (int n, int[] textures, int offset) { + gl.glGenTextures(n, textures, offset); } - @Override - public final void glGetIntegerv(int pname, int[] params, int offset) - { - gl.glGetIntegerv( pname, params, offset ); + @Override public final void glGetIntegerv (int pname, int[] params, int offset) { + gl.glGetIntegerv(pname, params, offset); } - @Override - public final void glLightModelfv(int pname, float[] params, int offset) - { - gl.glLightModelfv( pname, params, offset ); + @Override public final void glLightModelfv (int pname, float[] params, int offset) { + gl.glLightModelfv(pname, params, offset); } - @Override - public final void glLightModelxv(int pname, int[] params, int offset) - { - gl.glLightModelxv( pname, params, offset ); + @Override public final void glLightModelxv (int pname, int[] params, int offset) { + gl.glLightModelxv(pname, params, offset); } - @Override - public final void glLightfv(int light, int pname, float[] params, int offset) - { - gl.glLightfv( light, pname, params, offset ); + @Override public final void glLightfv (int light, int pname, float[] params, int offset) { + gl.glLightfv(light, pname, params, offset); } - @Override - public final void glLightxv(int light, int pname, int[] params, int offset) - { - gl.glLightxv( light, pname, params, offset ); + @Override public final void glLightxv (int light, int pname, int[] params, int offset) { + gl.glLightxv(light, pname, params, offset); } - @Override - public final void glLoadMatrixf(float[] m, int offset) - { - gl.glLoadMatrixf( m, offset ); + @Override public final void glLoadMatrixf (float[] m, int offset) { + gl.glLoadMatrixf(m, offset); } - @Override - public final void glLoadMatrixx(int[] m, int offset) - { - gl.glLoadMatrixx( m, offset ); + @Override public final void glLoadMatrixx (int[] m, int offset) { + gl.glLoadMatrixx(m, offset); } - @Override - public final void glMaterialfv(int face, int pname, float[] params, int offset) - { - gl.glMaterialfv( face, pname, params, offset ); + @Override public final void glMaterialfv (int face, int pname, float[] params, int offset) { + gl.glMaterialfv(face, pname, params, offset); } - @Override - public final void glMaterialxv(int face, int pname, int[] params, int offset) - { - gl.glMaterialxv( face, pname, params, offset ); + @Override public final void glMaterialxv (int face, int pname, int[] params, int offset) { + gl.glMaterialxv(face, pname, params, offset); } - @Override - public final void glMultMatrixf(float[] m, int offset) - { - gl.glMultMatrixf( m, offset ); + @Override public final void glMultMatrixf (float[] m, int offset) { + gl.glMultMatrixf(m, offset); } - @Override - public final void glMultMatrixx(int[] m, int offset) - { - gl.glMultMatrixx( m, offset ); + @Override public final void glMultMatrixx (int[] m, int offset) { + gl.glMultMatrixx(m, offset); } - @Override - public final void glTexEnvfv(int target, int pname, float[] params, int offset) - { - gl.glTexEnvfv( target, pname, params, offset ); + @Override public final void glTexEnvfv (int target, int pname, float[] params, int offset) { + gl.glTexEnvfv(target, pname, params, offset); } - @Override - public final void glTexEnvxv(int target, int pname, int[] params, int offset) - { - gl.glTexEnvxv( target, pname, params, offset ); + @Override public final void glTexEnvxv (int target, int pname, int[] params, int offset) { + gl.glTexEnvxv(target, pname, params, offset); } - @Override - public void glPolygonMode(int face, int mode) { -// throw new UnsupportedOperationException( "not available in OpenGL ES" ); - } + @Override public void glPolygonMode (int face, int mode) { +// throw new UnsupportedOperationException( "not available in OpenGL ES" ); + } } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGL11.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGL11.java index 9d0cbdd00..2fe9db67b 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGL11.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGL11.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import java.nio.Buffer; @@ -27,428 +25,285 @@ import com.badlogic.gdx.graphics.GL11; * An implementation of the {@link GL11} interface for Android * * @author mzechner - * + * */ -final class AndroidGL11 extends AndroidGL10 implements GL11 -{ +final class AndroidGL11 extends AndroidGL10 implements GL11 { private final javax.microedition.khronos.opengles.GL11 gl; - - public AndroidGL11(GL10 gl) - { - super(gl); - this.gl = (javax.microedition.khronos.opengles.GL11)gl; + + public AndroidGL11 (GL10 gl) { + super(gl); + this.gl = (javax.microedition.khronos.opengles.GL11)gl; } - @Override - public void glBindBuffer(int target, int buffer) - { - gl.glBindBuffer( target, buffer ); + @Override public void glBindBuffer (int target, int buffer) { + gl.glBindBuffer(target, buffer); } - @Override - public void glBufferData(int target, int size, Buffer data, int usage) - { - gl.glBufferData( target, size, data, usage ); + @Override public void glBufferData (int target, int size, Buffer data, int usage) { + gl.glBufferData(target, size, data, usage); } - @Override - public void glBufferSubData(int target, int offset, int size, Buffer data) - { - gl.glBufferSubData( target, offset, size, data ); + @Override public void glBufferSubData (int target, int offset, int size, Buffer data) { + gl.glBufferSubData(target, offset, size, data); } - @Override - public void glClipPlanef(int plane, FloatBuffer equation) - { - gl.glClipPlanef( plane, equation ); + @Override public void glClipPlanef (int plane, FloatBuffer equation) { + gl.glClipPlanef(plane, equation); } - @Override - public void glClipPlanex(int plane, IntBuffer equation) - { - gl.glClipPlanex( plane, equation ); + @Override public void glClipPlanex (int plane, IntBuffer equation) { + gl.glClipPlanex(plane, equation); } - @Override - public void glColor4ub(byte red, byte green, byte blue, byte alpha) - { - gl.glColor4ub( red, green, blue, alpha ); + @Override public void glColor4ub (byte red, byte green, byte blue, byte alpha) { + gl.glColor4ub(red, green, blue, alpha); } - @Override - public void glDeleteBuffers(int n, IntBuffer buffers) - { - gl.glDeleteBuffers( n, buffers ); + @Override public void glDeleteBuffers (int n, IntBuffer buffers) { + gl.glDeleteBuffers(n, buffers); } - @Override - public void glGenBuffers(int n, IntBuffer buffers) - { - gl.glGenBuffers( n, buffers ); + @Override public void glGenBuffers (int n, IntBuffer buffers) { + gl.glGenBuffers(n, buffers); } - @Override - public void glGetBooleanv(int pname, IntBuffer params) - { - gl.glGetBooleanv( pname, params ); + @Override public void glGetBooleanv (int pname, IntBuffer params) { + gl.glGetBooleanv(pname, params); } - @Override - public void glGetBufferParameteriv(int target, int pname, IntBuffer params) - { - gl.glGetBufferParameteriv( target, pname, params ); + @Override public void glGetBufferParameteriv (int target, int pname, IntBuffer params) { + gl.glGetBufferParameteriv(target, pname, params); } - @Override - public void glGetClipPlanef(int pname, FloatBuffer eqn) - { - gl.glGetClipPlanef( pname, eqn ); + @Override public void glGetClipPlanef (int pname, FloatBuffer eqn) { + gl.glGetClipPlanef(pname, eqn); } - @Override - public void glGetClipPlanex(int pname, IntBuffer eqn) - { - gl.glGetClipPlanex( pname, eqn ); + @Override public void glGetClipPlanex (int pname, IntBuffer eqn) { + gl.glGetClipPlanex(pname, eqn); } - @Override - public void glGetFixedv(int pname, IntBuffer params) - { - gl.glGetFixedv( pname, params ); + @Override public void glGetFixedv (int pname, IntBuffer params) { + gl.glGetFixedv(pname, params); } - @Override - public void glGetFloatv(int pname, FloatBuffer params) - { - gl.glGetFloatv( pname, params ); + @Override public void glGetFloatv (int pname, FloatBuffer params) { + gl.glGetFloatv(pname, params); } - @Override - public void glGetLightfv(int light, int pname, FloatBuffer params) - { - gl.glGetLightfv( light, pname, params ); + @Override public void glGetLightfv (int light, int pname, FloatBuffer params) { + gl.glGetLightfv(light, pname, params); } - @Override - public void glGetLightxv(int light, int pname, IntBuffer params) - { - gl.glGetLightxv( light, pname, params ); + @Override public void glGetLightxv (int light, int pname, IntBuffer params) { + gl.glGetLightxv(light, pname, params); } - @Override - public void glGetMaterialfv(int face, int pname, FloatBuffer params) - { - gl.glGetMaterialfv( face, pname, params ); + @Override public void glGetMaterialfv (int face, int pname, FloatBuffer params) { + gl.glGetMaterialfv(face, pname, params); } - @Override - public void glGetMaterialxv(int face, int pname, IntBuffer params) - { - gl.glGetMaterialxv( face, pname, params ); + @Override public void glGetMaterialxv (int face, int pname, IntBuffer params) { + gl.glGetMaterialxv(face, pname, params); } - @Override - public void glGetPointerv(int pname, Buffer[] params) - { - gl.glGetPointerv( pname, params ); + @Override public void glGetPointerv (int pname, Buffer[] params) { + gl.glGetPointerv(pname, params); } - @Override - public void glGetTexEnviv(int env, int pname, IntBuffer params) - { - gl.glGetTexEnviv( env, pname, params ); + @Override public void glGetTexEnviv (int env, int pname, IntBuffer params) { + gl.glGetTexEnviv(env, pname, params); } - @Override - public void glGetTexEnvxv(int env, int pname, IntBuffer params) - { - gl.glGetTexEnvxv( env, pname, params ); + @Override public void glGetTexEnvxv (int env, int pname, IntBuffer params) { + gl.glGetTexEnvxv(env, pname, params); } - @Override - public void glGetTexParameterfv(int target, int pname, FloatBuffer params) - { - gl.glGetTexParameterfv( target, pname, params ); + @Override public void glGetTexParameterfv (int target, int pname, FloatBuffer params) { + gl.glGetTexParameterfv(target, pname, params); } - @Override - public void glGetTexParameteriv(int target, int pname, IntBuffer params) - { - gl.glGetTexParameteriv( target, pname, params ); + @Override public void glGetTexParameteriv (int target, int pname, IntBuffer params) { + gl.glGetTexParameteriv(target, pname, params); } - @Override - public void glGetTexParameterxv(int target, int pname, IntBuffer params) - { - gl.glGetTexParameterxv( target, pname, params ); + @Override public void glGetTexParameterxv (int target, int pname, IntBuffer params) { + gl.glGetTexParameterxv(target, pname, params); } - @Override - public boolean glIsBuffer(int buffer) - { - return gl.glIsBuffer( buffer ); + @Override public boolean glIsBuffer (int buffer) { + return gl.glIsBuffer(buffer); } - @Override - public boolean glIsEnabled(int cap) - { - return gl.glIsEnabled( cap ); + @Override public boolean glIsEnabled (int cap) { + return gl.glIsEnabled(cap); } - @Override - public boolean glIsTexture(int texture) - { - return gl.glIsTexture( texture ); + @Override public boolean glIsTexture (int texture) { + return gl.glIsTexture(texture); } - @Override - public void glPointParameterf(int pname, float param) - { - gl.glPointParameterf( pname, param ); + @Override public void glPointParameterf (int pname, float param) { + gl.glPointParameterf(pname, param); } - @Override - public void glPointParameterfv(int pname, FloatBuffer params) - { - gl.glPointParameterfv( pname, params ); + @Override public void glPointParameterfv (int pname, FloatBuffer params) { + gl.glPointParameterfv(pname, params); } - @Override - public void glPointParameterx(int pname, int param) - { - gl.glPointParameterx( pname, param ); + @Override public void glPointParameterx (int pname, int param) { + gl.glPointParameterx(pname, param); } - @Override - public void glPointParameterxv(int pname, IntBuffer params) - { - gl.glPointParameterxv( pname, params ); + @Override public void glPointParameterxv (int pname, IntBuffer params) { + gl.glPointParameterxv(pname, params); } - @Override - public void glPointSizePointerOES(int type, int stride, Buffer pointer) - { - gl.glPointSizePointerOES( type, stride, pointer ); + @Override public void glPointSizePointerOES (int type, int stride, Buffer pointer) { + gl.glPointSizePointerOES(type, stride, pointer); } - @Override - public void glTexEnvi(int target, int pname, int param) - { - gl.glTexEnvi( target, pname, param ); + @Override public void glTexEnvi (int target, int pname, int param) { + gl.glTexEnvi(target, pname, param); } - @Override - public void glTexEnviv(int target, int pname, IntBuffer params) - { - gl.glTexEnviv( target, pname, params ); + @Override public void glTexEnviv (int target, int pname, IntBuffer params) { + gl.glTexEnviv(target, pname, params); } - @Override - public void glTexParameterfv(int target, int pname, FloatBuffer params) - { - gl.glTexParameterfv( target, pname, params ); + @Override public void glTexParameterfv (int target, int pname, FloatBuffer params) { + gl.glTexParameterfv(target, pname, params); } - @Override - public void glTexParameteri(int target, int pname, int param) - { - gl.glTexParameteri( target, pname, param ); + @Override public void glTexParameteri (int target, int pname, int param) { + gl.glTexParameteri(target, pname, param); } - @Override - public void glTexParameteriv(int target, int pname, IntBuffer params) - { - gl.glTexParameteriv( target, pname, params ); + @Override public void glTexParameteriv (int target, int pname, IntBuffer params) { + gl.glTexParameteriv(target, pname, params); } - @Override - public void glTexParameterxv(int target, int pname, IntBuffer params) - { - gl.glTexParameterxv( target, pname, params ); + @Override public void glTexParameterxv (int target, int pname, IntBuffer params) { + gl.glTexParameterxv(target, pname, params); } - @Override - public void glClipPlanef(int plane, float[] equation, int offset) - { - gl.glClipPlanef( plane, equation, offset ); + @Override public void glClipPlanef (int plane, float[] equation, int offset) { + gl.glClipPlanef(plane, equation, offset); } - @Override - public void glClipPlanex(int plane, int[] equation, int offset) - { - gl.glClipPlanex( plane, equation, offset ); + @Override public void glClipPlanex (int plane, int[] equation, int offset) { + gl.glClipPlanex(plane, equation, offset); } - @Override - public void glDeleteBuffers(int n, int[] buffers, int offset) - { - gl.glDeleteBuffers( n, buffers, offset ); + @Override public void glDeleteBuffers (int n, int[] buffers, int offset) { + gl.glDeleteBuffers(n, buffers, offset); } - @Override - public void glGenBuffers(int n, int[] buffers, int offset) - { - gl.glGenBuffers( n, buffers, offset ); + @Override public void glGenBuffers (int n, int[] buffers, int offset) { + gl.glGenBuffers(n, buffers, offset); } - @Override - public void glGetBooleanv(int pname, boolean[] params, int offset) - { - gl.glGetBooleanv( pname, params, offset ); + @Override public void glGetBooleanv (int pname, boolean[] params, int offset) { + gl.glGetBooleanv(pname, params, offset); } - @Override - public void glGetBufferParameteriv(int target, int pname, int[] params, - int offset) - { - gl.glGetBufferParameteriv( target, pname, params, offset ); + @Override public void glGetBufferParameteriv (int target, int pname, int[] params, int offset) { + gl.glGetBufferParameteriv(target, pname, params, offset); } - @Override - public void glGetClipPlanef(int pname, float[] eqn, int offset) - { - gl.glGetClipPlanef( pname, eqn, offset ); + @Override public void glGetClipPlanef (int pname, float[] eqn, int offset) { + gl.glGetClipPlanef(pname, eqn, offset); } - @Override - public void glGetClipPlanex(int pname, int[] eqn, int offset) - { - gl.glGetClipPlanex( pname, eqn, offset ); + @Override public void glGetClipPlanex (int pname, int[] eqn, int offset) { + gl.glGetClipPlanex(pname, eqn, offset); } - @Override - public void glGetFixedv(int pname, int[] params, int offset) - { - gl.glGetFixedv( pname, params, offset ); + @Override public void glGetFixedv (int pname, int[] params, int offset) { + gl.glGetFixedv(pname, params, offset); } - @Override - public void glGetFloatv(int pname, float[] params, int offset) - { - gl.glGetFloatv( pname, params, offset ); + @Override public void glGetFloatv (int pname, float[] params, int offset) { + gl.glGetFloatv(pname, params, offset); } - @Override - public void glGetLightfv(int light, int pname, float[] params, int offset) - { - gl.glGetLightfv( light, pname, params, offset ); + @Override public void glGetLightfv (int light, int pname, float[] params, int offset) { + gl.glGetLightfv(light, pname, params, offset); } - @Override - public void glGetLightxv(int light, int pname, int[] params, int offset) - { - gl.glGetLightxv( light, pname, params, offset ); + @Override public void glGetLightxv (int light, int pname, int[] params, int offset) { + gl.glGetLightxv(light, pname, params, offset); } - @Override - public void glGetMaterialfv(int face, int pname, float[] params, int offset) - { - gl.glGetMaterialfv( face, pname, params, offset ); + @Override public void glGetMaterialfv (int face, int pname, float[] params, int offset) { + gl.glGetMaterialfv(face, pname, params, offset); } - @Override - public void glGetMaterialxv(int face, int pname, int[] params, int offset) - { - gl.glGetMaterialxv( face, pname, params, offset ); + @Override public void glGetMaterialxv (int face, int pname, int[] params, int offset) { + gl.glGetMaterialxv(face, pname, params, offset); } - @Override - public void glGetTexEnviv(int env, int pname, int[] params, int offset) - { - gl.glGetTexEnviv( env, pname, params, offset ); + @Override public void glGetTexEnviv (int env, int pname, int[] params, int offset) { + gl.glGetTexEnviv(env, pname, params, offset); } - @Override - public void glGetTexEnvxv(int env, int pname, int[] params, int offset) - { - gl.glGetTexEnvxv( env, pname, params, offset ); + @Override public void glGetTexEnvxv (int env, int pname, int[] params, int offset) { + gl.glGetTexEnvxv(env, pname, params, offset); } - @Override - public void glGetTexParameterfv(int target, int pname, float[] params, - int offset) - { - gl.glGetTexParameterfv( target, pname, params, offset ); + @Override public void glGetTexParameterfv (int target, int pname, float[] params, int offset) { + gl.glGetTexParameterfv(target, pname, params, offset); } - @Override - public void glGetTexParameteriv(int target, int pname, int[] params, - int offset) - { - gl.glGetTexParameteriv( target, pname, params, offset ); + @Override public void glGetTexParameteriv (int target, int pname, int[] params, int offset) { + gl.glGetTexParameteriv(target, pname, params, offset); } - @Override - public void glGetTexParameterxv(int target, int pname, int[] params, - int offset) - { - gl.glGetTexParameterxv( target, pname, params, offset ); + @Override public void glGetTexParameterxv (int target, int pname, int[] params, int offset) { + gl.glGetTexParameterxv(target, pname, params, offset); } - @Override - public void glPointParameterfv(int pname, float[] params, int offset) - { - gl.glPointParameterfv( pname, params, offset ); + @Override public void glPointParameterfv (int pname, float[] params, int offset) { + gl.glPointParameterfv(pname, params, offset); } - @Override - public void glPointParameterxv(int pname, int[] params, int offset) - { - gl.glPointParameterxv( pname, params, offset ); + @Override public void glPointParameterxv (int pname, int[] params, int offset) { + gl.glPointParameterxv(pname, params, offset); } - @Override - public void glTexEnviv(int target, int pname, int[] params, int offset) - { - gl.glTexEnviv( target, pname, params, offset ); + @Override public void glTexEnviv (int target, int pname, int[] params, int offset) { + gl.glTexEnviv(target, pname, params, offset); } - @Override - public void glTexParameterfv(int target, int pname, float[] params, - int offset) - { - gl.glTexParameterfv( target, pname, params, offset ); + @Override public void glTexParameterfv (int target, int pname, float[] params, int offset) { + gl.glTexParameterfv(target, pname, params, offset); } - @Override - public void glTexParameteriv(int target, int pname, int[] params, int offset) - { - gl.glTexParameteriv( target, pname, params, offset ); + @Override public void glTexParameteriv (int target, int pname, int[] params, int offset) { + gl.glTexParameteriv(target, pname, params, offset); } - @Override - public void glTexParameterxv(int target, int pname, int[] params, int offset) - { - gl.glTexParameterxv( target, pname, params, offset ); + @Override public void glTexParameterxv (int target, int pname, int[] params, int offset) { + gl.glTexParameterxv(target, pname, params, offset); } - @Override - public void glColorPointer(int size, int type, int stride, int pointer) - { - gl.glColorPointer( size, type, stride, pointer ); + @Override public void glColorPointer (int size, int type, int stride, int pointer) { + gl.glColorPointer(size, type, stride, pointer); } - @Override - public void glNormalPointer( int type, int stride, int pointer) - { - gl.glNormalPointer( type, stride, pointer ); + @Override public void glNormalPointer (int type, int stride, int pointer) { + gl.glNormalPointer(type, stride, pointer); } - @Override - public void glTexCoordPointer(int size, int type, int stride, int pointer) - { - gl.glTexCoordPointer( size, type, stride, pointer ); + @Override public void glTexCoordPointer (int size, int type, int stride, int pointer) { + gl.glTexCoordPointer(size, type, stride, pointer); } - @Override - public void glVertexPointer(int size, int type, int stride, int pointer) - { - gl.glVertexPointer( size, type, stride, pointer ); + @Override public void glVertexPointer (int size, int type, int stride, int pointer) { + gl.glVertexPointer(size, type, stride, pointer); } - - @Override - public void glDrawElements( int mode, int count, int type, int indices ) - { - gl.glDrawElements( mode, count, type, indices ); + + @Override public void glDrawElements (int mode, int count, int type, int indices) { + gl.glDrawElements(mode, count, type, indices); } } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGL20.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGL20.java index 3820825b0..4c2b963b2 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGL20.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGL20.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import java.nio.Buffer; @@ -21,302 +19,303 @@ import java.nio.IntBuffer; import com.badlogic.gdx.graphics.GL20; +public class AndroidGL20 implements GL20 { + static { + System.loadLibrary("androidgl20"); + init(); + } + + private static native void init (); + + public native void glActiveTexture (int texture); + + public native void glAttachShader (int program, int shader); -public class AndroidGL20 implements GL20 -{ - static - { - System.loadLibrary( "androidgl20" ); - init( ); - } - - private static native void init( ); - - public native void glActiveTexture ( int texture ); + public native void glBindAttribLocation (int program, int index, String name); - public native void glAttachShader ( int program, int shader ); + public native void glBindBuffer (int target, int buffer); - public native void glBindAttribLocation ( int program, int index, String name ); + public native void glBindFramebuffer (int target, int framebuffer); - public native void glBindBuffer ( int target, int buffer ); + public native void glBindRenderbuffer (int target, int renderbuffer); - public native void glBindFramebuffer ( int target, int framebuffer ); + public native void glBindTexture (int target, int texture); - public native void glBindRenderbuffer ( int target, int renderbuffer ); + public native void glBlendColor (float red, float green, float blue, float alpha); - public native void glBindTexture ( int target, int texture ); + public native void glBlendEquation (int mode); - public native void glBlendColor ( float red, float green, float blue, float alpha ); + public native void glBlendEquationSeparate (int modeRGB, int modeAlpha); - public native void glBlendEquation ( int mode ); + public native void glBlendFunc (int sfactor, int dfactor); - public native void glBlendEquationSeparate ( int modeRGB, int modeAlpha ); + public native void glBlendFuncSeparate (int srcRGB, int dstRGB, int srcAlpha, int dstAlpha); - public native void glBlendFunc ( int sfactor, int dfactor ); + public native void glBufferData (int target, int size, Buffer data, int usage); - public native void glBlendFuncSeparate ( int srcRGB, int dstRGB, int srcAlpha, int dstAlpha ); + public native void glBufferSubData (int target, int offset, int size, Buffer data); - public native void glBufferData ( int target, int size, Buffer data, int usage ); + public native int glCheckFramebufferStatus (int target); - public native void glBufferSubData ( int target, int offset, int size, Buffer data ); + public native void glClear (int mask); - public native int glCheckFramebufferStatus ( int target ); + public native void glClearColor (float red, float green, float blue, float alpha); - public native void glClear ( int mask ); + public native void glClearDepthf (float depth); - public native void glClearColor ( float red, float green, float blue, float alpha ); + public native void glClearStencil (int s); - public native void glClearDepthf ( float depth ); + public native void glColorMask (boolean red, boolean green, boolean blue, boolean alpha); - public native void glClearStencil ( int s ); + public native void glCompileShader (int shader); - public native void glColorMask ( boolean red, boolean green, boolean blue, boolean alpha ); + public native void glCompressedTexImage2D (int target, int level, int internalformat, int width, int height, int border, + int imageSize, Buffer data); - public native void glCompileShader ( int shader ); + public native void glCompressedTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, + int format, int imageSize, Buffer data); - public native void glCompressedTexImage2D ( int target, int level, int internalformat, int width, int height, int border, int imageSize, Buffer data ); + public native void glCopyTexImage2D (int target, int level, int internalformat, int x, int y, int width, int height, int border); - public native void glCompressedTexSubImage2D ( int target, int level, int xoffset, int yoffset, int width, int height, int format, int imageSize, Buffer data ); + public native void glCopyTexSubImage2D (int target, int level, int xoffset, int yoffset, int x, int y, int width, int height); - public native void glCopyTexImage2D ( int target, int level, int internalformat, int x, int y, int width, int height, int border ); + public native int glCreateProgram (); - public native void glCopyTexSubImage2D ( int target, int level, int xoffset, int yoffset, int x, int y, int width, int height ); + public native int glCreateShader (int type); - public native int glCreateProgram ( ); + public native void glCullFace (int mode); - public native int glCreateShader ( int type ); + public native void glDeleteBuffers (int n, IntBuffer buffers); - public native void glCullFace ( int mode ); + public native void glDeleteFramebuffers (int n, IntBuffer framebuffers); - public native void glDeleteBuffers ( int n, IntBuffer buffers ); + public native void glDeleteProgram (int program); - public native void glDeleteFramebuffers ( int n, IntBuffer framebuffers ); + public native void glDeleteRenderbuffers (int n, IntBuffer renderbuffers); - public native void glDeleteProgram ( int program ); + public native void glDeleteShader (int shader); - public native void glDeleteRenderbuffers ( int n, IntBuffer renderbuffers ); + public native void glDeleteTextures (int n, IntBuffer textures); - public native void glDeleteShader ( int shader ); + public native void glDepthFunc (int func); - public native void glDeleteTextures ( int n, IntBuffer textures ); + public native void glDepthMask (boolean flag); - public native void glDepthFunc ( int func ); + public native void glDepthRangef (float zNear, float zFar); - public native void glDepthMask ( boolean flag ); + public native void glDetachShader (int program, int shader); - public native void glDepthRangef ( float zNear, float zFar ); + public native void glDisable (int cap); - public native void glDetachShader ( int program, int shader ); + public native void glDisableVertexAttribArray (int index); - public native void glDisable ( int cap ); + public native void glDrawArrays (int mode, int first, int count); - public native void glDisableVertexAttribArray ( int index ); + public native void glDrawElements (int mode, int count, int type, Buffer indices); - public native void glDrawArrays ( int mode, int first, int count ); + public native void glDrawElements (int mode, int count, int type, int indices); - public native void glDrawElements ( int mode, int count, int type, Buffer indices ); - - public native void glDrawElements ( int mode, int count, int type, int indices ); + public native void glEnable (int cap); - public native void glEnable ( int cap ); + public native void glEnableVertexAttribArray (int index); - public native void glEnableVertexAttribArray ( int index ); + public native void glFinish (); - public native void glFinish ( ); + public native void glFlush (); - public native void glFlush ( ); + public native void glFramebufferRenderbuffer (int target, int attachment, int renderbuffertarget, int renderbuffer); - public native void glFramebufferRenderbuffer ( int target, int attachment, int renderbuffertarget, int renderbuffer ); + public native void glFramebufferTexture2D (int target, int attachment, int textarget, int texture, int level); - public native void glFramebufferTexture2D ( int target, int attachment, int textarget, int texture, int level ); + public native void glFrontFace (int mode); - public native void glFrontFace ( int mode ); + public native void glGenBuffers (int n, IntBuffer buffers); - public native void glGenBuffers ( int n, IntBuffer buffers ); + public native void glGenerateMipmap (int target); - public native void glGenerateMipmap ( int target ); + public native void glGenFramebuffers (int n, IntBuffer framebuffers); - public native void glGenFramebuffers ( int n, IntBuffer framebuffers ); + public native void glGenRenderbuffers (int n, IntBuffer renderbuffers); - public native void glGenRenderbuffers ( int n, IntBuffer renderbuffers ); + public native void glGenTextures (int n, IntBuffer textures); - public native void glGenTextures ( int n, IntBuffer textures ); + public native String glGetActiveAttrib (int program, int index, IntBuffer size, Buffer type); - public native String glGetActiveAttrib ( int program, int index, IntBuffer size, Buffer type ); + public native String glGetActiveUniform (int program, int index, IntBuffer size, Buffer type); - public native String glGetActiveUniform ( int program, int index, IntBuffer size, Buffer type ); + public native void glGetAttachedShaders (int program, int maxcount, Buffer count, IntBuffer shaders); - public native void glGetAttachedShaders ( int program, int maxcount, Buffer count, IntBuffer shaders ); + public native int glGetAttribLocation (int program, String name); - public native int glGetAttribLocation ( int program, String name ); + public native void glGetBooleanv (int pname, Buffer params); - public native void glGetBooleanv ( int pname, Buffer params ); + public native void glGetBufferParameteriv (int target, int pname, IntBuffer params); - public native void glGetBufferParameteriv ( int target, int pname, IntBuffer params ); + public native int glGetError (); - public native int glGetError ( ); + public native void glGetFloatv (int pname, FloatBuffer params); - public native void glGetFloatv ( int pname, FloatBuffer params ); + public native void glGetFramebufferAttachmentParameteriv (int target, int attachment, int pname, IntBuffer params); - public native void glGetFramebufferAttachmentParameteriv ( int target, int attachment, int pname, IntBuffer params ); + public native void glGetIntegerv (int pname, IntBuffer params); - public native void glGetIntegerv ( int pname, IntBuffer params ); + public native void glGetProgramiv (int program, int pname, IntBuffer params); - public native void glGetProgramiv ( int program, int pname, IntBuffer params ); + public native String glGetProgramInfoLog (int program); - public native String glGetProgramInfoLog ( int program ); + public native void glGetRenderbufferParameteriv (int target, int pname, IntBuffer params); - public native void glGetRenderbufferParameteriv ( int target, int pname, IntBuffer params ); + public native void glGetShaderiv (int shader, int pname, IntBuffer params); - public native void glGetShaderiv ( int shader, int pname, IntBuffer params ); + public native String glGetShaderInfoLog (int shader); - public native String glGetShaderInfoLog ( int shader ); + public native void glGetShaderPrecisionFormat (int shadertype, int precisiontype, IntBuffer range, IntBuffer precision); - public native void glGetShaderPrecisionFormat ( int shadertype, int precisiontype, IntBuffer range, IntBuffer precision ); + public native void glGetShaderSource (int shader, int bufsize, Buffer length, String source); - public native void glGetShaderSource ( int shader, int bufsize, Buffer length, String source ); + public native String glGetString (int name); - public native String glGetString ( int name ); + public native void glGetTexParameterfv (int target, int pname, FloatBuffer params); - public native void glGetTexParameterfv ( int target, int pname, FloatBuffer params ); + public native void glGetTexParameteriv (int target, int pname, IntBuffer params); - public native void glGetTexParameteriv ( int target, int pname, IntBuffer params ); + public native void glGetUniformfv (int program, int location, FloatBuffer params); - public native void glGetUniformfv ( int program, int location, FloatBuffer params ); + public native void glGetUniformiv (int program, int location, IntBuffer params); - public native void glGetUniformiv ( int program, int location, IntBuffer params ); + public native int glGetUniformLocation (int program, String name); - public native int glGetUniformLocation ( int program, String name ); + public native void glGetVertexAttribfv (int index, int pname, FloatBuffer params); - public native void glGetVertexAttribfv ( int index, int pname, FloatBuffer params ); + public native void glGetVertexAttribiv (int index, int pname, IntBuffer params); - public native void glGetVertexAttribiv ( int index, int pname, IntBuffer params ); + public native void glGetVertexAttribPointerv (int index, int pname, Buffer pointer); - public native void glGetVertexAttribPointerv ( int index, int pname, Buffer pointer ); + public native void glHint (int target, int mode); - public native void glHint ( int target, int mode ); + public native boolean glIsBuffer (int buffer); - public native boolean glIsBuffer ( int buffer ); + public native boolean glIsEnabled (int cap); - public native boolean glIsEnabled ( int cap ); + public native boolean glIsFramebuffer (int framebuffer); - public native boolean glIsFramebuffer ( int framebuffer ); + public native boolean glIsProgram (int program); - public native boolean glIsProgram ( int program ); + public native boolean glIsRenderbuffer (int renderbuffer); - public native boolean glIsRenderbuffer ( int renderbuffer ); + public native boolean glIsShader (int shader); - public native boolean glIsShader ( int shader ); + public native boolean glIsTexture (int texture); - public native boolean glIsTexture ( int texture ); + public native void glLineWidth (float width); - public native void glLineWidth ( float width ); + public native void glLinkProgram (int program); - public native void glLinkProgram ( int program ); + public native void glPixelStorei (int pname, int param); - public native void glPixelStorei ( int pname, int param ); + public native void glPolygonOffset (float factor, float units); - public native void glPolygonOffset ( float factor, float units ); + public native void glReadPixels (int x, int y, int width, int height, int format, int type, Buffer pixels); - public native void glReadPixels ( int x, int y, int width, int height, int format, int type, Buffer pixels ); + public native void glReleaseShaderCompiler (); - public native void glReleaseShaderCompiler ( ); + public native void glRenderbufferStorage (int target, int internalformat, int width, int height); - public native void glRenderbufferStorage ( int target, int internalformat, int width, int height ); + public native void glSampleCoverage (float value, boolean invert); - public native void glSampleCoverage ( float value, boolean invert ); + public native void glScissor (int x, int y, int width, int height); - public native void glScissor ( int x, int y, int width, int height ); + public native void glShaderBinary (int n, IntBuffer shaders, int binaryformat, Buffer binary, int length); - public native void glShaderBinary ( int n, IntBuffer shaders, int binaryformat, Buffer binary, int length ); + public native void glShaderSource (int shader, String string); - public native void glShaderSource ( int shader, String string ); + public native void glStencilFunc (int func, int ref, int mask); - public native void glStencilFunc ( int func, int ref, int mask ); + public native void glStencilFuncSeparate (int face, int func, int ref, int mask); - public native void glStencilFuncSeparate ( int face, int func, int ref, int mask ); + public native void glStencilMask (int mask); - public native void glStencilMask ( int mask ); + public native void glStencilMaskSeparate (int face, int mask); - public native void glStencilMaskSeparate ( int face, int mask ); + public native void glStencilOp (int fail, int zfail, int zpass); - public native void glStencilOp ( int fail, int zfail, int zpass ); + public native void glStencilOpSeparate (int face, int fail, int zfail, int zpass); - public native void glStencilOpSeparate ( int face, int fail, int zfail, int zpass ); + public native void glTexImage2D (int target, int level, int internalformat, int width, int height, int border, int format, + int type, Buffer pixels); - public native void glTexImage2D ( int target, int level, int internalformat, int width, int height, int border, int format, int type, Buffer pixels ); + public native void glTexParameterf (int target, int pname, float param); - public native void glTexParameterf ( int target, int pname, float param ); + public native void glTexParameterfv (int target, int pname, FloatBuffer params); - public native void glTexParameterfv ( int target, int pname, FloatBuffer params ); + public native void glTexParameteri (int target, int pname, int param); - public native void glTexParameteri ( int target, int pname, int param ); + public native void glTexParameteriv (int target, int pname, IntBuffer params); - public native void glTexParameteriv ( int target, int pname, IntBuffer params ); + public native void glTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, int format, + int type, Buffer pixels); - public native void glTexSubImage2D ( int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, Buffer pixels ); + public native void glUniform1f (int location, float x); - public native void glUniform1f ( int location, float x ); + public native void glUniform1fv (int location, int count, FloatBuffer v); - public native void glUniform1fv ( int location, int count, FloatBuffer v ); + public native void glUniform1i (int location, int x); - public native void glUniform1i ( int location, int x ); + public native void glUniform1iv (int location, int count, IntBuffer v); - public native void glUniform1iv ( int location, int count, IntBuffer v ); + public native void glUniform2f (int location, float x, float y); - public native void glUniform2f ( int location, float x, float y ); + public native void glUniform2fv (int location, int count, FloatBuffer v); - public native void glUniform2fv ( int location, int count, FloatBuffer v ); + public native void glUniform2i (int location, int x, int y); - public native void glUniform2i ( int location, int x, int y ); + public native void glUniform2iv (int location, int count, IntBuffer v); - public native void glUniform2iv ( int location, int count, IntBuffer v ); + public native void glUniform3f (int location, float x, float y, float z); - public native void glUniform3f ( int location, float x, float y, float z ); + public native void glUniform3fv (int location, int count, FloatBuffer v); - public native void glUniform3fv ( int location, int count, FloatBuffer v ); + public native void glUniform3i (int location, int x, int y, int z); - public native void glUniform3i ( int location, int x, int y, int z ); + public native void glUniform3iv (int location, int count, IntBuffer v); - public native void glUniform3iv ( int location, int count, IntBuffer v ); + public native void glUniform4f (int location, float x, float y, float z, float w); - public native void glUniform4f ( int location, float x, float y, float z, float w ); + public native void glUniform4fv (int location, int count, FloatBuffer v); - public native void glUniform4fv ( int location, int count, FloatBuffer v ); + public native void glUniform4i (int location, int x, int y, int z, int w); - public native void glUniform4i ( int location, int x, int y, int z, int w ); + public native void glUniform4iv (int location, int count, IntBuffer v); - public native void glUniform4iv ( int location, int count, IntBuffer v ); + public native void glUniformMatrix2fv (int location, int count, boolean transpose, FloatBuffer value); - public native void glUniformMatrix2fv ( int location, int count, boolean transpose, FloatBuffer value ); + public native void glUniformMatrix3fv (int location, int count, boolean transpose, FloatBuffer value); - public native void glUniformMatrix3fv ( int location, int count, boolean transpose, FloatBuffer value ); + public native void glUniformMatrix4fv (int location, int count, boolean transpose, FloatBuffer value); - public native void glUniformMatrix4fv ( int location, int count, boolean transpose, FloatBuffer value ); + public native void glUseProgram (int program); - public native void glUseProgram ( int program ); + public native void glValidateProgram (int program); - public native void glValidateProgram ( int program ); + public native void glVertexAttrib1f (int indx, float x); - public native void glVertexAttrib1f ( int indx, float x ); + public native void glVertexAttrib1fv (int indx, FloatBuffer values); - public native void glVertexAttrib1fv ( int indx, FloatBuffer values ); + public native void glVertexAttrib2f (int indx, float x, float y); - public native void glVertexAttrib2f ( int indx, float x, float y ); + public native void glVertexAttrib2fv (int indx, FloatBuffer values); - public native void glVertexAttrib2fv ( int indx, FloatBuffer values ); + public native void glVertexAttrib3f (int indx, float x, float y, float z); - public native void glVertexAttrib3f ( int indx, float x, float y, float z ); + public native void glVertexAttrib3fv (int indx, FloatBuffer values); - public native void glVertexAttrib3fv ( int indx, FloatBuffer values ); + public native void glVertexAttrib4f (int indx, float x, float y, float z, float w); - public native void glVertexAttrib4f ( int indx, float x, float y, float z, float w ); + public native void glVertexAttrib4fv (int indx, FloatBuffer values); - public native void glVertexAttrib4fv ( int indx, FloatBuffer values ); + public native void glVertexAttribPointer (int indx, int size, int type, boolean normalized, int stride, Buffer ptr); - public native void glVertexAttribPointer ( int indx, int size, int type, boolean normalized, int stride, Buffer ptr ); - - public native void glVertexAttribPointer ( int indx, int size, int type, boolean normalized, int stride, int ptr ); + public native void glVertexAttribPointer (int indx, int size, int type, boolean normalized, int stride, int ptr); - public native void glViewport ( int x, int y, int width, int height ); + public native void glViewport (int x, int y, int width, int height); } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGraphics.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGraphics.java index 56012f56e..86e92ba6f 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGraphics.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGraphics.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import java.io.IOException; @@ -38,6 +36,7 @@ import com.badlogic.gdx.backends.android.surfaceview.GLSurfaceView20; import com.badlogic.gdx.backends.android.surfaceview.GLSurfaceViewCupcake; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Font; +import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.FrameBuffer; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.GL11; @@ -45,17 +44,16 @@ import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.GLCommon; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.Pixmap; +import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.ShaderProgram; import com.badlogic.gdx.graphics.Texture; -import com.badlogic.gdx.graphics.Font.FontStyle; -import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; import com.badlogic.gdx.math.WindowedMean; /** * An implementation of {@link Graphics} for Android. - * + * * @author mzechner */ final class AndroidGraphics implements Graphics, Renderer { @@ -89,7 +87,7 @@ final class AndroidGraphics implements Graphics, Renderer { * Common instance */ protected GLCommon gl; - + /** * the GL10 instance * */ @@ -140,63 +138,49 @@ final class AndroidGraphics implements Graphics, Renderer { */ private boolean dispose = false; - public AndroidGraphics(AndroidApplication activity, boolean useGL2IfAvailable) { + public AndroidGraphics (AndroidApplication activity, boolean useGL2IfAvailable) { view = createGLSurfaceView(activity, useGL2IfAvailable); this.app = activity; } - private View createGLSurfaceView( Activity activity, boolean useGL2 ) - { - if (useGL2 && checkGL20( ) ) - { - GLSurfaceView20 view = new GLSurfaceView20( activity ); - view.setRenderer( this ); + private View createGLSurfaceView (Activity activity, boolean useGL2) { + if (useGL2 && checkGL20()) { + GLSurfaceView20 view = new GLSurfaceView20(activity); + view.setRenderer(this); return view; - } - else - { - if( Integer.parseInt( android.os.Build.VERSION.SDK ) <= 4 ) - { - GLSurfaceViewCupcake view = new GLSurfaceViewCupcake( activity ); - view.setRenderer( this ); + } else { + if (Integer.parseInt(android.os.Build.VERSION.SDK) <= 4) { + GLSurfaceViewCupcake view = new GLSurfaceViewCupcake(activity); + view.setRenderer(this); return view; - } - else - { - android.opengl.GLSurfaceView view = new android.opengl.GLSurfaceView( activity ); - view.setRenderer( this ); + } else { + android.opengl.GLSurfaceView view = new android.opengl.GLSurfaceView(activity); + view.setRenderer(this); return view; } } - } /** * This is a hack... - * + * * @param input */ - protected void setInput(AndroidInput input) { + protected void setInput (AndroidInput input) { this.input = input; } - private boolean checkGL20( ) { - EGL10 egl = (EGL10) EGLContext.getEGL(); + private boolean checkGL20 () { + EGL10 egl = (EGL10)EGLContext.getEGL(); EGLDisplay display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); int[] version = new int[2]; egl.eglInitialize(display, version); int EGL_OPENGL_ES2_BIT = 4; - int[] configAttribs = - { - EGL10.EGL_RED_SIZE, 4, - EGL10.EGL_GREEN_SIZE, 4, - EGL10.EGL_BLUE_SIZE, 4, - EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - EGL10.EGL_NONE - }; + int[] configAttribs = {EGL10.EGL_RED_SIZE, 4, EGL10.EGL_GREEN_SIZE, 4, EGL10.EGL_BLUE_SIZE, 4, EGL10.EGL_RENDERABLE_TYPE, + EGL_OPENGL_ES2_BIT, EGL10.EGL_NONE}; EGLConfig[] configs = new EGLConfig[10]; int[] num_config = new int[1]; @@ -208,89 +192,77 @@ final class AndroidGraphics implements Graphics, Renderer { /** * {@inheritDoc} */ - @Override - public GL10 getGL10() { + @Override public GL10 getGL10 () { return gl10; } /** * {@inheritDoc} */ - @Override - public GL11 getGL11() { + @Override public GL11 getGL11 () { return gl11; } /** * {@inheritDoc} */ - @Override - public GL20 getGL20() { + @Override public GL20 getGL20 () { return gl20; } /** * {@inheritDoc} */ - @Override - public int getHeight() { + @Override public int getHeight () { return height; } /** * {@inheritDoc} */ - @Override - public int getWidth() { + @Override public int getWidth () { return width; } /** * {@inheritDoc} */ - @Override - public boolean isGL11Available() { + @Override public boolean isGL11Available () { return gl11 != null; } /** * {@inheritDoc} */ - @Override - public boolean isGL20Available() { + @Override public boolean isGL20Available () { return gl20 != null; } /** * {@inheritDoc} */ - @Override - public Font newFont(String fontName, int size, FontStyle style ) { - return new AndroidFont(this, fontName, size, style ); + @Override public Font newFont (String fontName, int size, FontStyle style) { + return new AndroidFont(this, fontName, size, style); } /** * {@inheritDoc} */ - @Override - public Font newFont(FileHandle file, int size, FontStyle style) { - AndroidFileHandle aHandle = (AndroidFileHandle) file; + @Override public Font newFont (FileHandle file, int size, FontStyle style) { + AndroidFileHandle aHandle = (AndroidFileHandle)file; AndroidFont font = new AndroidFont(this, aHandle.getAssetManager(), aHandle.getFileName(), size, style); return font; } - private static boolean isPowerOfTwo( int value ) - { - return ((value!=0) && (value&(value-1))==0); + private static boolean isPowerOfTwo (int value) { + return ((value != 0) && (value & (value - 1)) == 0); } /** * {@inheritDoc} */ - @Override - public Pixmap newPixmap(int width, int height, Format format) { - if( !isPowerOfTwo( width ) || !isPowerOfTwo( height ) ) - throw new GdxRuntimeException( "Dimensions have to be a power of two" ); + @Override public Pixmap newPixmap (int width, int height, Format format) { + if (!isPowerOfTwo(width) || !isPowerOfTwo(height)) throw new GdxRuntimeException("Dimensions have to be a power of two"); return new AndroidPixmap(width, height, format); } @@ -298,15 +270,13 @@ final class AndroidGraphics implements Graphics, Renderer { /** * {@inheritDoc} */ - @Override - public Pixmap newPixmap(InputStream in) { + @Override public Pixmap newPixmap (InputStream in) { Bitmap bitmap = BitmapFactory.decodeStream(in, null, null); - if( bitmap == null ) - throw new GdxRuntimeException( "Couldn't load Pixmap from InputStream" ); + if (bitmap == null) throw new GdxRuntimeException("Couldn't load Pixmap from InputStream"); - if( !isPowerOfTwo( bitmap.getWidth() ) || !isPowerOfTwo( bitmap.getHeight() ) ) - throw new GdxRuntimeException( "Dimensions have to be a power of two" ); + if (!isPowerOfTwo(bitmap.getWidth()) || !isPowerOfTwo(bitmap.getHeight())) + throw new GdxRuntimeException("Dimensions have to be a power of two"); return new AndroidPixmap(bitmap); } @@ -314,9 +284,8 @@ final class AndroidGraphics implements Graphics, Renderer { /** * {@inheritDoc} */ - @Override - public Pixmap newPixmap(FileHandle file) { - AndroidFileHandle aHandle = (AndroidFileHandle) file; + @Override public Pixmap newPixmap (FileHandle file) { + AndroidFileHandle aHandle = (AndroidFileHandle)file; Bitmap bitmap = null; if (aHandle.isAsset()) { @@ -326,17 +295,16 @@ final class AndroidGraphics implements Graphics, Renderer { bitmap = BitmapFactory.decodeStream(in, null, null); in.close(); } catch (IOException e) { - throw new GdxRuntimeException( "Couldn't open Pixmap from file '" + file + "'", e ); + throw new GdxRuntimeException("Couldn't open Pixmap from file '" + file + "'", e); } } else { bitmap = BitmapFactory.decodeFile(aHandle.getFileName()); } - if( bitmap == null ) - throw new GdxRuntimeException( "Couldn't open Pixmap from file '" + file + "'" ); + if (bitmap == null) throw new GdxRuntimeException("Couldn't open Pixmap from file '" + file + "'"); - if( !isPowerOfTwo( bitmap.getWidth() ) || !isPowerOfTwo( bitmap.getHeight() ) ) - throw new GdxRuntimeException( "Dimensions have to be a power of two" ); + if (!isPowerOfTwo(bitmap.getWidth()) || !isPowerOfTwo(bitmap.getHeight())) + throw new GdxRuntimeException("Dimensions have to be a power of two"); return new AndroidPixmap(bitmap); } @@ -344,47 +312,39 @@ final class AndroidGraphics implements Graphics, Renderer { /** * {@inheritDoc} */ - @Override - public Pixmap newPixmap(Object nativePixmap) { - return new AndroidPixmap((Bitmap) nativePixmap); + @Override public Pixmap newPixmap (Object nativePixmap) { + return new AndroidPixmap((Bitmap)nativePixmap); } /** * {@inheritDoc} */ - @Override - public void setRenderListener(RenderListener listener) { + @Override public void setRenderListener (RenderListener listener) { synchronized (this) { - if (this.listener != null) - this.listener.dispose(); + if (this.listener != null) this.listener.dispose(); this.listener = listener; } } - @Override - public void onDrawFrame(javax.microedition.khronos.opengles.GL10 gl) { + @Override public void onDrawFrame (javax.microedition.khronos.opengles.GL10 gl) { // calculate delta time deltaTime = (System.nanoTime() - lastFrameTime) / 1000000000.0f; lastFrameTime = System.nanoTime(); mean.addValue(deltaTime); // this is a hack so the events get processed synchronously. - if (input != null) - input.update(); + if (input != null) input.update(); synchronized (this) { - if (listener != null) - listener.render(); + if (listener != null) listener.render(); } if (dispose) { - if (listener != null) - listener.dispose(); + if (listener != null) listener.dispose(); listener = null; dispose = false; } - if (System.nanoTime() - frameStart > 1000000000) { fps = frames; frames = 0; @@ -394,57 +354,46 @@ final class AndroidGraphics implements Graphics, Renderer { } /** - * This instantiates the GL10, GL11 and GL20 instances. - * Includes the check for certain devices that pretend - * to support GL11 but fuck up vertex buffer objects. This - * includes the pixelflinger which segfaults when buffers - * are deleted as well as the Motorola CLIQ and the Samsung - * Behold II. - * + * This instantiates the GL10, GL11 and GL20 instances. Includes the check for certain devices that pretend to support GL11 but + * fuck up vertex buffer objects. This includes the pixelflinger which segfaults when buffers are deleted as well as the + * Motorola CLIQ and the Samsung Behold II. + * * @param gl */ - private void setupGL(javax.microedition.khronos.opengles.GL10 gl) { - if (gl10 != null || gl20 != null) - return; + private void setupGL (javax.microedition.khronos.opengles.GL10 gl) { + if (gl10 != null || gl20 != null) return; - if( view instanceof GLSurfaceView20 ) - { + if (view instanceof GLSurfaceView20) { gl20 = new AndroidGL20(); this.gl = gl20; - } - else - { + } else { gl10 = new AndroidGL10(gl); this.gl = gl10; if (gl instanceof javax.microedition.khronos.opengles.GL11) { String renderer = gl.glGetString(GL10.GL_RENDERER); - if (renderer.toLowerCase().contains("pixelflinger")) - return; + if (renderer.toLowerCase().contains("pixelflinger")) return; - if (android.os.Build.MODEL.equals("MB200") || android.os.Build.MODEL.equals("MB220") || android.os.Build.MODEL.contains("Behold")) - return; - gl11 = new AndroidGL11((javax.microedition.khronos.opengles.GL11) gl); + if (android.os.Build.MODEL.equals("MB200") || android.os.Build.MODEL.equals("MB220") + || android.os.Build.MODEL.contains("Behold")) return; + gl11 = new AndroidGL11((javax.microedition.khronos.opengles.GL11)gl); gl10 = gl11; } } - + Gdx.gl = this.gl; Gdx.gl10 = gl10; Gdx.gl11 = gl11; Gdx.gl20 = gl20; } - @Override - public void onSurfaceChanged(javax.microedition.khronos.opengles.GL10 gl, int width, int height) { + @Override public void onSurfaceChanged (javax.microedition.khronos.opengles.GL10 gl, int width, int height) { this.width = width; this.height = height; - if (listener != null) - listener.surfaceChanged(width, height); + if (listener != null) listener.surfaceChanged(width, height); } - @Override - public void onSurfaceCreated(javax.microedition.khronos.opengles.GL10 gl, EGLConfig config) { + @Override public void onSurfaceCreated (javax.microedition.khronos.opengles.GL10 gl, EGLConfig config) { setupGL(gl); Mesh.invalidateAllMeshes(); @@ -457,23 +406,21 @@ final class AndroidGraphics implements Graphics, Renderer { this.width = display.getWidth(); this.height = display.getHeight(); - if (listener != null) - listener.surfaceCreated(); + if (listener != null) listener.surfaceCreated(); mean = new WindowedMean(5); this.lastFrameTime = System.nanoTime(); - gl.glViewport( 0, 0, this.width, this.height ); + gl.glViewport(0, 0, this.width, this.height); } /** * {@inheritDoc} */ - @Override - public float getDeltaTime() { + @Override public float getDeltaTime () { return mean.getMean() == 0 ? deltaTime : mean.getMean(); } - public void disposeRenderListener() { + public void disposeRenderListener () { dispose = true; while (dispose) { try { @@ -486,53 +433,44 @@ final class AndroidGraphics implements Graphics, Renderer { /** * {@inheritDoc} */ - @Override - public GraphicsType getType() { + @Override public GraphicsType getType () { return GraphicsType.AndroidGL; } /** * {@inheritDoc} */ - @Override - public int getFramesPerSecond() { + @Override public int getFramesPerSecond () { return fps; } - @Override - public Texture newUnmanagedTexture(int width, int height, Format format, - TextureFilter minFilter, TextureFilter magFilter, - TextureWrap uWrap, TextureWrap vWrap) - { - if( !isPowerOfTwo( width ) || !isPowerOfTwo( height ) ) - throw new GdxRuntimeException( "Dimensions have to be a power of two" ); + @Override public Texture newUnmanagedTexture (int width, int height, Format format, TextureFilter minFilter, + TextureFilter magFilter, TextureWrap uWrap, TextureWrap vWrap) { + if (!isPowerOfTwo(width) || !isPowerOfTwo(height)) throw new GdxRuntimeException("Dimensions have to be a power of two"); Bitmap.Config config = AndroidPixmap.getInternalFormat(format); Bitmap bitmap = Bitmap.createBitmap(width, height, config); Texture texture = null; - texture = new AndroidTexture(this, bitmap, minFilter, magFilter, uWrap, vWrap, false, null ); + texture = new AndroidTexture(this, bitmap, minFilter, magFilter, uWrap, vWrap, false, null); bitmap.recycle(); return texture; } - @Override - public Texture newUnmanagedTexture(Pixmap pixmap, TextureFilter minFilter, - TextureFilter magFilter, TextureWrap uWrap, TextureWrap vWrap) { + @Override public Texture newUnmanagedTexture (Pixmap pixmap, TextureFilter minFilter, TextureFilter magFilter, + TextureWrap uWrap, TextureWrap vWrap) { - if( !isPowerOfTwo( pixmap.getWidth() ) || !isPowerOfTwo( pixmap.getHeight() ) ) - throw new GdxRuntimeException( "Dimensions have to be a power of two" ); + if (!isPowerOfTwo(pixmap.getWidth()) || !isPowerOfTwo(pixmap.getHeight())) + throw new GdxRuntimeException("Dimensions have to be a power of two"); - return new AndroidTexture(this, (Bitmap) pixmap.getNativePixmap(), minFilter, magFilter, uWrap, vWrap, false, null); + return new AndroidTexture(this, (Bitmap)pixmap.getNativePixmap(), minFilter, magFilter, uWrap, vWrap, false, null); } - @Override - public Texture newTexture(FileHandle file, TextureFilter minFilter, - TextureFilter magFilter, TextureWrap uWrap, TextureWrap vWrap) { - return new AndroidTexture(this, (Bitmap) null, minFilter, magFilter, uWrap, vWrap, true, (AndroidFileHandle)file); + @Override public Texture newTexture (FileHandle file, TextureFilter minFilter, TextureFilter magFilter, TextureWrap uWrap, + TextureWrap vWrap) { + return new AndroidTexture(this, (Bitmap)null, minFilter, magFilter, uWrap, vWrap, true, (AndroidFileHandle)file); } - public void clearManagedCaches() - { + public void clearManagedCaches () { Mesh.clearAllMeshes(); AndroidTexture.clearAllTextures(); ShaderProgram.clearAllShaderPrograms(); @@ -540,22 +478,17 @@ final class AndroidGraphics implements Graphics, Renderer { Font.clearAllFonts(); } - - - /** + /** * @return the GLSurfaceView */ - public View getView() - { + public View getView () { return view; } /** * {@inheritDoc} */ - @Override - public GLCommon getGLCommon() - { + @Override public GLCommon getGLCommon () { return gl; } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidInput.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidInput.java index 8c12120eb..37899cdf0 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidInput.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidInput.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import java.util.ArrayList; @@ -37,86 +35,76 @@ import com.badlogic.gdx.Input; import com.badlogic.gdx.InputListener; /** - * An implementation of the {@link Input} interface for Android. + * An implementation of the {@link Input} interface for Android. * * @author mzechner - * + * */ -final class AndroidInput implements Input, OnKeyListener, OnTouchListener, SensorEventListener -{ +final class AndroidInput implements Input, OnKeyListener, OnTouchListener, SensorEventListener { /** touch coordinates in x, package private for touch handlers **/ int[] touchX = new int[10]; - + /** touch coordinates in y, package private for touch handlers **/ int[] touchY = new int[10]; - + /** touch state, package private for touch handlers **/ - boolean[] touched = new boolean[10]; + boolean[] touched = new boolean[10]; /** key state **/ - private HashSet keys = new HashSet( ); - + private HashSet keys = new HashSet(); + /** whether the accelerometer is available **/ - public boolean accelerometerAvailable = false; - + public boolean accelerometerAvailable = false; + /** the sensor manager **/ private SensorManager manager; - + /** the accelerometer values **/ - private final float[] accelerometerValues = new float[3]; - + private final float[] accelerometerValues = new float[3]; + /** user input text **/ private String text = null; - + /** the last user input text listener **/ private TextInputListener textListener = null; - + /** a nice handler **/ private Handler handle; - + /** array of input listeners **/ - private final ArrayList inputListeners = new ArrayList( ); - + private final ArrayList inputListeners = new ArrayList(); + /** the app **/ - private final AndroidApplication app; - + private final AndroidApplication app; + /** the touch handler **/ private final AndroidTouchHandler touchHandler; - - /** touch handler sleep time in milliseconds**/ + + /** touch handler sleep time in milliseconds **/ private int sleepTime = 0; - + /** * helper enum * @author mzechner - * + * */ - static enum EventType - { - MouseDown, - MouseUp, - MouseMoved, - MouseDragged, - KeyDown, - KeyUp, - KeyTyped + static enum EventType { + MouseDown, MouseUp, MouseMoved, MouseDragged, KeyDown, KeyUp, KeyTyped } /** * Helper class * @author mzechner - * + * */ - static class Event - { - public int x, y; + static class Event { + public int x, y; public int pointer; public int keycode; public char keychar; public EventType type; - public void set( EventType type, int x, int y, int pointer, int keycode, char keychar ) - { + public void set (EventType type, int x, int y, int pointer, int keycode, char keychar) { this.type = type; this.x = x; this.y = y; @@ -124,299 +112,232 @@ final class AndroidInput implements Input, OnKeyListener, OnTouchListener, Senso this.keycode = keycode; this.keychar = keychar; } - } + } /** queue of events to be processed, package private for touch handlers **/ - final ArrayList eventQueue = new ArrayList( ); - + final ArrayList eventQueue = new ArrayList(); + /** pool of free Event instances, package private for touch handlers **/ - final ArrayList freeEvents = new ArrayList( ); - + final ArrayList freeEvents = new ArrayList(); + /** index to the next free event, package private for touch handlers **/ int freeEventIndex = 0; - + /** whether multitouch is supported or not **/ final boolean hasMultitouch; - - AndroidInput( AndroidApplication activity, View view, int sleepTime ) - { - view.setOnKeyListener( this ); - view.setOnTouchListener( this ); + + AndroidInput (AndroidApplication activity, View view, int sleepTime) { + view.setOnKeyListener(this); + view.setOnTouchListener(this); view.setFocusable(true); view.setFocusableInTouchMode(true); - view.requestFocus(); + view.requestFocus(); view.requestFocusFromTouch(); - + manager = (SensorManager)activity.getSystemService(Context.SENSOR_SERVICE); - if( manager.getSensorList(Sensor.TYPE_ACCELEROMETER).size() == 0 ) + if (manager.getSensorList(Sensor.TYPE_ACCELEROMETER).size() == 0) accelerometerAvailable = false; - else - { + else { Sensor accelerometer = manager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0); - if( !manager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME ) ) + if (!manager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME)) accelerometerAvailable = false; else accelerometerAvailable = true; } - - for( int i = 0; i < 1000; i++ ) - freeEvents.add( new Event( ) ); - handle = new Handler(); + for (int i = 0; i < 1000; i++) + freeEvents.add(new Event()); + + handle = new Handler(); this.app = activity; - + this.sleepTime = sleepTime; - - int sdkVersion = Integer.parseInt( android.os.Build.VERSION.SDK ); - - if( sdkVersion >= 5 ) + + int sdkVersion = Integer.parseInt(android.os.Build.VERSION.SDK); + + if (sdkVersion >= 5) touchHandler = new AndroidMultiTouchHandler(); else touchHandler = new AndroidSingleTouchHandler(); - - - hasMultitouch = touchHandler instanceof AndroidMultiTouchHandler && ((AndroidMultiTouchHandler)touchHandler).supportsMultitouch(activity); + + hasMultitouch = touchHandler instanceof AndroidMultiTouchHandler + && ((AndroidMultiTouchHandler)touchHandler).supportsMultitouch(activity); } /** - * Called from within the render method of the AndroidGraphics instance. - * This is ugly but the only way to syncrhonously process events. + * Called from within the render method of the AndroidGraphics instance. This is ugly but the only way to syncrhonously process + * events. */ - protected void update( ) - { - synchronized( eventQueue ) - { - for( int i = 0; i < eventQueue.size(); i++ ) - { + protected void update () { + synchronized (eventQueue) { + for (int i = 0; i < eventQueue.size(); i++) { Event event = eventQueue.get(i); - if( event.type == EventType.MouseDown ) - for( int j = 0; j < inputListeners.size(); j++ ) - if( inputListeners.get(j).touchDown(event.x, event.y, event.pointer ) ) - break; - if( event.type == EventType.MouseUp ) - for( int j = 0; j < inputListeners.size(); j++ ) - if( inputListeners.get(j).touchUp(event.x, event.y, event.pointer ) ) - break; - if( event.type == EventType.MouseDragged ) - for( int j = 0; j < inputListeners.size(); j++ ) - if( inputListeners.get(j).touchDragged(event.x, event.y, event.pointer ) ) - break; - if( event.type == EventType.KeyDown ) - for( int j = 0; j < inputListeners.size(); j++ ) - if( inputListeners.get(j).keyDown( event.keycode ) ) - break; - if( event.type == EventType.KeyUp ) - for( int j = 0; j < inputListeners.size(); j++ ) - if( inputListeners.get(j).keyUp( event.keycode ) ) - break; - if( event.type == EventType.KeyTyped ) - for( int j = 0; j < inputListeners.size(); j++ ) - if( inputListeners.get(j).keyTyped( event.keychar ) ) - break; + if (event.type == EventType.MouseDown) for (int j = 0; j < inputListeners.size(); j++) + if (inputListeners.get(j).touchDown(event.x, event.y, event.pointer)) break; + if (event.type == EventType.MouseUp) for (int j = 0; j < inputListeners.size(); j++) + if (inputListeners.get(j).touchUp(event.x, event.y, event.pointer)) break; + if (event.type == EventType.MouseDragged) for (int j = 0; j < inputListeners.size(); j++) + if (inputListeners.get(j).touchDragged(event.x, event.y, event.pointer)) break; + if (event.type == EventType.KeyDown) for (int j = 0; j < inputListeners.size(); j++) + if (inputListeners.get(j).keyDown(event.keycode)) break; + if (event.type == EventType.KeyUp) for (int j = 0; j < inputListeners.size(); j++) + if (inputListeners.get(j).keyUp(event.keycode)) break; + if (event.type == EventType.KeyTyped) for (int j = 0; j < inputListeners.size(); j++) + if (inputListeners.get(j).keyTyped(event.keychar)) break; } eventQueue.clear(); freeEventIndex = 0; } - - if( textListener != null ) - { - textListener.input( text ); + + if (textListener != null) { + textListener.input(text); textListener = null; } } - - @Override - public void addInputListener(InputListener listener) - { - synchronized ( eventQueue) - { - if( !inputListeners.contains( listener )) - inputListeners.add( listener ); + + @Override public void addInputListener (InputListener listener) { + synchronized (eventQueue) { + if (!inputListeners.contains(listener)) inputListeners.add(listener); } } - @Override - public float getAccelerometerX() - { + @Override public float getAccelerometerX () { return accelerometerValues[0]; } - @Override - public float getAccelerometerY() - { + @Override public float getAccelerometerY () { return accelerometerValues[1]; } - @Override - public float getAccelerometerZ() - { + @Override public float getAccelerometerZ () { return accelerometerValues[2]; } - @Override - public void getTextInput( final TextInputListener listener, final String title, final String text) - { - handle.post( new Runnable() - { - public void run( ) - { - + @Override public void getTextInput (final TextInputListener listener, final String title, final String text) { + handle.post(new Runnable() { + public void run () { - AlertDialog.Builder alert = new AlertDialog.Builder(AndroidInput.this.app); + AlertDialog.Builder alert = new AlertDialog.Builder(AndroidInput.this.app); - alert.setTitle(title); + alert.setTitle(title); - // Set an EditText view to get user input + // Set an EditText view to get user input final EditText input = new EditText(AndroidInput.this.app); - input.setText( text ); + input.setText(text); input.setSingleLine(); - alert.setView(input); - - alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int whichButton) { - AndroidInput.this.text = input.getText().toString(); - textListener = listener; - } - }); + alert.setView(input); + + alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { + public void onClick (DialogInterface dialog, int whichButton) { + AndroidInput.this.text = input.getText().toString(); + textListener = listener; + } + }); alert.show(); } - } ); + }); } - @Override - public int getX() - { + @Override public int getX () { return touchX[0]; } - @Override - public int getY() - { + @Override public int getY () { return touchY[0]; } - - @Override - public int getX( int pointer ) - { + + @Override public int getX (int pointer) { return touchX[pointer]; } - @Override - public int getY( int pointer ) - { + @Override public int getY (int pointer) { return touchY[pointer]; } - public boolean isTouched( int pointer ) - { + public boolean isTouched (int pointer) { return touched[pointer]; } - - @Override - public boolean isAccelerometerAvailable() - { + + @Override public boolean isAccelerometerAvailable () { return accelerometerAvailable; } - @Override - public boolean isKeyPressed(int key) - { - synchronized(eventQueue) - { - if( key == Input.Keys.ANY_KEY ) + @Override public boolean isKeyPressed (int key) { + synchronized (eventQueue) { + if (key == Input.Keys.ANY_KEY) return keys.size() > 0; else - return keys.contains( key ); + return keys.contains(key); } } - @Override - public boolean isTouched() - { + @Override public boolean isTouched () { return touched[0]; } - @Override - public void removeInputListener(InputListener listener) - { - synchronized( eventQueue ) - { - inputListeners.remove( listener ); + @Override public void removeInputListener (InputListener listener) { + synchronized (eventQueue) { + inputListeners.remove(listener); } } boolean requestFocus = true; - @Override - public boolean onTouch(View view, MotionEvent event) - { - if( requestFocus ) - { - view.requestFocus(); + + @Override public boolean onTouch (View view, MotionEvent event) { + if (requestFocus) { + view.requestFocus(); view.requestFocusFromTouch(); requestFocus = false; } - - touchHandler.onTouch( event, this ); - - if( sleepTime != 0 ) - { + + touchHandler.onTouch(event, this); + + if (sleepTime != 0) { try { - Thread.sleep( sleepTime ); + Thread.sleep(sleepTime); } catch (InterruptedException e) { // yeah, right... } } - + return true; } - @Override - public boolean onKey(View v, int keyCode, KeyEvent event) - { - synchronized( eventQueue ) - { - if( event.getAction() == KeyEvent.ACTION_DOWN ) - { + @Override public boolean onKey (View v, int keyCode, KeyEvent event) { + synchronized (eventQueue) { + if (event.getAction() == KeyEvent.ACTION_DOWN) { Event ev = freeEvents.get(freeEventIndex++); - ev.set( EventType.KeyDown, 0, 0, 0, event.getKeyCode(), (char)event.getUnicodeChar() ); - eventQueue.add( ev ); - keys.add( event.getKeyCode() ); + ev.set(EventType.KeyDown, 0, 0, 0, event.getKeyCode(), (char)event.getUnicodeChar()); + eventQueue.add(ev); + keys.add(event.getKeyCode()); } - if( event.getAction() == KeyEvent.ACTION_UP ) - { - keys.remove( event.getKeyCode() ); - + if (event.getAction() == KeyEvent.ACTION_UP) { + keys.remove(event.getKeyCode()); + Event ev = freeEvents.get(freeEventIndex++); - ev.set( EventType.KeyUp, 0, 0, 0, event.getKeyCode(), (char)event.getUnicodeChar() ); - eventQueue.add( ev ); - + ev.set(EventType.KeyUp, 0, 0, 0, event.getKeyCode(), (char)event.getUnicodeChar()); + eventQueue.add(ev); + ev = freeEvents.get(freeEventIndex++); - ev.set( EventType.KeyTyped, 0, 0, 0, event.getKeyCode(), (char)event.getUnicodeChar() ); - eventQueue.add( ev ); + ev.set(EventType.KeyTyped, 0, 0, 0, event.getKeyCode(), (char)event.getUnicodeChar()); + eventQueue.add(ev); } } - + return false; } - @Override - public void onAccuracyChanged(Sensor arg0, int arg1) - { - + @Override public void onAccuracyChanged (Sensor arg0, int arg1) { + } - @Override - public void onSensorChanged(SensorEvent event) - { - if( event.sensor.getType() == Sensor.TYPE_ACCELEROMETER ) - { - System.arraycopy( event.values, 0, accelerometerValues, 0, accelerometerValues.length ); - } + @Override public void onSensorChanged (SensorEvent event) { + if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { + System.arraycopy(event.values, 0, accelerometerValues, 0, accelerometerValues.length); + } } - @Override - public boolean supportsMultitouch() - { + @Override public boolean supportsMultitouch () { return hasMultitouch; } } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidMultiTouchHandler.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidMultiTouchHandler.java index 09a4e724c..0c188b9fb 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidMultiTouchHandler.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidMultiTouchHandler.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import android.view.MotionEvent; @@ -21,74 +19,67 @@ import com.badlogic.gdx.backends.android.AndroidInput.Event; import com.badlogic.gdx.backends.android.AndroidInput.EventType; /** - * Multitouch handler for devices running Android >= 2.0. If device is - * capable of (fake) multitouch this will report additional pointers. + * Multitouch handler for devices running Android >= 2.0. If device is capable of (fake) multitouch this will report additional + * pointers. * * @author badlogicgames@gmail.com - * + * */ -public class AndroidMultiTouchHandler implements AndroidTouchHandler -{ - public void onTouch( MotionEvent event, AndroidInput input ) - { - final int action = event.getAction() & MotionEvent.ACTION_MASK; +public class AndroidMultiTouchHandler implements AndroidTouchHandler { + public void onTouch (MotionEvent event, AndroidInput input) { + final int action = event.getAction() & MotionEvent.ACTION_MASK; int pointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_ID_MASK) >> MotionEvent.ACTION_POINTER_ID_SHIFT; - int pointerId = event.getPointerId( pointerIndex ); - + int pointerId = event.getPointerId(pointerIndex); + int x = 0, y = 0; - - switch( action ) - { - case MotionEvent.ACTION_DOWN: - case MotionEvent.ACTION_POINTER_DOWN: - x = (int)event.getX( pointerIndex ); - y = (int)event.getY( pointerIndex ); - postTouchEvent( input, EventType.MouseDown, x, y, pointerId ); - input.touchX[pointerId] = x; - input.touchY[pointerId] = y; - input.touched[pointerId] = true; - break; - case MotionEvent.ACTION_UP: - case MotionEvent.ACTION_POINTER_UP: - case MotionEvent.ACTION_OUTSIDE: - case MotionEvent.ACTION_CANCEL: - x = (int)event.getX( pointerIndex ); - y = (int)event.getY( pointerIndex ); - postTouchEvent( input, EventType.MouseUp, x, y, pointerId ); + switch (action) { + case MotionEvent.ACTION_DOWN: + case MotionEvent.ACTION_POINTER_DOWN: + x = (int)event.getX(pointerIndex); + y = (int)event.getY(pointerIndex); + postTouchEvent(input, EventType.MouseDown, x, y, pointerId); + input.touchX[pointerId] = x; + input.touchY[pointerId] = y; + input.touched[pointerId] = true; + break; + + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_POINTER_UP: + case MotionEvent.ACTION_OUTSIDE: + case MotionEvent.ACTION_CANCEL: + x = (int)event.getX(pointerIndex); + y = (int)event.getY(pointerIndex); + postTouchEvent(input, EventType.MouseUp, x, y, pointerId); + input.touchX[pointerId] = x; + input.touchY[pointerId] = y; + input.touched[pointerId] = false; + break; + + case MotionEvent.ACTION_MOVE: + int pointerCount = event.getPointerCount(); + for (int i = 0; i < pointerCount; i++) { + pointerIndex = i; + pointerId = event.getPointerId(pointerIndex); + x = (int)event.getX(pointerIndex); + y = (int)event.getY(pointerIndex); + postTouchEvent(input, EventType.MouseDragged, x, y, pointerId); input.touchX[pointerId] = x; input.touchY[pointerId] = y; - input.touched[pointerId] = false; - break; - - case MotionEvent.ACTION_MOVE: - int pointerCount = event.getPointerCount(); - for( int i = 0; i < pointerCount; i++ ) - { - pointerIndex = i; - pointerId = event.getPointerId( pointerIndex ); - x = (int)event.getX( pointerIndex ); - y = (int)event.getY( pointerIndex ); - postTouchEvent( input, EventType.MouseDragged, x, y, pointerId ); - input.touchX[pointerId] = x; - input.touchY[pointerId] = y; - } - break; - } + } + break; + } } - - private void postTouchEvent( AndroidInput input, EventType type, int x, int y, int pointer ) - { - synchronized( input.eventQueue ) - { + + private void postTouchEvent (AndroidInput input, EventType type, int x, int y, int pointer) { + synchronized (input.eventQueue) { Event ev = input.freeEvents.get(input.freeEventIndex++); - ev.set( type, x, y, pointer, 0, '\0' ); - input.eventQueue.add( ev ); - } + ev.set(type, x, y, pointer, 0, '\0'); + input.eventQueue.add(ev); + } } - public boolean supportsMultitouch( AndroidApplication activity ) - { - return activity.getPackageManager().hasSystemFeature( "android.hardware.touchscreen.multitouch" ); + public boolean supportsMultitouch (AndroidApplication activity) { + return activity.getPackageManager().hasSystemFeature("android.hardware.touchscreen.multitouch"); } } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidMusic.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidMusic.java index 8ef0b242e..9af666cb0 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidMusic.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidMusic.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import java.io.IOException; @@ -21,82 +19,56 @@ import android.media.MediaPlayer; import com.badlogic.gdx.audio.Music; -public class AndroidMusic implements Music -{ +public class AndroidMusic implements Music { private final AndroidAudio audio; private final MediaPlayer player; private boolean isPrepared = true; - - AndroidMusic( AndroidAudio audio, MediaPlayer player ) - { + + AndroidMusic (AndroidAudio audio, MediaPlayer player) { this.audio = audio; this.player = player; } - @Override - public void dispose() - { - if( player.isPlaying() ) - player.stop(); + @Override public void dispose () { + if (player.isPlaying()) player.stop(); player.release(); audio.musics.remove(this); } - @Override - public boolean isLooping() - { + @Override public boolean isLooping () { return player.isLooping(); } - @Override - public boolean isPlaying() - { + @Override public boolean isPlaying () { return player.isPlaying(); } - @Override - public void pause() - { - if( player.isPlaying() ) - player.pause(); + @Override public void pause () { + if (player.isPlaying()) player.pause(); } - @Override - public void play() - { - if( player.isPlaying() ) - return; - - try - { - if( !isPrepared ) - player.prepare(); + @Override public void play () { + if (player.isPlaying()) return; + + try { + if (!isPrepared) player.prepare(); player.start(); - } catch (IllegalStateException e) - { + } catch (IllegalStateException e) { e.printStackTrace(); - } - catch (IOException e) - { + } catch (IOException e) { e.printStackTrace(); - } + } } - @Override - public void setLooping(boolean isLooping) - { - player.setLooping( isLooping ); + @Override public void setLooping (boolean isLooping) { + player.setLooping(isLooping); } - @Override - public void setVolume(float volume) - { - player.setVolume( volume, volume ); + @Override public void setVolume (float volume) { + player.setVolume(volume, volume); } - @Override - public void stop() - { + @Override public void stop () { player.stop(); isPrepared = false; } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidPixmap.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidPixmap.java index 48765c5ac..6119b5782 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidPixmap.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidPixmap.java @@ -1,239 +1,193 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; +import android.graphics.Paint.Style; +import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; -import android.graphics.Paint.Style; -import android.graphics.PorterDuff.Mode; import com.badlogic.gdx.graphics.Pixmap; - /** * An implementation of {@link Pixmap} for Android. * * @author badlogicgames@gmail.com - * + * */ -final class AndroidPixmap implements Pixmap -{ +final class AndroidPixmap implements Pixmap { Canvas canvas; Bitmap pixmap; Paint paint; int r, g, b, a; - AndroidPixmap( int width, int height, Pixmap.Format format ) - { - Bitmap.Config config = getInternalFormat( format ); - pixmap = Bitmap.createBitmap( width, height, config ); - canvas = new Canvas( pixmap ); - paint = new Paint( ); - paint.setStyle( Style.FILL ); - + AndroidPixmap (int width, int height, Pixmap.Format format) { + Bitmap.Config config = getInternalFormat(format); + pixmap = Bitmap.createBitmap(width, height, config); + canvas = new Canvas(pixmap); + paint = new Paint(); + paint.setStyle(Style.FILL); + paint.setAntiAlias(true); - paint.setXfermode( new PorterDuffXfermode( Mode.SRC ) ); + paint.setXfermode(new PorterDuffXfermode(Mode.SRC)); } - + /** * {@inheritDoc} */ - public AndroidPixmap(Bitmap bitmap) - { + public AndroidPixmap (Bitmap bitmap) { pixmap = bitmap; - - if( pixmap.isMutable() ) - canvas = new Canvas( pixmap ); - paint = new Paint( ); - paint.setStyle( Style.FILL ); + + if (pixmap.isMutable()) canvas = new Canvas(pixmap); + paint = new Paint(); + paint.setStyle(Style.FILL); paint.setAntiAlias(true); - paint.setXfermode( new PorterDuffXfermode( Mode.SRC ) ); + paint.setXfermode(new PorterDuffXfermode(Mode.SRC)); } - protected static Bitmap.Config getInternalFormat( Pixmap.Format format ) - { - if( format == Pixmap.Format.Alpha ) - return Bitmap.Config.ALPHA_8; - if( format == Pixmap.Format.RGBA4444 ) - return Bitmap.Config.ARGB_4444; - if( format == Pixmap.Format.RGB565 ) - return Bitmap.Config.RGB_565; + protected static Bitmap.Config getInternalFormat (Pixmap.Format format) { + if (format == Pixmap.Format.Alpha) return Bitmap.Config.ALPHA_8; + if (format == Pixmap.Format.RGBA4444) return Bitmap.Config.ARGB_4444; + if (format == Pixmap.Format.RGB565) return Bitmap.Config.RGB_565; return Bitmap.Config.ARGB_8888; } - + /** * {@inheritDoc} */ - @Override - public void drawCircle(int x, int y, int radius) - { - if( canvas == null ) - return; + @Override public void drawCircle (int x, int y, int radius) { + if (canvas == null) return; paint.setStyle(Style.STROKE); - canvas.drawCircle( x + radius, y + radius, radius, paint ); + canvas.drawCircle(x + radius, y + radius, radius, paint); paint.setStyle(Style.FILL); } /** * {@inheritDoc} */ - @Override - public void drawLine(int x, int y, int x2, int y2) - { - if( canvas == null ) - return; - canvas.drawLine( x, y, x2, y2, paint ); + @Override public void drawLine (int x, int y, int x2, int y2) { + if (canvas == null) return; + canvas.drawLine(x, y, x2, y2, paint); } /** * {@inheritDoc} */ - @Override - public void drawRectangle(int x, int y, int width, int height) - { - if( canvas == null ) - return; + @Override public void drawRectangle (int x, int y, int width, int height) { + if (canvas == null) return; paint.setStyle(Style.STROKE); - canvas.drawRect( x, y, x + width, y + height, paint ); + canvas.drawRect(x, y, x + width, y + height, paint); paint.setStyle(Style.FILL); } /** * {@inheritDoc} */ - @Override - public void fill() - { - if( canvas == null ) - return; + @Override public void fill () { + if (canvas == null) return; fillRectangle(0, 0, pixmap.getWidth(), pixmap.getHeight()); } /** * {@inheritDoc} */ - @Override - public void fillCircle(int x, int y, int radius) - { - if( canvas == null ) - return; - canvas.drawCircle( x + radius, y + radius, radius, paint ); + @Override public void fillCircle (int x, int y, int radius) { + if (canvas == null) return; + canvas.drawCircle(x + radius, y + radius, radius, paint); } /** * {@inheritDoc} */ - @Override - public void fillRectangle(int x, int y, int width, int height) - { - if( canvas == null ) - return; - canvas.drawRect( x, y, x + width, y + height, paint ); + @Override public void fillRectangle (int x, int y, int width, int height) { + if (canvas == null) return; + canvas.drawRect(x, y, x + width, y + height, paint); } /** * {@inheritDoc} */ - @Override - public Object getNativePixmap() - { + @Override public Object getNativePixmap () { return pixmap; } /** * {@inheritDoc} */ - @Override - public void setColor(float r, float g, float b, float a) - { + @Override public void setColor (float r, float g, float b, float a) { this.r = (int)(255 * r); this.g = (int)(255 * g); this.b = (int)(255 * b); this.a = (int)(255 * a); - - paint.setColor( this.a << 24 | this.r << 16 | this.g << 8 | this.b ); + + paint.setColor(this.a << 24 | this.r << 16 | this.g << 8 | this.b); } /** * {@inheritDoc} */ - @Override - public void setStrokeWidth(int width) - { - paint.setStrokeWidth( width ); + @Override public void setStrokeWidth (int width) { + paint.setStrokeWidth(width); } /** * {@inheritDoc} */ - @Override - public int getPixel(int x, int y) - { - if( x < 0 || x >= pixmap.getWidth() ) - return 0; - if( y < 0 || y >= pixmap.getHeight() ) - return 0; + @Override public int getPixel (int x, int y) { + if (x < 0 || x >= pixmap.getWidth()) return 0; + if (y < 0 || y >= pixmap.getHeight()) return 0; return pixmap.getPixel(x, y); } /** * {@inheritDoc} */ - @Override - public int getHeight() - { + @Override public int getHeight () { return pixmap.getHeight(); } /** * {@inheritDoc} */ - @Override - public int getWidth() { + @Override public int getWidth () { return pixmap.getWidth(); } - Rect src = new Rect( ); - RectF dst = new RectF( ); + Rect src = new Rect(); + RectF dst = new RectF(); + /** * {@inheritDoc} */ - @Override - public void drawPixmap(Pixmap pixmap, int x, int y, int srcx, int srcy, - int width, int height) - { - if( canvas == null ) - return; - - dst.set( x, y, x + width, y + height ); - src.set( srcx, srcy, srcx + width, srcy + height ); - + @Override public void drawPixmap (Pixmap pixmap, int x, int y, int srcx, int srcy, int width, int height) { + if (canvas == null) return; + + dst.set(x, y, x + width, y + height); + src.set(srcx, srcy, srcx + width, srcy + height); + canvas.drawBitmap((Bitmap)pixmap.getNativePixmap(), src, dst, null); - + } /** * {@inheritDoc} */ - @Override - public void dispose() { + @Override public void dispose () { pixmap.recycle(); pixmap = null; } @@ -241,10 +195,8 @@ final class AndroidPixmap implements Pixmap /** * {@inheritDoc} */ - @Override - public void getPixelRow(int[] pixels, int y) - { - pixmap.getPixels( pixels, 0, pixmap.getWidth(), 0, y, pixmap.getWidth(), 1 ); + @Override public void getPixelRow (int[] pixels, int y) { + pixmap.getPixels(pixels, 0, pixmap.getWidth(), 0, y, pixmap.getWidth(), 1); } } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidSingleTouchHandler.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidSingleTouchHandler.java index a0ba6762f..a44e334cb 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidSingleTouchHandler.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidSingleTouchHandler.java @@ -1,70 +1,60 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; +import android.view.MotionEvent; + import com.badlogic.gdx.backends.android.AndroidInput.Event; import com.badlogic.gdx.backends.android.AndroidInput.EventType; -import android.view.MotionEvent; - /** * Single touch handler for devices running <= 1.6 * * @author badlogicgames@gmail.com - * + * */ -public class AndroidSingleTouchHandler implements AndroidTouchHandler -{ - public void onTouch( MotionEvent event, AndroidInput input ) - { +public class AndroidSingleTouchHandler implements AndroidTouchHandler { + public void onTouch (MotionEvent event, AndroidInput input) { int x = (int)event.getX(); int y = (int)event.getY(); input.touchX[0] = x; input.touchY[0] = y; - if( event.getAction() == MotionEvent.ACTION_DOWN ) - { - postTouchEvent(input, EventType.MouseDown, x, y, 0 ); + if (event.getAction() == MotionEvent.ACTION_DOWN) { + postTouchEvent(input, EventType.MouseDown, x, y, 0); input.touched[0] = true; } - - if( event.getAction() == MotionEvent.ACTION_MOVE ) - { - postTouchEvent(input, EventType.MouseDragged, x, y, 0 ); - input.touched[0] = true; + + if (event.getAction() == MotionEvent.ACTION_MOVE) { + postTouchEvent(input, EventType.MouseDragged, x, y, 0); + input.touched[0] = true; } - if( event.getAction() == MotionEvent.ACTION_UP ) - { - postTouchEvent(input, EventType.MouseUp, x, y, 0 ); - input.touched[0] = false; + if (event.getAction() == MotionEvent.ACTION_UP) { + postTouchEvent(input, EventType.MouseUp, x, y, 0); + input.touched[0] = false; } - - if( event.getAction() == MotionEvent.ACTION_CANCEL ) - { - postTouchEvent(input, EventType.MouseUp, x, y, 0 ); - input.touched[0] = false; + + if (event.getAction() == MotionEvent.ACTION_CANCEL) { + postTouchEvent(input, EventType.MouseUp, x, y, 0); + input.touched[0] = false; } } - - private void postTouchEvent( AndroidInput input, EventType type, int x, int y, int pointer ) - { - synchronized( input.eventQueue ) - { + + private void postTouchEvent (AndroidInput input, EventType type, int x, int y, int pointer) { + synchronized (input.eventQueue) { Event ev = input.freeEvents.get(input.freeEventIndex++); - ev.set( type, x, y, pointer, 0, '\0' ); - input.eventQueue.add( ev ); - } + ev.set(type, x, y, pointer, 0, '\0'); + input.eventQueue.add(ev); + } } } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidSound.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidSound.java index 11ea64914..2160e3c38 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidSound.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidSound.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import android.media.AudioManager; @@ -20,36 +18,28 @@ import android.media.SoundPool; import com.badlogic.gdx.audio.Sound; -final class AndroidSound implements Sound -{ +final class AndroidSound implements Sound { final SoundPool soundPool; final AudioManager manager; final int soundId; - - AndroidSound( SoundPool pool, AudioManager manager, int soundId ) - { + + AndroidSound (SoundPool pool, AudioManager manager, int soundId) { this.soundPool = pool; this.manager = manager; this.soundId = soundId; } - - @Override - public void dispose() - { - soundPool.unload( soundId ); + + @Override public void dispose () { + soundPool.unload(soundId); } - @Override - public void play() - { - play( 1 ); + @Override public void play () { + play(1); } - @Override - public void play(float volume) - { + @Override public void play (float volume) { int streamVolume = manager.getStreamVolume(AudioManager.STREAM_MUSIC); - soundPool.play( soundId, streamVolume * volume, streamVolume * volume, 1, 0, 1 ); + soundPool.play(soundId, streamVolume * volume, streamVolume * volume, 1, 0, 1); } - + } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidTexture.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidTexture.java index 9f8ad5727..d953d6225 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidTexture.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidTexture.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import java.nio.ByteBuffer; @@ -27,8 +25,6 @@ import android.util.Log; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.GdxRuntimeException; import com.badlogic.gdx.graphics.GL10; -import com.badlogic.gdx.graphics.GL11; -import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; @@ -36,18 +32,17 @@ import com.badlogic.gdx.graphics.Texture; * An implementation of {@link Texture} for Android * * @author badlogicgames@gmail.com - * + * */ -final class AndroidTexture implements Texture -{ +final class AndroidTexture implements Texture { /** list of currently active textures used to invalidate them in case the surface was lost **/ - private static final ArrayList textures = new ArrayList( ); + private static final ArrayList textures = new ArrayList(); /** the texture handle **/ private int textureHandle; /** height in pixels of texture **/ private int texHeight; /** width in pixels of texture **/ - private int texWidth; + private int texWidth; /** whether this texture is managed **/ private final boolean isManaged; /** the managed pixmap **/ @@ -61,9 +56,9 @@ final class AndroidTexture implements Texture /** the u wrap **/ private final TextureWrap uWrap; /** the v wrap **/ - private final TextureWrap vWrap; + private final TextureWrap vWrap; /** invalidate flag **/ - private boolean invalidated = false; + private boolean invalidated = false; /** file handle **/ private AndroidFileHandle file; @@ -73,8 +68,8 @@ final class AndroidTexture implements Texture * @param gl * @param bitmap */ - AndroidTexture( AndroidGraphics graphics, Bitmap image, TextureFilter minFilter, TextureFilter maxFilter, TextureWrap uWrap, TextureWrap vWrap, boolean managed, AndroidFileHandle file ) - { + AndroidTexture (AndroidGraphics graphics, Bitmap image, TextureFilter minFilter, TextureFilter maxFilter, TextureWrap uWrap, + TextureWrap vWrap, boolean managed, AndroidFileHandle file) { this.file = file; this.isManaged = managed; this.bitmap = image; @@ -82,163 +77,140 @@ final class AndroidTexture implements Texture this.magFilter = maxFilter; this.uWrap = uWrap; this.vWrap = vWrap; - if( image != null ) - { + if (image != null) { this.texWidth = image.getWidth(); - this.texHeight = image.getHeight(); + this.texHeight = image.getHeight(); } - if( minFilter == TextureFilter.MipMap ) + if (minFilter == TextureFilter.MipMap) isMipMap = true; else isMipMap = false; - createTexture( ); - buildMipmap( ); - Gdx.gl.glBindTexture( GL10.GL_TEXTURE_2D, 0 ); + createTexture(); + buildMipmap(); + Gdx.gl.glBindTexture(GL10.GL_TEXTURE_2D, 0); bitmap = null; - if( isManaged ) - textures.add( this ); - } + if (isManaged) textures.add(this); + } - private void rebuild( ) - { - createTexture( ); - buildMipmap( ); + private void rebuild () { + createTexture(); + buildMipmap(); invalidated = false; } - private void createTexture( ) - { + private void createTexture () { ByteBuffer buffer = ByteBuffer.allocateDirect(4); buffer.order(ByteOrder.nativeOrder()); IntBuffer intBuffer = buffer.asIntBuffer(); Gdx.gl.glGenTextures(1, intBuffer); - textureHandle = intBuffer.get(0); + textureHandle = intBuffer.get(0); - Gdx.gl.glBindTexture( GL10.GL_TEXTURE_2D, textureHandle ); - Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, getTextureFilter( minFilter ) ); - Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, getTextureFilter( magFilter ) ); - Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, getTextureWrap( uWrap ) ); - Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, getTextureWrap( vWrap ) ); + Gdx.gl.glBindTexture(GL10.GL_TEXTURE_2D, textureHandle); + Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, getTextureFilter(minFilter)); + Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, getTextureFilter(magFilter)); + Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, getTextureWrap(uWrap)); + Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, getTextureWrap(vWrap)); } - private int getTextureFilter( TextureFilter filter ) - { - if( filter == TextureFilter.Linear ) + private int getTextureFilter (TextureFilter filter) { + if (filter == TextureFilter.Linear) return GL10.GL_LINEAR; + else if (filter == TextureFilter.Nearest) + return GL10.GL_NEAREST; else - if( filter == TextureFilter.Nearest ) - return GL10.GL_NEAREST; - else - return GL10.GL_LINEAR_MIPMAP_NEAREST; + return GL10.GL_LINEAR_MIPMAP_NEAREST; } - private int getTextureWrap( TextureWrap wrap ) - { - if( wrap == TextureWrap.ClampToEdge ) + private int getTextureWrap (TextureWrap wrap) { + if (wrap == TextureWrap.ClampToEdge) return GL10.GL_CLAMP_TO_EDGE; else return GL10.GL_REPEAT; } - private Bitmap loadBitmap( AndroidFileHandle file ) - { - Pixmap pixmap = Gdx.graphics.newPixmap( file ); + private Bitmap loadBitmap (AndroidFileHandle file) { + Pixmap pixmap = Gdx.graphics.newPixmap(file); Bitmap image = (Bitmap)pixmap.getNativePixmap(); this.texWidth = image.getWidth(); - this.texHeight = image.getHeight(); + this.texHeight = image.getHeight(); return (Bitmap)pixmap.getNativePixmap(); } - private static boolean isPowerOfTwo( int value ) - { - return ((value!=0) && (value&(value-1))==0); + private static boolean isPowerOfTwo (int value) { + return ((value != 0) && (value & (value - 1)) == 0); } - private void buildMipmap( ) - { - Bitmap obitmap = null; - if( file != null ) - obitmap = loadBitmap( file ); + private void buildMipmap () { + Bitmap obitmap = null; + if (file != null) + obitmap = loadBitmap(file); else obitmap = this.bitmap; Bitmap bitmap = obitmap; int level = 0; int height = bitmap.getHeight(); - int width = bitmap.getWidth(); - Log.d( "texture", "creating texture mipmaps: " + bitmap.getWidth() + ", " + bitmap.getHeight() ); + int width = bitmap.getWidth(); + Log.d("texture", "creating texture mipmaps: " + bitmap.getWidth() + ", " + bitmap.getHeight()); - if( !isPowerOfTwo( bitmap.getWidth() ) || !isPowerOfTwo( bitmap.getHeight() ) ) - throw new GdxRuntimeException( "Dimensions have to be a power of two" ); + if (!isPowerOfTwo(bitmap.getWidth()) || !isPowerOfTwo(bitmap.getHeight())) + throw new GdxRuntimeException("Dimensions have to be a power of two"); - while(height >= 1 || width >= 1 && level < 4 ) { - GLUtils.texImage2D(GL10.GL_TEXTURE_2D, level, bitmap, 0); - if(height == 1 || width == 1 || isMipMap == false ) - { + while (height >= 1 || width >= 1 && level < 4) { + GLUtils.texImage2D(GL10.GL_TEXTURE_2D, level, bitmap, 0); + if (height == 1 || width == 1 || isMipMap == false) { break; } level++; - if( height > 1 ) - height /= 2; - if( width > 1 ) - width /= 2; + if (height > 1) height /= 2; + if (width > 1) width /= 2; Bitmap bitmap2 = Bitmap.createScaledBitmap(bitmap, width, height, true); - if( level > 1 ) - bitmap.recycle(); + if (level > 1) bitmap.recycle(); bitmap = bitmap2; - } + } - if( file != null ) - obitmap.recycle(); + if (file != null) obitmap.recycle(); } - public boolean isManaged( ) - { + public boolean isManaged () { return isManaged; } /** * {@inheritDoc} */ - public void draw( Pixmap bmp, int x, int y ) - { - if( isManaged ) - throw new GdxRuntimeException( "Can't draw to a managed texture!" ); + public void draw (Pixmap bmp, int x, int y) { + if (isManaged) throw new GdxRuntimeException("Can't draw to a managed texture!"); - if( isManaged && invalidated ) - rebuild( ); + if (isManaged && invalidated) rebuild(); - Gdx.gl.glBindTexture( GL10.GL_TEXTURE_2D, textureHandle ); + Gdx.gl.glBindTexture(GL10.GL_TEXTURE_2D, textureHandle); Bitmap bitmap = (Bitmap)bmp.getNativePixmap(); int level = 0; int height = bitmap.getHeight(); - int width = bitmap.getWidth(); + int width = bitmap.getWidth(); - while(height >= 1 || width >= 1 && level < 4 ) { - GLUtils.texSubImage2D( GL10.GL_TEXTURE_2D, level, x, y, bitmap ); + while (height >= 1 || width >= 1 && level < 4) { + GLUtils.texSubImage2D(GL10.GL_TEXTURE_2D, level, x, y, bitmap); - if(height == 1 || width == 1 || isMipMap == false ) - { + if (height == 1 || width == 1 || isMipMap == false) { break; } level++; - if( height > 1 ) - height /= 2; - if( width > 1 ) - width /= 2; + if (height > 1) height /= 2; + if (width > 1) width /= 2; Bitmap bitmap2 = Bitmap.createScaledBitmap(bitmap, width, height, true); - if( level > 1 ) - bitmap.recycle(); + if (level > 1) bitmap.recycle(); bitmap = bitmap2; - } + } } static Texture lastTexture = null; @@ -246,113 +218,99 @@ final class AndroidTexture implements Texture /** * {@inheritDoc} */ - public void bind( ) - { - if( isManaged && invalidated ) - { - rebuild( ); + public void bind () { + if (isManaged && invalidated) { + rebuild(); lastTexture = null; } - if( lastTexture != this ) - { + if (lastTexture != this) { lastTexture = this; - Gdx.gl.glBindTexture( GL10.GL_TEXTURE_2D, textureHandle ); + Gdx.gl.glBindTexture(GL10.GL_TEXTURE_2D, textureHandle); } } /** * {@inheritDoc} */ - @Override - public void dispose( ) - { -// if( gl10 != null ) -// { -// if( gl10 instanceof GL11 ) -// { -// GL11 gl11 = (GL11)gl10; -// if( gl11.glIsTexture( textureHandle ) ) -// { -// int[] textures = { textureHandle }; -// gl10.glDeleteTextures( 1, textures, 0 ); -// } -// } -// else -// { -// int[] textures = { textureHandle }; -// gl10.glDeleteTextures( 1, textures, 0 ); -// } -// } -// else -// { -// if( gl20.glIsTexture( textureHandle ) ) -// { -// ByteBuffer buffer = ByteBuffer.allocateDirect(4); -// buffer.order(ByteOrder.nativeOrder()); -// IntBuffer intBuffer = buffer.asIntBuffer(); -// intBuffer.put(textureHandle); -// intBuffer.position(0); -// gl20.glDeleteTextures( 1, intBuffer); -// } -// } + @Override public void dispose () { +// if( gl10 != null ) +// { +// if( gl10 instanceof GL11 ) +// { +// GL11 gl11 = (GL11)gl10; +// if( gl11.glIsTexture( textureHandle ) ) +// { +// int[] textures = { textureHandle }; +// gl10.glDeleteTextures( 1, textures, 0 ); +// } +// } +// else +// { +// int[] textures = { textureHandle }; +// gl10.glDeleteTextures( 1, textures, 0 ); +// } +// } +// else +// { +// if( gl20.glIsTexture( textureHandle ) ) +// { +// ByteBuffer buffer = ByteBuffer.allocateDirect(4); +// buffer.order(ByteOrder.nativeOrder()); +// IntBuffer intBuffer = buffer.asIntBuffer(); +// intBuffer.put(textureHandle); +// intBuffer.position(0); +// gl20.glDeleteTextures( 1, intBuffer); +// } +// } ByteBuffer buffer = ByteBuffer.allocateDirect(4); buffer.order(ByteOrder.nativeOrder()); IntBuffer intBuffer = buffer.asIntBuffer(); intBuffer.put(textureHandle); intBuffer.position(0); - Gdx.gl.glDeleteTextures( 1, intBuffer); - textureHandle = 0; - if( bitmap != null ) - { + Gdx.gl.glDeleteTextures(1, intBuffer); + textureHandle = 0; + if (bitmap != null) { bitmap.recycle(); bitmap = null; } - textures.remove( this ); + textures.remove(this); } /** * {@inheritDoc} */ - @Override - public int getHeight() { + @Override public int getHeight () { return texHeight; } /** * {@inheritDoc} */ - @Override - public int getWidth() { + @Override public int getWidth () { return texWidth; } /** * {@inheritDoc} */ - @Override - public int getTextureObjectHandle() - { + @Override public int getTextureObjectHandle () { return textureHandle; } - public static void invalidateAllTextures( ) - { - for( int i = 0; i < textures.size(); i++ ) - { - if( textures.get(i).isManaged ) - { + public static void invalidateAllTextures () { + for (int i = 0; i < textures.size(); i++) { + if (textures.get(i).isManaged) { AndroidTexture texture = textures.get(i); texture.invalidated = true; - texture.rebuild( ); + texture.rebuild(); } } lastTexture = null; } - public static void clearAllTextures( ) - { + public static void clearAllTextures () { textures.clear(); lastTexture = null; } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidTouchHandler.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidTouchHandler.java index bcd647fd9..6d2d295bb 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidTouchHandler.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidTouchHandler.java @@ -1,23 +1,20 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import android.view.MotionEvent; -public interface AndroidTouchHandler -{ - public void onTouch( MotionEvent event, AndroidInput input ); +public interface AndroidTouchHandler { + public void onTouch (MotionEvent event, AndroidInput input); } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/EGLLogWrapper.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/EGLLogWrapper.java index c44a79f6d..bd0897d5c 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/EGLLogWrapper.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/EGLLogWrapper.java @@ -1,18 +1,16 @@ /* * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. */ + package com.badlogic.gdx.backends.android.surfaceview; import java.io.IOException; @@ -27,534 +25,511 @@ import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; class EGLLogWrapper implements EGL11 { - private EGL10 mEgl10; - Writer mLog; - boolean mLogArgumentNames; - boolean mCheckError; - private int mArgCount; - - - public EGLLogWrapper(EGL egl, int configFlags, Writer log) { - mEgl10 = (EGL10) egl; - mLog = log; - mLogArgumentNames = - (GLDebugHelper.CONFIG_LOG_ARGUMENT_NAMES & configFlags) != 0; - mCheckError = - (GLDebugHelper.CONFIG_CHECK_GL_ERROR & configFlags) != 0; - } - - public boolean eglChooseConfig(EGLDisplay display, int[] attrib_list, - EGLConfig[] configs, int config_size, int[] num_config) { - begin("eglChooseConfig"); - arg("display", display); - arg("attrib_list", attrib_list); - arg("config_size", config_size); - end(); - - boolean result = mEgl10.eglChooseConfig(display, attrib_list, configs, - config_size, num_config); - arg("configs", configs); - arg("num_config", num_config); - returns(result); - checkError(); - return result; - } - - public boolean eglCopyBuffers(EGLDisplay display, EGLSurface surface, - Object native_pixmap) { - begin("eglCopyBuffers"); - arg("display", display); - arg("surface", surface); - arg("native_pixmap", native_pixmap); - end(); - - boolean result = mEgl10.eglCopyBuffers(display, surface, native_pixmap); - returns(result); - checkError(); - return result; - } - - public EGLContext eglCreateContext(EGLDisplay display, EGLConfig config, - EGLContext share_context, int[] attrib_list) { - begin("eglCreateContext"); - arg("display", display); - arg("config", config); - arg("share_context", share_context); - arg("attrib_list", attrib_list); - end(); - - EGLContext result = mEgl10.eglCreateContext(display, config, - share_context, attrib_list); - returns(result); - checkError(); - return result; - } - - public EGLSurface eglCreatePbufferSurface(EGLDisplay display, - EGLConfig config, int[] attrib_list) { - begin("eglCreatePbufferSurface"); - arg("display", display); - arg("config", config); - arg("attrib_list", attrib_list); - end(); - - EGLSurface result = mEgl10.eglCreatePbufferSurface(display, config, - attrib_list); - returns(result); - checkError(); - return result; - } - - public EGLSurface eglCreatePixmapSurface(EGLDisplay display, - EGLConfig config, Object native_pixmap, int[] attrib_list) { - begin("eglCreatePixmapSurface"); - arg("display", display); - arg("config", config); - arg("native_pixmap", native_pixmap); - arg("attrib_list", attrib_list); - end(); - - EGLSurface result = mEgl10.eglCreatePixmapSurface(display, config, - native_pixmap, attrib_list); - returns(result); - checkError(); - return result; - } - - public EGLSurface eglCreateWindowSurface(EGLDisplay display, - EGLConfig config, Object native_window, int[] attrib_list) { - begin("eglCreateWindowSurface"); - arg("display", display); - arg("config", config); - arg("native_window", native_window); - arg("attrib_list", attrib_list); - end(); - - EGLSurface result = mEgl10.eglCreateWindowSurface(display, config, - native_window, attrib_list); - returns(result); - checkError(); - return result; - } - - public boolean eglDestroyContext(EGLDisplay display, EGLContext context) { - begin("eglDestroyContext"); - arg("display", display); - arg("context", context); - end(); - - boolean result = mEgl10.eglDestroyContext(display, context); - returns(result); - checkError(); - return result; - } - - public boolean eglDestroySurface(EGLDisplay display, EGLSurface surface) { - begin("eglDestroySurface"); - arg("display", display); - arg("surface", surface); - end(); - - boolean result = mEgl10.eglDestroySurface(display, surface); - returns(result); - checkError(); - return result; - } - - public boolean eglGetConfigAttrib(EGLDisplay display, EGLConfig config, - int attribute, int[] value) { - begin("eglGetConfigAttrib"); - arg("display", display); - arg("config", config); - arg("attribute", attribute); - end(); - boolean result = mEgl10.eglGetConfigAttrib(display, config, attribute, - value); - arg("value", value); - returns(result); - checkError(); - return false; - } - - public boolean eglGetConfigs(EGLDisplay display, EGLConfig[] configs, - int config_size, int[] num_config) { - begin("eglGetConfigs"); - arg("display", display); - arg("config_size", config_size); - end(); - - boolean result = mEgl10.eglGetConfigs(display, configs, config_size, - num_config); - arg("configs", configs); - arg("num_config", num_config); - returns(result); - checkError(); - return result; - } - - public EGLContext eglGetCurrentContext() { - begin("eglGetCurrentContext"); - end(); - - EGLContext result = mEgl10.eglGetCurrentContext(); - returns(result); - - checkError(); - return result; - } - - public EGLDisplay eglGetCurrentDisplay() { - begin("eglGetCurrentDisplay"); - end(); - - EGLDisplay result = mEgl10.eglGetCurrentDisplay(); - returns(result); - - checkError(); - return result; - } - - public EGLSurface eglGetCurrentSurface(int readdraw) { - begin("eglGetCurrentSurface"); - arg("readdraw", readdraw); - end(); - - EGLSurface result = mEgl10.eglGetCurrentSurface(readdraw); - returns(result); - - checkError(); - return result; - } - - public EGLDisplay eglGetDisplay(Object native_display) { - begin("eglGetDisplay"); - arg("native_display", native_display); - end(); - - EGLDisplay result = mEgl10.eglGetDisplay(native_display); - returns(result); - - checkError(); - return result; - } - - public int eglGetError() { - begin("eglGetError"); - end(); - - int result = mEgl10.eglGetError(); - returns(getErrorString(result)); - - return result; - } - - public boolean eglInitialize(EGLDisplay display, int[] major_minor) { - begin("eglInitialize"); - arg("display", display); - end(); - boolean result = mEgl10.eglInitialize(display, major_minor); - returns(result); - arg("major_minor", major_minor); - checkError(); - return result; - } - - public boolean eglMakeCurrent(EGLDisplay display, EGLSurface draw, - EGLSurface read, EGLContext context) { - begin("eglMakeCurrent"); - arg("display", display); - arg("draw", draw); - arg("read", read); - arg("context", context); - end(); - boolean result = mEgl10.eglMakeCurrent(display, draw, read, context); - returns(result); - checkError(); - return result; - } - - public boolean eglQueryContext(EGLDisplay display, EGLContext context, - int attribute, int[] value) { - begin("eglQueryContext"); - arg("display", display); - arg("context", context); - arg("attribute", attribute); - end(); - boolean result = mEgl10.eglQueryContext(display, context, attribute, - value); - returns(value[0]); - returns(result); - checkError(); - return result; - } - - public String eglQueryString(EGLDisplay display, int name) { - begin("eglQueryString"); - arg("display", display); - arg("name", name); - end(); - String result = mEgl10.eglQueryString(display, name); - returns(result); - checkError(); - return result; - } - - public boolean eglQuerySurface(EGLDisplay display, EGLSurface surface, - int attribute, int[] value) { - begin("eglQuerySurface"); - arg("display", display); - arg("surface", surface); - arg("attribute", attribute); - end(); - boolean result = mEgl10.eglQuerySurface(display, surface, attribute, - value); - returns(value[0]); - returns(result); - checkError(); - return result; - } - - public boolean eglSwapBuffers(EGLDisplay display, EGLSurface surface) { - begin("eglInitialize"); - arg("display", display); - arg("surface", surface); - end(); - boolean result = mEgl10.eglSwapBuffers(display, surface); - returns(result); - checkError(); - return result; - } - - public boolean eglTerminate(EGLDisplay display) { - begin("eglTerminate"); - arg("display", display); - end(); - boolean result = mEgl10.eglTerminate(display); - returns(result); - checkError(); - return result; - } - - public boolean eglWaitGL() { - begin("eglWaitGL"); - end(); - boolean result = mEgl10.eglWaitGL(); - returns(result); - checkError(); - return result; - } - - public boolean eglWaitNative(int engine, Object bindTarget) { - begin("eglWaitNative"); - arg("engine", engine); - arg("bindTarget", bindTarget); - end(); - boolean result = mEgl10.eglWaitNative(engine, bindTarget); - returns(result); - checkError(); - return result; - } - - private void checkError() { - int eglError; - if ((eglError = mEgl10.eglGetError()) != EGL_SUCCESS) { - String errorMessage = "eglError: " + getErrorString(eglError); - logLine(errorMessage); - if (mCheckError) { - throw new GLException(eglError, errorMessage); - } - } - } - - private void logLine(String message) { - log(message + '\n'); - } - - private void log(String message) { - try { - mLog.write(message); - } catch (IOException e) { - // Ignore exception, keep on trying - } - } - - private void begin(String name) { - log(name + '('); - mArgCount = 0; - } - - private void arg(String name, String value) { - if (mArgCount++ > 0) { - log(", "); - } - if (mLogArgumentNames) { - log(name + "="); - } - log(value); - } - - private void end() { - log(");\n"); - flush(); - } - - private void flush() { - try { - mLog.flush(); - } catch (IOException e) { - mLog = null; - } - } - - private void arg(String name, int value) { - arg(name, Integer.toString(value)); - } - - private void arg(String name, Object object) { - arg(name, toString(object)); - } - - private void arg(String name, EGLDisplay object) { - if (object == EGL10.EGL_DEFAULT_DISPLAY) { - arg(name, "EGL10.EGL_DEFAULT_DISPLAY"); - } else if (object == EGL_NO_DISPLAY) { - arg(name, "EGL10.EGL_NO_DISPLAY"); - } else { - arg(name, toString(object)); - } - } - - private void arg(String name, EGLContext object) { - if (object == EGL10.EGL_NO_CONTEXT) { - arg(name, "EGL10.EGL_NO_CONTEXT"); - } else { - arg(name, toString(object)); - } - } - - private void arg(String name, EGLSurface object) { - if (object == EGL10.EGL_NO_SURFACE) { - arg(name, "EGL10.EGL_NO_SURFACE"); - } else { - arg(name, toString(object)); - } - } - - private void returns(String result) { - log(" returns " + result + ";\n"); - flush(); - } - - private void returns(int result) { - returns(Integer.toString(result)); - } - - private void returns(boolean result) { - returns(Boolean.toString(result)); - } - - private void returns(Object result) { - returns(toString(result)); - } - - private String toString(Object obj) { - if (obj == null) { - return "null"; - } else { - return obj.toString(); - } - } - - private void arg(String name, int[] arr) { - if (arr == null) { - arg(name, "null"); - } else { - arg(name, toString(arr.length, arr, 0)); - } - } - - private void arg(String name, Object[] arr) { - if (arr == null) { - arg(name, "null"); - } else { - arg(name, toString(arr.length, arr, 0)); - } - } - - private String toString(int n, int[] arr, int offset) { - StringBuilder buf = new StringBuilder(); - buf.append("{\n"); - int arrLen = arr.length; - for (int i = 0; i < n; i++) { - int index = offset + i; - buf.append(" [" + index + "] = "); - if (index < 0 || index >= arrLen) { - buf.append("out of bounds"); - } else { - buf.append(arr[index]); - } - buf.append('\n'); - } - buf.append("}"); - return buf.toString(); - } - - private String toString(int n, Object[] arr, int offset) { - StringBuilder buf = new StringBuilder(); - buf.append("{\n"); - int arrLen = arr.length; - for (int i = 0; i < n; i++) { - int index = offset + i; - buf.append(" [" + index + "] = "); - if (index < 0 || index >= arrLen) { - buf.append("out of bounds"); - } else { - buf.append(arr[index]); - } - buf.append('\n'); - } - buf.append("}"); - return buf.toString(); - } - - private static String getHex(int value) { - return "0x" + Integer.toHexString(value); - } - - public static String getErrorString(int error) { - switch (error) { - case EGL_SUCCESS: - return "EGL_SUCCESS"; - case EGL_NOT_INITIALIZED: - return "EGL_NOT_INITIALIZED"; - case EGL_BAD_ACCESS: - return "EGL_BAD_ACCESS"; - case EGL_BAD_ALLOC: - return "EGL_BAD_ALLOC"; - case EGL_BAD_ATTRIBUTE: - return "EGL_BAD_ATTRIBUTE"; - case EGL_BAD_CONFIG: - return "EGL_BAD_CONFIG"; - case EGL_BAD_CONTEXT: - return "EGL_BAD_CONTEXT"; - case EGL_BAD_CURRENT_SURFACE: - return "EGL_BAD_CURRENT_SURFACE"; - case EGL_BAD_DISPLAY: - return "EGL_BAD_DISPLAY"; - case EGL_BAD_MATCH: - return "EGL_BAD_MATCH"; - case EGL_BAD_NATIVE_PIXMAP: - return "EGL_BAD_NATIVE_PIXMAP"; - case EGL_BAD_NATIVE_WINDOW: - return "EGL_BAD_NATIVE_WINDOW"; - case EGL_BAD_PARAMETER: - return "EGL_BAD_PARAMETER"; - case EGL_BAD_SURFACE: - return "EGL_BAD_SURFACE"; - case EGL11.EGL_CONTEXT_LOST: - return "EGL_CONTEXT_LOST"; - default: - return getHex(error); - } - } -} \ No newline at end of file + private EGL10 mEgl10; + Writer mLog; + boolean mLogArgumentNames; + boolean mCheckError; + private int mArgCount; + + public EGLLogWrapper (EGL egl, int configFlags, Writer log) { + mEgl10 = (EGL10)egl; + mLog = log; + mLogArgumentNames = (GLDebugHelper.CONFIG_LOG_ARGUMENT_NAMES & configFlags) != 0; + mCheckError = (GLDebugHelper.CONFIG_CHECK_GL_ERROR & configFlags) != 0; + } + + public boolean eglChooseConfig (EGLDisplay display, int[] attrib_list, EGLConfig[] configs, int config_size, int[] num_config) { + begin("eglChooseConfig"); + arg("display", display); + arg("attrib_list", attrib_list); + arg("config_size", config_size); + end(); + + boolean result = mEgl10.eglChooseConfig(display, attrib_list, configs, config_size, num_config); + arg("configs", configs); + arg("num_config", num_config); + returns(result); + checkError(); + return result; + } + + public boolean eglCopyBuffers (EGLDisplay display, EGLSurface surface, Object native_pixmap) { + begin("eglCopyBuffers"); + arg("display", display); + arg("surface", surface); + arg("native_pixmap", native_pixmap); + end(); + + boolean result = mEgl10.eglCopyBuffers(display, surface, native_pixmap); + returns(result); + checkError(); + return result; + } + + public EGLContext eglCreateContext (EGLDisplay display, EGLConfig config, EGLContext share_context, int[] attrib_list) { + begin("eglCreateContext"); + arg("display", display); + arg("config", config); + arg("share_context", share_context); + arg("attrib_list", attrib_list); + end(); + + EGLContext result = mEgl10.eglCreateContext(display, config, share_context, attrib_list); + returns(result); + checkError(); + return result; + } + + public EGLSurface eglCreatePbufferSurface (EGLDisplay display, EGLConfig config, int[] attrib_list) { + begin("eglCreatePbufferSurface"); + arg("display", display); + arg("config", config); + arg("attrib_list", attrib_list); + end(); + + EGLSurface result = mEgl10.eglCreatePbufferSurface(display, config, attrib_list); + returns(result); + checkError(); + return result; + } + + public EGLSurface eglCreatePixmapSurface (EGLDisplay display, EGLConfig config, Object native_pixmap, int[] attrib_list) { + begin("eglCreatePixmapSurface"); + arg("display", display); + arg("config", config); + arg("native_pixmap", native_pixmap); + arg("attrib_list", attrib_list); + end(); + + EGLSurface result = mEgl10.eglCreatePixmapSurface(display, config, native_pixmap, attrib_list); + returns(result); + checkError(); + return result; + } + + public EGLSurface eglCreateWindowSurface (EGLDisplay display, EGLConfig config, Object native_window, int[] attrib_list) { + begin("eglCreateWindowSurface"); + arg("display", display); + arg("config", config); + arg("native_window", native_window); + arg("attrib_list", attrib_list); + end(); + + EGLSurface result = mEgl10.eglCreateWindowSurface(display, config, native_window, attrib_list); + returns(result); + checkError(); + return result; + } + + public boolean eglDestroyContext (EGLDisplay display, EGLContext context) { + begin("eglDestroyContext"); + arg("display", display); + arg("context", context); + end(); + + boolean result = mEgl10.eglDestroyContext(display, context); + returns(result); + checkError(); + return result; + } + + public boolean eglDestroySurface (EGLDisplay display, EGLSurface surface) { + begin("eglDestroySurface"); + arg("display", display); + arg("surface", surface); + end(); + + boolean result = mEgl10.eglDestroySurface(display, surface); + returns(result); + checkError(); + return result; + } + + public boolean eglGetConfigAttrib (EGLDisplay display, EGLConfig config, int attribute, int[] value) { + begin("eglGetConfigAttrib"); + arg("display", display); + arg("config", config); + arg("attribute", attribute); + end(); + boolean result = mEgl10.eglGetConfigAttrib(display, config, attribute, value); + arg("value", value); + returns(result); + checkError(); + return false; + } + + public boolean eglGetConfigs (EGLDisplay display, EGLConfig[] configs, int config_size, int[] num_config) { + begin("eglGetConfigs"); + arg("display", display); + arg("config_size", config_size); + end(); + + boolean result = mEgl10.eglGetConfigs(display, configs, config_size, num_config); + arg("configs", configs); + arg("num_config", num_config); + returns(result); + checkError(); + return result; + } + + public EGLContext eglGetCurrentContext () { + begin("eglGetCurrentContext"); + end(); + + EGLContext result = mEgl10.eglGetCurrentContext(); + returns(result); + + checkError(); + return result; + } + + public EGLDisplay eglGetCurrentDisplay () { + begin("eglGetCurrentDisplay"); + end(); + + EGLDisplay result = mEgl10.eglGetCurrentDisplay(); + returns(result); + + checkError(); + return result; + } + + public EGLSurface eglGetCurrentSurface (int readdraw) { + begin("eglGetCurrentSurface"); + arg("readdraw", readdraw); + end(); + + EGLSurface result = mEgl10.eglGetCurrentSurface(readdraw); + returns(result); + + checkError(); + return result; + } + + public EGLDisplay eglGetDisplay (Object native_display) { + begin("eglGetDisplay"); + arg("native_display", native_display); + end(); + + EGLDisplay result = mEgl10.eglGetDisplay(native_display); + returns(result); + + checkError(); + return result; + } + + public int eglGetError () { + begin("eglGetError"); + end(); + + int result = mEgl10.eglGetError(); + returns(getErrorString(result)); + + return result; + } + + public boolean eglInitialize (EGLDisplay display, int[] major_minor) { + begin("eglInitialize"); + arg("display", display); + end(); + boolean result = mEgl10.eglInitialize(display, major_minor); + returns(result); + arg("major_minor", major_minor); + checkError(); + return result; + } + + public boolean eglMakeCurrent (EGLDisplay display, EGLSurface draw, EGLSurface read, EGLContext context) { + begin("eglMakeCurrent"); + arg("display", display); + arg("draw", draw); + arg("read", read); + arg("context", context); + end(); + boolean result = mEgl10.eglMakeCurrent(display, draw, read, context); + returns(result); + checkError(); + return result; + } + + public boolean eglQueryContext (EGLDisplay display, EGLContext context, int attribute, int[] value) { + begin("eglQueryContext"); + arg("display", display); + arg("context", context); + arg("attribute", attribute); + end(); + boolean result = mEgl10.eglQueryContext(display, context, attribute, value); + returns(value[0]); + returns(result); + checkError(); + return result; + } + + public String eglQueryString (EGLDisplay display, int name) { + begin("eglQueryString"); + arg("display", display); + arg("name", name); + end(); + String result = mEgl10.eglQueryString(display, name); + returns(result); + checkError(); + return result; + } + + public boolean eglQuerySurface (EGLDisplay display, EGLSurface surface, int attribute, int[] value) { + begin("eglQuerySurface"); + arg("display", display); + arg("surface", surface); + arg("attribute", attribute); + end(); + boolean result = mEgl10.eglQuerySurface(display, surface, attribute, value); + returns(value[0]); + returns(result); + checkError(); + return result; + } + + public boolean eglSwapBuffers (EGLDisplay display, EGLSurface surface) { + begin("eglInitialize"); + arg("display", display); + arg("surface", surface); + end(); + boolean result = mEgl10.eglSwapBuffers(display, surface); + returns(result); + checkError(); + return result; + } + + public boolean eglTerminate (EGLDisplay display) { + begin("eglTerminate"); + arg("display", display); + end(); + boolean result = mEgl10.eglTerminate(display); + returns(result); + checkError(); + return result; + } + + public boolean eglWaitGL () { + begin("eglWaitGL"); + end(); + boolean result = mEgl10.eglWaitGL(); + returns(result); + checkError(); + return result; + } + + public boolean eglWaitNative (int engine, Object bindTarget) { + begin("eglWaitNative"); + arg("engine", engine); + arg("bindTarget", bindTarget); + end(); + boolean result = mEgl10.eglWaitNative(engine, bindTarget); + returns(result); + checkError(); + return result; + } + + private void checkError () { + int eglError; + if ((eglError = mEgl10.eglGetError()) != EGL_SUCCESS) { + String errorMessage = "eglError: " + getErrorString(eglError); + logLine(errorMessage); + if (mCheckError) { + throw new GLException(eglError, errorMessage); + } + } + } + + private void logLine (String message) { + log(message + '\n'); + } + + private void log (String message) { + try { + mLog.write(message); + } catch (IOException e) { + // Ignore exception, keep on trying + } + } + + private void begin (String name) { + log(name + '('); + mArgCount = 0; + } + + private void arg (String name, String value) { + if (mArgCount++ > 0) { + log(", "); + } + if (mLogArgumentNames) { + log(name + "="); + } + log(value); + } + + private void end () { + log(");\n"); + flush(); + } + + private void flush () { + try { + mLog.flush(); + } catch (IOException e) { + mLog = null; + } + } + + private void arg (String name, int value) { + arg(name, Integer.toString(value)); + } + + private void arg (String name, Object object) { + arg(name, toString(object)); + } + + private void arg (String name, EGLDisplay object) { + if (object == EGL10.EGL_DEFAULT_DISPLAY) { + arg(name, "EGL10.EGL_DEFAULT_DISPLAY"); + } else if (object == EGL_NO_DISPLAY) { + arg(name, "EGL10.EGL_NO_DISPLAY"); + } else { + arg(name, toString(object)); + } + } + + private void arg (String name, EGLContext object) { + if (object == EGL10.EGL_NO_CONTEXT) { + arg(name, "EGL10.EGL_NO_CONTEXT"); + } else { + arg(name, toString(object)); + } + } + + private void arg (String name, EGLSurface object) { + if (object == EGL10.EGL_NO_SURFACE) { + arg(name, "EGL10.EGL_NO_SURFACE"); + } else { + arg(name, toString(object)); + } + } + + private void returns (String result) { + log(" returns " + result + ";\n"); + flush(); + } + + private void returns (int result) { + returns(Integer.toString(result)); + } + + private void returns (boolean result) { + returns(Boolean.toString(result)); + } + + private void returns (Object result) { + returns(toString(result)); + } + + private String toString (Object obj) { + if (obj == null) { + return "null"; + } else { + return obj.toString(); + } + } + + private void arg (String name, int[] arr) { + if (arr == null) { + arg(name, "null"); + } else { + arg(name, toString(arr.length, arr, 0)); + } + } + + private void arg (String name, Object[] arr) { + if (arr == null) { + arg(name, "null"); + } else { + arg(name, toString(arr.length, arr, 0)); + } + } + + private String toString (int n, int[] arr, int offset) { + StringBuilder buf = new StringBuilder(); + buf.append("{\n"); + int arrLen = arr.length; + for (int i = 0; i < n; i++) { + int index = offset + i; + buf.append(" [" + index + "] = "); + if (index < 0 || index >= arrLen) { + buf.append("out of bounds"); + } else { + buf.append(arr[index]); + } + buf.append('\n'); + } + buf.append("}"); + return buf.toString(); + } + + private String toString (int n, Object[] arr, int offset) { + StringBuilder buf = new StringBuilder(); + buf.append("{\n"); + int arrLen = arr.length; + for (int i = 0; i < n; i++) { + int index = offset + i; + buf.append(" [" + index + "] = "); + if (index < 0 || index >= arrLen) { + buf.append("out of bounds"); + } else { + buf.append(arr[index]); + } + buf.append('\n'); + } + buf.append("}"); + return buf.toString(); + } + + private static String getHex (int value) { + return "0x" + Integer.toHexString(value); + } + + public static String getErrorString (int error) { + switch (error) { + case EGL_SUCCESS: + return "EGL_SUCCESS"; + case EGL_NOT_INITIALIZED: + return "EGL_NOT_INITIALIZED"; + case EGL_BAD_ACCESS: + return "EGL_BAD_ACCESS"; + case EGL_BAD_ALLOC: + return "EGL_BAD_ALLOC"; + case EGL_BAD_ATTRIBUTE: + return "EGL_BAD_ATTRIBUTE"; + case EGL_BAD_CONFIG: + return "EGL_BAD_CONFIG"; + case EGL_BAD_CONTEXT: + return "EGL_BAD_CONTEXT"; + case EGL_BAD_CURRENT_SURFACE: + return "EGL_BAD_CURRENT_SURFACE"; + case EGL_BAD_DISPLAY: + return "EGL_BAD_DISPLAY"; + case EGL_BAD_MATCH: + return "EGL_BAD_MATCH"; + case EGL_BAD_NATIVE_PIXMAP: + return "EGL_BAD_NATIVE_PIXMAP"; + case EGL_BAD_NATIVE_WINDOW: + return "EGL_BAD_NATIVE_WINDOW"; + case EGL_BAD_PARAMETER: + return "EGL_BAD_PARAMETER"; + case EGL_BAD_SURFACE: + return "EGL_BAD_SURFACE"; + case EGL11.EGL_CONTEXT_LOST: + return "EGL_CONTEXT_LOST"; + default: + return getHex(error); + } + } +} diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLBaseSurfaceView.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLBaseSurfaceView.java index 9e0d229b3..39f79f43e 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLBaseSurfaceView.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLBaseSurfaceView.java @@ -1,17 +1,14 @@ /* * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. */ package com.badlogic.gdx.backends.android.surfaceview; @@ -30,42 +27,35 @@ import javax.microedition.khronos.opengles.GL10; import android.content.Context; import android.opengl.GLSurfaceView; -import android.opengl.GLSurfaceView.Renderer; import android.util.AttributeSet; import android.util.Log; import android.view.SurfaceHolder; /** - * An implementation of SurfaceView that uses the dedicated surface for - * displaying OpenGL rendering. + * An implementation of SurfaceView that uses the dedicated surface for displaying OpenGL rendering. *

* A GLSurfaceView provides the following features: *

*

    - *
  • Manages a surface, which is a special piece of memory that can be - * composited into the Android view system. + *
  • Manages a surface, which is a special piece of memory that can be composited into the Android view system. *
  • Manages an EGL display, which enables OpenGL to render into a surface. *
  • Accepts a user-provided Renderer object that does the actual rendering. - *
  • Renders on a dedicated thread to decouple rendering performance from the - * UI thread. + *
  • Renders on a dedicated thread to decouple rendering performance from the UI thread. *
  • Supports both on-demand and continuous rendering. *
  • Optionally wraps, traces, and/or error-checks the renderer's OpenGL calls. *
- * + * *

Using GLSurfaceView

*

- * Typically you use GLSurfaceView by subclassing it and overriding one or more of the - * View system input event methods. If your application does not need to override event - * methods then GLSurfaceView can be used as-is. For the most part - * GLSurfaceView behavior is customized by calling "set" methods rather than by subclassing. - * For example, unlike a regular View, drawing is delegated to a separate Renderer object which - * is registered with the GLSurfaceView - * using the {@link #setRenderer(Renderer)} call. + * Typically you use GLSurfaceView by subclassing it and overriding one or more of the View system input event methods. If your + * application does not need to override event methods then GLSurfaceView can be used as-is. For the most part GLSurfaceView + * behavior is customized by calling "set" methods rather than by subclassing. For example, unlike a regular View, drawing is + * delegated to a separate Renderer object which is registered with the GLSurfaceView using the {@link #setRenderer(Renderer)} + * call. *

*

Initializing GLSurfaceView

- * All you have to do to initialize a GLSurfaceView is call {@link #setRenderer(Renderer)}. - * However, if desired, you can modify the default behavior of GLSurfaceView by calling one or - * more of these methods before calling setRenderer: + * All you have to do to initialize a GLSurfaceView is call {@link #setRenderer(Renderer)}. However, if desired, you can modify + * the default behavior of GLSurfaceView by calling one or more of these methods before calling setRenderer: *
    *
  • {@link #setDebugFlags(int)} *
  • {@link #setEGLConfigChooser(boolean)} @@ -75,1205 +65,1117 @@ import android.view.SurfaceHolder; *
*

*

Choosing an EGL Configuration

- * A given Android device may support multiple possible types of drawing surfaces. - * The available surfaces may differ in how may channels of data are present, as - * well as how many bits are allocated to each channel. Therefore, the first thing - * GLSurfaceView has to do when starting to render is choose what type of surface to use. + * A given Android device may support multiple possible types of drawing surfaces. The available surfaces may differ in how may + * channels of data are present, as well as how many bits are allocated to each channel. Therefore, the first thing GLSurfaceView + * has to do when starting to render is choose what type of surface to use. *

- * By default GLSurfaceView chooses an available surface that's closest to a 16-bit R5G6B5 surface - * with a 16-bit depth buffer and no stencil. If you would prefer a different surface (for example, - * if you do not need a depth buffer) you can override the default behavior by calling one of the - * setEGLConfigChooser methods. + * By default GLSurfaceView chooses an available surface that's closest to a 16-bit R5G6B5 surface with a 16-bit depth buffer and + * no stencil. If you would prefer a different surface (for example, if you do not need a depth buffer) you can override the + * default behavior by calling one of the setEGLConfigChooser methods. *

*

Debug Behavior

- * You can optionally modify the behavior of GLSurfaceView by calling - * one or more of the debugging methods {@link #setDebugFlags(int)}, - * and {@link #setGLWrapper}. These methods may be called before and/or after setRenderer, but + * You can optionally modify the behavior of GLSurfaceView by calling one or more of the debugging methods + * {@link #setDebugFlags(int)}, and {@link #setGLWrapper}. These methods may be called before and/or after setRenderer, but * typically they are called before setRenderer so that they take effect immediately. *

*

Setting a Renderer

- * Finally, you must call {@link #setRenderer} to register a {@link Renderer}. - * The renderer is - * responsible for doing the actual OpenGL rendering. + * Finally, you must call {@link #setRenderer} to register a {@link Renderer}. The renderer is responsible for doing the actual + * OpenGL rendering. *

*

Rendering Mode

- * Once the renderer is set, you can control whether the renderer draws - * continuously or on-demand by calling + * Once the renderer is set, you can control whether the renderer draws continuously or on-demand by calling * {@link #setRenderMode}. The default is continuous rendering. *

*

Activity Life-cycle

- * A GLSurfaceView must be notified when the activity is paused and resumed. GLSurfaceView clients - * are required to call {@link #onPause()} when the activity pauses and - * {@link #onResume()} when the activity resumes. These calls allow GLSurfaceView to - * pause and resume the rendering thread, and also allow GLSurfaceView to release and recreate - * the OpenGL display. + * A GLSurfaceView must be notified when the activity is paused and resumed. GLSurfaceView clients are required to call + * {@link #onPause()} when the activity pauses and {@link #onResume()} when the activity resumes. These calls allow GLSurfaceView + * to pause and resume the rendering thread, and also allow GLSurfaceView to release and recreate the OpenGL display. *

*

Handling events

*

- * To handle an event you will typically subclass GLSurfaceView and override the - * appropriate method, just as you would with any other View. However, when handling - * the event, you may need to communicate with the Renderer object - * that's running in the rendering thread. You can do this using any - * standard Java cross-thread communication mechanism. In addition, - * one relatively easy way to communicate with your renderer is - * to call - * {@link #queueEvent(Runnable)}. For example: + * To handle an event you will typically subclass GLSurfaceView and override the appropriate method, just as you would with any + * other View. However, when handling the event, you may need to communicate with the Renderer object that's running in the + * rendering thread. You can do this using any standard Java cross-thread communication mechanism. In addition, one relatively + * easy way to communicate with your renderer is to call {@link #queueEvent(Runnable)}. For example: + * *

  * class MyGLSurfaceView extends GLSurfaceView {
- *
- *     private MyRenderer mMyRenderer;
- *
- *     public void start() {
+ * 
+ * 	private MyRenderer mMyRenderer;
+ * 
+ * 	public void start() {
  *         mMyRenderer = ...;
  *         setRenderer(mMyRenderer);
  *     }
- *
- *     public boolean onKeyDown(int keyCode, KeyEvent event) {
- *         if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
- *             queueEvent(new Runnable() {
- *                 // This method will be called on the rendering
- *                 // thread:
- *                 public void run() {
- *                     mMyRenderer.handleDpadCenter();
- *                 }});
- *             return true;
- *         }
- *         return super.onKeyDown(keyCode, event);
- *     }
+ * 
+ * 	public boolean onKeyDown (int keyCode, KeyEvent event) {
+ * 		if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
+ * 			queueEvent(new Runnable() {
+ * 				// This method will be called on the rendering
+ * 				// thread:
+ * 				public void run () {
+ * 					mMyRenderer.handleDpadCenter();
+ * 				}
+ * 			});
+ * 			return true;
+ * 		}
+ * 		return super.onKeyDown(keyCode, event);
+ * 	}
  * }
+ * 
  * 
- * + * */ public class GLBaseSurfaceView extends GLSurfaceView implements SurfaceHolder.Callback { - private final static boolean LOG_THREADS = false; - private final static boolean LOG_SURFACE = false; - private final static boolean LOG_RENDERER = false; - // Work-around for bug 2263168 - private final static boolean DRAW_TWICE_AFTER_SIZE_CHANGED = true; - /** - * The renderer only renders - * when the surface is created, or when {@link #requestRender} is called. - * - * @see #getRenderMode() - * @see #setRenderMode(int) - */ - public final static int RENDERMODE_WHEN_DIRTY = 0; - /** - * The renderer is called - * continuously to re-render the scene. - * - * @see #getRenderMode() - * @see #setRenderMode(int) - * @see #requestRender() - */ - public final static int RENDERMODE_CONTINUOUSLY = 1; - - /** - * Check glError() after every GL call and throw an exception if glError indicates - * that an error has occurred. This can be used to help track down which OpenGL ES call - * is causing an error. - * - * @see #getDebugFlags - * @see #setDebugFlags - */ - public final static int DEBUG_CHECK_GL_ERROR = 1; - - /** - * Log GL calls to the system log at "verbose" level with tag "GLSurfaceView". - * - * @see #getDebugFlags - * @see #setDebugFlags - */ - public final static int DEBUG_LOG_GL_CALLS = 2; - - /** - * Standard View constructor. In order to render something, you - * must call {@link #setRenderer} to register a renderer. - */ - public GLBaseSurfaceView(Context context) { - super(context); - init(); - } - - /** - * Standard View constructor. In order to render something, you - * must call {@link #setRenderer} to register a renderer. - */ - public GLBaseSurfaceView(Context context, AttributeSet attrs) { - super(context, attrs); - init(); - } - - private void init() { - // Install a SurfaceHolder.Callback so we get notified when the - // underlying surface is created and destroyed - SurfaceHolder holder = getHolder(); - holder.addCallback(this); - } - - /** - * Set the glWrapper. If the glWrapper is not null, its - * {@link GLWrapper#wrap(GL)} method is called - * whenever a surface is created. A GLWrapper can be used to wrap - * the GL object that's passed to the renderer. Wrapping a GL - * object enables examining and modifying the behavior of the - * GL calls made by the renderer. - *

- * Wrapping is typically used for debugging purposes. - *

- * The default value is null. - * @param glWrapper the new GLWrapper - */ - public void setGLWrapper(GLWrapper glWrapper) { - mGLWrapper = glWrapper; - } - - /** - * Set the debug flags to a new value. The value is - * constructed by OR-together zero or more - * of the DEBUG_CHECK_* constants. The debug flags take effect - * whenever a surface is created. The default value is zero. - * @param debugFlags the new debug flags - * @see #DEBUG_CHECK_GL_ERROR - * @see #DEBUG_LOG_GL_CALLS - */ - public void setDebugFlags(int debugFlags) { - mDebugFlags = debugFlags; - } - - /** - * Get the current value of the debug flags. - * @return the current value of the debug flags. - */ - public int getDebugFlags() { - return mDebugFlags; - } - - /** - * Set the renderer associated with this view. Also starts the thread that - * will call the renderer, which in turn causes the rendering to start. - *

This method should be called once and only once in the life-cycle of - * a GLSurfaceView. - *

The following GLSurfaceView methods can only be called before - * setRenderer is called: - *

    - *
  • {@link #setEGLConfigChooser(boolean)} - *
  • {@link #setEGLConfigChooser(EGLConfigChooser)} - *
  • {@link #setEGLConfigChooser(int, int, int, int, int, int)} - *
- *

- * The following GLSurfaceView methods can only be called after - * setRenderer is called: - *

    - *
  • {@link #getRenderMode()} - *
  • {@link #onPause()} - *
  • {@link #onResume()} - *
  • {@link #queueEvent(Runnable)} - *
  • {@link #requestRender()} - *
  • {@link #setRenderMode(int)} - *
- * - * @param renderer the renderer to use to perform OpenGL drawing. - */ - public void setRenderer(Renderer renderer) { - checkRenderThreadState(); - if (mEGLConfigChooser == null) { - mEGLConfigChooser = new SimpleEGLConfigChooser(true); - } - if (mEGLContextFactory == null) { - mEGLContextFactory = new DefaultContextFactory(); - } - if (mEGLWindowSurfaceFactory == null) { - mEGLWindowSurfaceFactory = new DefaultWindowSurfaceFactory(); - } - mGLThread = new GLThread(renderer); - mGLThread.start(); - } - - /** - * Install a custom EGLContextFactory. - *

If this method is - * called, it must be called before {@link #setRenderer(Renderer)} - * is called. - *

- * If this method is not called, then by default - * a context will be created with no shared context and - * with a null attribute list. - */ - public void setEGLContextFactory(EGLContextFactory factory) { - checkRenderThreadState(); - mEGLContextFactory = factory; - } - - /** - * Install a custom EGLWindowSurfaceFactory. - *

If this method is - * called, it must be called before {@link #setRenderer(Renderer)} - * is called. - *

- * If this method is not called, then by default - * a window surface will be created with a null attribute list. - */ - public void setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory factory) { - checkRenderThreadState(); - mEGLWindowSurfaceFactory = factory; - } - - /** - * Install a custom EGLConfigChooser. - *

If this method is - * called, it must be called before {@link #setRenderer(Renderer)} - * is called. - *

- * If no setEGLConfigChooser method is called, then by default the - * view will choose a config as close to 16-bit RGB as possible, with - * a depth buffer as close to 16 bits as possible. - * @param configChooser - */ - public void setEGLConfigChooser(EGLConfigChooser configChooser) { - checkRenderThreadState(); - mEGLConfigChooser = configChooser; - } - - /** - * Install a config chooser which will choose a config - * as close to 16-bit RGB as possible, with or without an optional depth - * buffer as close to 16-bits as possible. - *

If this method is - * called, it must be called before {@link #setRenderer(Renderer)} - * is called. - *

- * If no setEGLConfigChooser method is called, then by default the - * view will choose a config as close to 16-bit RGB as possible, with - * a depth buffer as close to 16 bits as possible. - * - * @param needDepth - */ - public void setEGLConfigChooser(boolean needDepth) { - setEGLConfigChooser(new SimpleEGLConfigChooser(needDepth)); - } - - /** - * Install a config chooser which will choose a config - * with at least the specified component sizes, and as close - * to the specified component sizes as possible. - *

If this method is - * called, it must be called before {@link #setRenderer(Renderer)} - * is called. - *

- * If no setEGLConfigChooser method is called, then by default the - * view will choose a config as close to 16-bit RGB as possible, with - * a depth buffer as close to 16 bits as possible. - * - */ - public void setEGLConfigChooser(int redSize, int greenSize, int blueSize, - int alphaSize, int depthSize, int stencilSize) { - setEGLConfigChooser(new ComponentSizeChooser(redSize, greenSize, - blueSize, alphaSize, depthSize, stencilSize)); - } - /** - * Set the rendering mode. When renderMode is - * RENDERMODE_CONTINUOUSLY, the renderer is called - * repeatedly to re-render the scene. When renderMode - * is RENDERMODE_WHEN_DIRTY, the renderer only rendered when the surface - * is created, or when {@link #requestRender} is called. Defaults to RENDERMODE_CONTINUOUSLY. - *

- * Using RENDERMODE_WHEN_DIRTY can improve battery life and overall system performance - * by allowing the GPU and CPU to idle when the view does not need to be updated. - *

- * This method can only be called after {@link #setRenderer(Renderer)} - * - * @param renderMode one of the RENDERMODE_X constants - * @see #RENDERMODE_CONTINUOUSLY - * @see #RENDERMODE_WHEN_DIRTY - */ - public void setRenderMode(int renderMode) { - mGLThread.setRenderMode(renderMode); - } - - /** - * Get the current rendering mode. May be called - * from any thread. Must not be called before a renderer has been set. - * @return the current rendering mode. - * @see #RENDERMODE_CONTINUOUSLY - * @see #RENDERMODE_WHEN_DIRTY - */ - public int getRenderMode() { - return mGLThread.getRenderMode(); - } - - /** - * Request that the renderer render a frame. - * This method is typically used when the render mode has been set to - * {@link #RENDERMODE_WHEN_DIRTY}, so that frames are only rendered on demand. - * May be called - * from any thread. Must not be called before a renderer has been set. - */ - public void requestRender() { - mGLThread.requestRender(); - } - - /** - * This method is part of the SurfaceHolder.Callback interface, and is - * not normally called or subclassed by clients of GLSurfaceView. - */ - public void surfaceCreated(SurfaceHolder holder) { - mGLThread.surfaceCreated(); - } - - /** - * This method is part of the SurfaceHolder.Callback interface, and is - * not normally called or subclassed by clients of GLSurfaceView. - */ - public void surfaceDestroyed(SurfaceHolder holder) { - // Surface will be destroyed when we return - mGLThread.surfaceDestroyed(); - } - - /** - * This method is part of the SurfaceHolder.Callback interface, and is - * not normally called or subclassed by clients of GLSurfaceView. - */ - public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { - mGLThread.onWindowResize(w, h); - } - - /** - * Inform the view that the activity is paused. The owner of this view must - * call this method when the activity is paused. Calling this method will - * pause the rendering thread. - * Must not be called before a renderer has been set. - */ - public void onPause() { - mGLThread.onPause(); - } - - /** - * Inform the view that the activity is resumed. The owner of this view must - * call this method when the activity is resumed. Calling this method will - * recreate the OpenGL display and resume the rendering - * thread. - * Must not be called before a renderer has been set. - */ - public void onResume() { - mGLThread.onResume(); - } - - /** - * Queue a runnable to be run on the GL rendering thread. This can be used - * to communicate with the Renderer on the rendering thread. - * Must not be called before a renderer has been set. - * @param r the runnable to be run on the GL rendering thread. - */ - public void queueEvent(Runnable r) { - mGLThread.queueEvent(r); - } - - /** - * This method is used as part of the View class and is not normally - * called or subclassed by clients of GLSurfaceView. - * Must not be called before a renderer has been set. - */ - @Override - protected void onDetachedFromWindow() { - super.onDetachedFromWindow(); - mGLThread.requestExitAndWait(); - } - - // ---------------------------------------------------------------------- - - /** - * An interface used to wrap a GL interface. - *

Typically - * used for implementing debugging and tracing on top of the default - * GL interface. You would typically use this by creating your own class - * that implemented all the GL methods by delegating to another GL instance. - * Then you could add your own behavior before or after calling the - * delegate. All the GLWrapper would do was instantiate and return the - * wrapper GL instance: - *

-     * class MyGLWrapper implements GLWrapper {
-     *     GL wrap(GL gl) {
-     *         return new MyGLImplementation(gl);
-     *     }
-     *     static class MyGLImplementation implements GL,GL10,GL11,... {
-     *         ...
-     *     }
-     * }
-     * 
- * @see #setGLWrapper(GLWrapper) - */ - public interface GLWrapper { - /** - * Wraps a gl interface in another gl interface. - * @param gl a GL interface that is to be wrapped. - * @return either the input argument or another GL object that wraps the input argument. - */ - GL wrap(GL gl); - } - - - /** - * An interface for customizing the eglCreateContext and eglDestroyContext calls. - *

- * This interface must be implemented by clients wishing to call - * {@link GLBaseSurfaceView#setEGLContextFactory(EGLContextFactory)} - */ - public interface EGLContextFactory { - EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig eglConfig); - void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context); - } - - private static class DefaultContextFactory implements EGLContextFactory { - - public EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig config) { - return egl.eglCreateContext(display, config, EGL10.EGL_NO_CONTEXT, null); - } - - public void destroyContext(EGL10 egl, EGLDisplay display, - EGLContext context) { - egl.eglDestroyContext(display, context); - } - } - - /** - * An interface for customizing the eglCreateWindowSurface and eglDestroySurface calls. - *

- * This interface must be implemented by clients wishing to call - * {@link GLBaseSurfaceView#setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory)} - */ - public interface EGLWindowSurfaceFactory { - EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display, EGLConfig config, - Object nativeWindow); - void destroySurface(EGL10 egl, EGLDisplay display, EGLSurface surface); - } - - private static class DefaultWindowSurfaceFactory implements EGLWindowSurfaceFactory { - - public EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display, - EGLConfig config, Object nativeWindow) { - return egl.eglCreateWindowSurface(display, config, nativeWindow, null); - } - - public void destroySurface(EGL10 egl, EGLDisplay display, - EGLSurface surface) { - egl.eglDestroySurface(display, surface); - } - } - - /** - * An interface for choosing an EGLConfig configuration from a list of - * potential configurations. - *

- * This interface must be implemented by clients wishing to call - * {@link GLBaseSurfaceView#setEGLConfigChooser(EGLConfigChooser)} - */ - public interface EGLConfigChooser { - /** - * Choose a configuration from the list. Implementors typically - * implement this method by calling - * {@link EGL10#eglChooseConfig} and iterating through the results. Please consult the - * EGL specification available from The Khronos Group to learn how to call eglChooseConfig. - * @param egl the EGL10 for the current display. - * @param display the current display. - * @return the chosen configuration. - */ - EGLConfig chooseConfig(EGL10 egl, EGLDisplay display); - } - - private static abstract class BaseConfigChooser - implements EGLConfigChooser { - public BaseConfigChooser(int[] configSpec) { - mConfigSpec = configSpec; - } - public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) { - int[] num_config = new int[1]; - egl.eglChooseConfig(display, mConfigSpec, null, 0, num_config); - - int numConfigs = num_config[0]; - - if (numConfigs <= 0) { - throw new IllegalArgumentException( - "No configs match configSpec"); - } - - EGLConfig[] configs = new EGLConfig[numConfigs]; - egl.eglChooseConfig(display, mConfigSpec, configs, numConfigs, - num_config); - EGLConfig config = chooseConfig(egl, display, configs); - if (config == null) { - throw new IllegalArgumentException("No config chosen"); - } - return config; - } - - abstract EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, - EGLConfig[] configs); - - protected int[] mConfigSpec; - } - - private static class ComponentSizeChooser extends BaseConfigChooser { - public ComponentSizeChooser(int redSize, int greenSize, int blueSize, - int alphaSize, int depthSize, int stencilSize) { - super(new int[] { - EGL10.EGL_RED_SIZE, redSize, - EGL10.EGL_GREEN_SIZE, greenSize, - EGL10.EGL_BLUE_SIZE, blueSize, - EGL10.EGL_ALPHA_SIZE, alphaSize, - EGL10.EGL_DEPTH_SIZE, depthSize, - EGL10.EGL_STENCIL_SIZE, stencilSize, - EGL10.EGL_NONE}); - mValue = new int[1]; - mRedSize = redSize; - mGreenSize = greenSize; - mBlueSize = blueSize; - mAlphaSize = alphaSize; - mDepthSize = depthSize; - mStencilSize = stencilSize; - } - - @Override - public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, - EGLConfig[] configs) { - EGLConfig closestConfig = null; - int closestDistance = 1000; - for(EGLConfig config : configs) { - int d = findConfigAttrib(egl, display, config, - EGL10.EGL_DEPTH_SIZE, 0); - int s = findConfigAttrib(egl, display, config, - EGL10.EGL_STENCIL_SIZE, 0); - if (d >= mDepthSize && s>= mStencilSize) { - int r = findConfigAttrib(egl, display, config, - EGL10.EGL_RED_SIZE, 0); - int g = findConfigAttrib(egl, display, config, - EGL10.EGL_GREEN_SIZE, 0); - int b = findConfigAttrib(egl, display, config, - EGL10.EGL_BLUE_SIZE, 0); - int a = findConfigAttrib(egl, display, config, - EGL10.EGL_ALPHA_SIZE, 0); - int distance = Math.abs(r - mRedSize) - + Math.abs(g - mGreenSize) - + Math.abs(b - mBlueSize) - + Math.abs(a - mAlphaSize); - if (distance < closestDistance) { - closestDistance = distance; - closestConfig = config; - } - } - } - return closestConfig; - } - - private int findConfigAttrib(EGL10 egl, EGLDisplay display, - EGLConfig config, int attribute, int defaultValue) { - - if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) { - return mValue[0]; - } - return defaultValue; - } - - private int[] mValue; - // Subclasses can adjust these values: - protected int mRedSize; - protected int mGreenSize; - protected int mBlueSize; - protected int mAlphaSize; - protected int mDepthSize; - protected int mStencilSize; - } - - /** - * This class will choose a supported surface as close to - * RGB565 as possible, with or without a depth buffer. - * - */ - private static class SimpleEGLConfigChooser extends ComponentSizeChooser { - public SimpleEGLConfigChooser(boolean withDepthBuffer) { - super(4, 4, 4, 0, withDepthBuffer ? 16 : 0, 0); - // Adjust target values. This way we'll accept a 4444 or - // 555 buffer if there's no 565 buffer available. - mRedSize = 5; - mGreenSize = 6; - mBlueSize = 5; - } - } - - /** - * An EGL helper class. - */ - - private class EglHelper { - public EglHelper() { - - } - - /** - * Initialize EGL for a given configuration spec. - * @param configSpec - */ - public void start(){ - /* - * Get an EGL instance - */ - mEgl = (EGL10) EGLContext.getEGL(); - - /* - * Get to the default display. - */ - mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); - - /* - * We can now initialize EGL for that display - */ - int[] version = new int[2]; - mEgl.eglInitialize(mEglDisplay, version); - mEglConfig = mEGLConfigChooser.chooseConfig(mEgl, mEglDisplay); - - /* - * Create an OpenGL ES context. This must be done only once, an - * OpenGL context is a somewhat heavy object. - */ - mEglContext = mEGLContextFactory.createContext(mEgl, mEglDisplay, mEglConfig); - if (mEglContext == null || mEglContext == EGL10.EGL_NO_CONTEXT) { - throw new RuntimeException("createContext failed"); - } - - mEglSurface = null; - } - - /* - * React to the creation of a new surface by creating and returning an - * OpenGL interface that renders to that surface. - */ - public GL createSurface(SurfaceHolder holder) { - /* - * The window size has changed, so we need to create a new - * surface. - */ - if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) { - - /* - * Unbind and destroy the old EGL surface, if - * there is one. - */ - mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, - EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); - mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, mEglSurface); - } - - /* - * Create an EGL surface we can render into. - */ - mEglSurface = mEGLWindowSurfaceFactory.createWindowSurface(mEgl, - mEglDisplay, mEglConfig, holder); - - if (mEglSurface == null || mEglSurface == EGL10.EGL_NO_SURFACE) { - throwEglException("createWindowSurface"); - } - - /* - * Before we can issue GL commands, we need to make sure - * the context is current and bound to a surface. - */ - if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)) { - throwEglException("eglMakeCurrent"); - } - - GL gl = mEglContext.getGL(); - if (mGLWrapper != null) { - gl = mGLWrapper.wrap(gl); - } - - if ((mDebugFlags & (DEBUG_CHECK_GL_ERROR | DEBUG_LOG_GL_CALLS)) != 0) { - int configFlags = 0; - Writer log = null; - if ((mDebugFlags & DEBUG_CHECK_GL_ERROR) != 0) { - configFlags |= GLDebugHelper.CONFIG_CHECK_GL_ERROR; - } - if ((mDebugFlags & DEBUG_LOG_GL_CALLS) != 0) { - log = new LogWriter(); - } - gl = GLDebugHelper.wrap(gl, configFlags, log); - } - return gl; - } - - /** - * Display the current render surface. - * @return false if the context has been lost. - */ - public boolean swap() { - mEgl.eglSwapBuffers(mEglDisplay, mEglSurface); - - /* - * Always check for EGL_CONTEXT_LOST, which means the context - * and all associated data were lost (For instance because - * the device went to sleep). We need to sleep until we - * get a new surface. - */ - return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST; - } - - public void destroySurface() { - if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) { - mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, - EGL10.EGL_NO_SURFACE, - EGL10.EGL_NO_CONTEXT); - mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, mEglSurface); - mEglSurface = null; - } - } - - public void finish() { - if (mEglContext != null) { - mEGLContextFactory.destroyContext(mEgl, mEglDisplay, mEglContext); - mEglContext = null; - } - if (mEglDisplay != null) { - mEgl.eglTerminate(mEglDisplay); - mEglDisplay = null; - } - } - - private void throwEglException(String function) { - throw new RuntimeException(function + " failed: " + mEgl.eglGetError()); - } - - EGL10 mEgl; - EGLDisplay mEglDisplay; - EGLSurface mEglSurface; - EGLConfig mEglConfig; - EGLContext mEglContext; - } - - /** - * A generic GL Thread. Takes care of initializing EGL and GL. Delegates - * to a Renderer instance to do the actual drawing. Can be configured to - * render continuously or on request. - * - * All potentially blocking synchronization is done through the - * sGLThreadManager object. This avoids multiple-lock ordering issues. - * - */ - class GLThread extends Thread { - GLThread(Renderer renderer) { - super(); - mWidth = 0; - mHeight = 0; - mRequestRender = true; - mRenderMode = RENDERMODE_CONTINUOUSLY; - mRenderer = renderer; - } - - @Override - public void run() { - setName("GLThread " + getId()); - if (LOG_THREADS) { - Log.i("GLThread", "starting tid=" + getId()); - } - - try { - guardedRun(); - } catch (InterruptedException e) { - // fall thru and exit normally - } finally { - sGLThreadManager.threadExiting(this); - } - } - - /* - * This private method should only be called inside a - * synchronized(sGLThreadManager) block. - */ - private void stopEglLocked() { - if (mHaveEgl) { - mHaveEgl = false; - mEglHelper.destroySurface(); - mEglHelper.finish(); - sGLThreadManager.releaseEglSurfaceLocked(this); - } - } - - private void guardedRun() throws InterruptedException { - mEglHelper = new EglHelper(); - try { - GL10 gl = null; - boolean createEglSurface = false; - boolean sizeChanged = false; - boolean wantRenderNotification = false; - boolean doRenderNotification = false; - int w = 0; - int h = 0; - Runnable event = null; - - while (true) { - synchronized (sGLThreadManager) { - while (true) { - if (mShouldExit) { - return; - } - - if (! mEventQueue.isEmpty()) { - event = mEventQueue.remove(0); - break; - } - - // Do we need to release the EGL surface? - if (mHaveEgl && mPaused) { - if (LOG_SURFACE) { - Log.i("GLThread", "releasing EGL surface because paused tid=" + getId()); - } - stopEglLocked(); - } - - // Have we lost the surface view surface? - if ((! mHasSurface) && (! mWaitingForSurface)) { - if (LOG_SURFACE) { - Log.i("GLThread", "noticed surfaceView surface lost tid=" + getId()); - } - if (mHaveEgl) { - stopEglLocked(); - } - mWaitingForSurface = true; - sGLThreadManager.notifyAll(); - } - - // Have we acquired the surface view surface? - if (mHasSurface && mWaitingForSurface) { - if (LOG_SURFACE) { - Log.i("GLThread", "noticed surfaceView surface acquired tid=" + getId()); - } - mWaitingForSurface = false; - sGLThreadManager.notifyAll(); - } - - if (doRenderNotification) { - wantRenderNotification = false; - doRenderNotification = false; - mRenderComplete = true; - sGLThreadManager.notifyAll(); - } - - // Ready to draw? - if ((!mPaused) && mHasSurface - && (mWidth > 0) && (mHeight > 0) - && (mRequestRender || (mRenderMode == RENDERMODE_CONTINUOUSLY))) { - - // If we don't have an egl surface, try to acquire one. - if ((! mHaveEgl) && sGLThreadManager.tryAcquireEglSurfaceLocked(this)) { - mHaveEgl = true; - mEglHelper.start(); - createEglSurface = true; - sizeChanged = true; - sGLThreadManager.notifyAll(); - } - - if (mHaveEgl) { - if (mSizeChanged) { - sizeChanged = true; - w = mWidth; - h = mHeight; - wantRenderNotification = true; - - if (DRAW_TWICE_AFTER_SIZE_CHANGED) { - // We keep mRequestRender true so that we draw twice after the size changes. - // (Once because of mSizeChanged, the second time because of mRequestRender.) - // This forces the updated graphics onto the screen. - } else { - mRequestRender = false; - } - mSizeChanged = false; - } else { - mRequestRender = false; - } - sGLThreadManager.notifyAll(); - break; - } - } - - // By design, this is the only place in a GLThread thread where we wait(). - if (LOG_THREADS) { - Log.i("GLThread", "waiting tid=" + getId()); - } - sGLThreadManager.wait(); - } - } // end of synchronized(sGLThreadManager) - - if (event != null) { - event.run(); - event = null; - continue; - } - - if (createEglSurface) { - gl = (GL10) mEglHelper.createSurface(getHolder()); - if (LOG_RENDERER) { - Log.w("GLThread", "onSurfaceCreated"); - } - mRenderer.onSurfaceCreated(gl, mEglHelper.mEglConfig); - createEglSurface = false; - } - - if (sizeChanged) { - if (LOG_RENDERER) { - Log.w("GLThread", "onSurfaceChanged(" + w + ", " + h + ")"); - } - mRenderer.onSurfaceChanged(gl, w, h); - sizeChanged = false; - } - - if (LOG_RENDERER) { - Log.w("GLThread", "onDrawFrame"); - } - mRenderer.onDrawFrame(gl); - if(!mEglHelper.swap()) { - if (LOG_SURFACE) { - Log.i("GLThread", "egl surface lost tid=" + getId()); - } - } - - if (wantRenderNotification) { - doRenderNotification = true; - } - } - } finally { - /* - * clean-up everything... - */ - synchronized (sGLThreadManager) { - stopEglLocked(); - } - } - } - - public void setRenderMode(int renderMode) { - if ( !((RENDERMODE_WHEN_DIRTY <= renderMode) && (renderMode <= RENDERMODE_CONTINUOUSLY)) ) { - throw new IllegalArgumentException("renderMode"); - } - synchronized(sGLThreadManager) { - mRenderMode = renderMode; - sGLThreadManager.notifyAll(); - } - } - - public int getRenderMode() { - synchronized(sGLThreadManager) { - return mRenderMode; - } - } - - public void requestRender() { - synchronized(sGLThreadManager) { - mRequestRender = true; - sGLThreadManager.notifyAll(); - } - } - - public void surfaceCreated() { - synchronized(sGLThreadManager) { - if (LOG_THREADS) { - Log.i("GLThread", "surfaceCreated tid=" + getId()); - } - mHasSurface = true; - sGLThreadManager.notifyAll(); - } - } - - public void surfaceDestroyed() { - synchronized(sGLThreadManager) { - if (LOG_THREADS) { - Log.i("GLThread", "surfaceDestroyed tid=" + getId()); - } - mHasSurface = false; - sGLThreadManager.notifyAll(); - while((!mWaitingForSurface) && (!mExited)) { - try { - sGLThreadManager.wait(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - } - } - } - - public void onPause() { - synchronized (sGLThreadManager) { - mPaused = true; - sGLThreadManager.notifyAll(); - } - } - - public void onResume() { - synchronized (sGLThreadManager) { - mPaused = false; - mRequestRender = true; - sGLThreadManager.notifyAll(); - } - } - - public void onWindowResize(int w, int h) { - synchronized (sGLThreadManager) { - mWidth = w; - mHeight = h; - mSizeChanged = true; - mRequestRender = true; - mRenderComplete = false; - sGLThreadManager.notifyAll(); - - // Wait for thread to react to resize and render a frame - while (! mExited && !mPaused && !mRenderComplete ) { - if (LOG_SURFACE) { - Log.i("Main thread", "onWindowResize waiting for render complete."); - } - try { - sGLThreadManager.wait(); - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - } - } - } - } - - public void requestExitAndWait() { - // don't call this from GLThread thread or it is a guaranteed - // deadlock! - synchronized(sGLThreadManager) { - mShouldExit = true; - sGLThreadManager.notifyAll(); - while (! mExited) { - try { - sGLThreadManager.wait(); - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - } - } - } - } - - /** - * Queue an "event" to be run on the GL rendering thread. - * @param r the runnable to be run on the GL rendering thread. - */ - public void queueEvent(Runnable r) { - if (r == null) { - throw new IllegalArgumentException("r must not be null"); - } - synchronized(sGLThreadManager) { - mEventQueue.add(r); - sGLThreadManager.notifyAll(); - } - } - - // Once the thread is started, all accesses to the following member - // variables are protected by the sGLThreadManager monitor - private boolean mShouldExit; - private boolean mExited; - private boolean mPaused; - private boolean mHasSurface; - private boolean mWaitingForSurface; - private boolean mHaveEgl; - private int mWidth; - private int mHeight; - private int mRenderMode; - private boolean mRequestRender; - private boolean mRenderComplete; - private ArrayList mEventQueue = new ArrayList(); - // End of member variables protected by the sGLThreadManager monitor. - - private Renderer mRenderer; - private EglHelper mEglHelper; - } - - static class LogWriter extends Writer { - - @Override public void close() { - flushBuilder(); - } - - @Override public void flush() { - flushBuilder(); - } - - @Override public void write(char[] buf, int offset, int count) { - for(int i = 0; i < count; i++) { - char c = buf[offset + i]; - if ( c == '\n') { - flushBuilder(); - } - else { - mBuilder.append(c); - } - } - } - - private void flushBuilder() { - if (mBuilder.length() > 0) { - Log.v("GLSurfaceView", mBuilder.toString()); - mBuilder.delete(0, mBuilder.length()); - } - } - - private StringBuilder mBuilder = new StringBuilder(); - } - - - private void checkRenderThreadState() { - if (mGLThread != null) { - throw new IllegalStateException( - "setRenderer has already been called for this instance."); - } - } - - private static class GLThreadManager { - - public synchronized void threadExiting(GLThread thread) { - if (LOG_THREADS) { - Log.i("GLThread", "exiting tid=" + thread.getId()); - } - thread.mExited = true; - if (mEglOwner == thread) { - mEglOwner = null; - } - notifyAll(); - } - - /* - * Tries once to acquire the right to use an EGL - * surface. Does not block. Requires that we are already - * in the sGLThreadManager monitor when this is called. - * @return true if the right to use an EGL surface was acquired. - */ - public boolean tryAcquireEglSurfaceLocked(GLThread thread) { - if (mEglOwner == thread || mEglOwner == null) { - mEglOwner = thread; - notifyAll(); - return true; - } - return false; - } - /* - * Releases the EGL surface. Requires that we are already in the - * sGLThreadManager monitor when this is called. - */ - public void releaseEglSurfaceLocked(GLThread thread) { - if (mEglOwner == thread) { - mEglOwner = null; - } - notifyAll(); - } - - private GLThread mEglOwner; - } - - private static final GLThreadManager sGLThreadManager = new GLThreadManager(); - private boolean mSizeChanged = true; - - private GLThread mGLThread; - private EGLConfigChooser mEGLConfigChooser; - private EGLContextFactory mEGLContextFactory; - private EGLWindowSurfaceFactory mEGLWindowSurfaceFactory; - private GLWrapper mGLWrapper; - private int mDebugFlags; + private final static boolean LOG_THREADS = false; + private final static boolean LOG_SURFACE = false; + private final static boolean LOG_RENDERER = false; + // Work-around for bug 2263168 + private final static boolean DRAW_TWICE_AFTER_SIZE_CHANGED = true; + /** + * The renderer only renders when the surface is created, or when {@link #requestRender} is called. + * + * @see #getRenderMode() + * @see #setRenderMode(int) + */ + public final static int RENDERMODE_WHEN_DIRTY = 0; + /** + * The renderer is called continuously to re-render the scene. + * + * @see #getRenderMode() + * @see #setRenderMode(int) + * @see #requestRender() + */ + public final static int RENDERMODE_CONTINUOUSLY = 1; + + /** + * Check glError() after every GL call and throw an exception if glError indicates that an error has occurred. This can be used + * to help track down which OpenGL ES call is causing an error. + * + * @see #getDebugFlags + * @see #setDebugFlags + */ + public final static int DEBUG_CHECK_GL_ERROR = 1; + + /** + * Log GL calls to the system log at "verbose" level with tag "GLSurfaceView". + * + * @see #getDebugFlags + * @see #setDebugFlags + */ + public final static int DEBUG_LOG_GL_CALLS = 2; + + /** + * Standard View constructor. In order to render something, you must call {@link #setRenderer} to register a renderer. + */ + public GLBaseSurfaceView (Context context) { + super(context); + init(); + } + + /** + * Standard View constructor. In order to render something, you must call {@link #setRenderer} to register a renderer. + */ + public GLBaseSurfaceView (Context context, AttributeSet attrs) { + super(context, attrs); + init(); + } + + private void init () { + // Install a SurfaceHolder.Callback so we get notified when the + // underlying surface is created and destroyed + SurfaceHolder holder = getHolder(); + holder.addCallback(this); + } + + /** + * Set the glWrapper. If the glWrapper is not null, its {@link GLWrapper#wrap(GL)} method is called whenever a surface is + * created. A GLWrapper can be used to wrap the GL object that's passed to the renderer. Wrapping a GL object enables examining + * and modifying the behavior of the GL calls made by the renderer. + *

+ * Wrapping is typically used for debugging purposes. + *

+ * The default value is null. + * @param glWrapper the new GLWrapper + */ + public void setGLWrapper (GLWrapper glWrapper) { + mGLWrapper = glWrapper; + } + + /** + * Set the debug flags to a new value. The value is constructed by OR-together zero or more of the DEBUG_CHECK_* constants. The + * debug flags take effect whenever a surface is created. The default value is zero. + * @param debugFlags the new debug flags + * @see #DEBUG_CHECK_GL_ERROR + * @see #DEBUG_LOG_GL_CALLS + */ + public void setDebugFlags (int debugFlags) { + mDebugFlags = debugFlags; + } + + /** + * Get the current value of the debug flags. + * @return the current value of the debug flags. + */ + public int getDebugFlags () { + return mDebugFlags; + } + + /** + * Set the renderer associated with this view. Also starts the thread that will call the renderer, which in turn causes the + * rendering to start. + *

+ * This method should be called once and only once in the life-cycle of a GLSurfaceView. + *

+ * The following GLSurfaceView methods can only be called before setRenderer is called: + *

    + *
  • {@link #setEGLConfigChooser(boolean)} + *
  • {@link #setEGLConfigChooser(EGLConfigChooser)} + *
  • {@link #setEGLConfigChooser(int, int, int, int, int, int)} + *
+ *

+ * The following GLSurfaceView methods can only be called after setRenderer is called: + *

    + *
  • {@link #getRenderMode()} + *
  • {@link #onPause()} + *
  • {@link #onResume()} + *
  • {@link #queueEvent(Runnable)} + *
  • {@link #requestRender()} + *
  • {@link #setRenderMode(int)} + *
+ * + * @param renderer the renderer to use to perform OpenGL drawing. + */ + public void setRenderer (Renderer renderer) { + checkRenderThreadState(); + if (mEGLConfigChooser == null) { + mEGLConfigChooser = new SimpleEGLConfigChooser(true); + } + if (mEGLContextFactory == null) { + mEGLContextFactory = new DefaultContextFactory(); + } + if (mEGLWindowSurfaceFactory == null) { + mEGLWindowSurfaceFactory = new DefaultWindowSurfaceFactory(); + } + mGLThread = new GLThread(renderer); + mGLThread.start(); + } + + /** + * Install a custom EGLContextFactory. + *

+ * If this method is called, it must be called before {@link #setRenderer(Renderer)} is called. + *

+ * If this method is not called, then by default a context will be created with no shared context and with a null attribute + * list. + */ + public void setEGLContextFactory (EGLContextFactory factory) { + checkRenderThreadState(); + mEGLContextFactory = factory; + } + + /** + * Install a custom EGLWindowSurfaceFactory. + *

+ * If this method is called, it must be called before {@link #setRenderer(Renderer)} is called. + *

+ * If this method is not called, then by default a window surface will be created with a null attribute list. + */ + public void setEGLWindowSurfaceFactory (EGLWindowSurfaceFactory factory) { + checkRenderThreadState(); + mEGLWindowSurfaceFactory = factory; + } + + /** + * Install a custom EGLConfigChooser. + *

+ * If this method is called, it must be called before {@link #setRenderer(Renderer)} is called. + *

+ * If no setEGLConfigChooser method is called, then by default the view will choose a config as close to 16-bit RGB as + * possible, with a depth buffer as close to 16 bits as possible. + * @param configChooser + */ + public void setEGLConfigChooser (EGLConfigChooser configChooser) { + checkRenderThreadState(); + mEGLConfigChooser = configChooser; + } + + /** + * Install a config chooser which will choose a config as close to 16-bit RGB as possible, with or without an optional depth + * buffer as close to 16-bits as possible. + *

+ * If this method is called, it must be called before {@link #setRenderer(Renderer)} is called. + *

+ * If no setEGLConfigChooser method is called, then by default the view will choose a config as close to 16-bit RGB as + * possible, with a depth buffer as close to 16 bits as possible. + * + * @param needDepth + */ + public void setEGLConfigChooser (boolean needDepth) { + setEGLConfigChooser(new SimpleEGLConfigChooser(needDepth)); + } + + /** + * Install a config chooser which will choose a config with at least the specified component sizes, and as close to the + * specified component sizes as possible. + *

+ * If this method is called, it must be called before {@link #setRenderer(Renderer)} is called. + *

+ * If no setEGLConfigChooser method is called, then by default the view will choose a config as close to 16-bit RGB as + * possible, with a depth buffer as close to 16 bits as possible. + * + */ + public void setEGLConfigChooser (int redSize, int greenSize, int blueSize, int alphaSize, int depthSize, int stencilSize) { + setEGLConfigChooser(new ComponentSizeChooser(redSize, greenSize, blueSize, alphaSize, depthSize, stencilSize)); + } + + /** + * Set the rendering mode. When renderMode is RENDERMODE_CONTINUOUSLY, the renderer is called repeatedly to re-render the + * scene. When renderMode is RENDERMODE_WHEN_DIRTY, the renderer only rendered when the surface is created, or when + * {@link #requestRender} is called. Defaults to RENDERMODE_CONTINUOUSLY. + *

+ * Using RENDERMODE_WHEN_DIRTY can improve battery life and overall system performance by allowing the GPU and CPU to idle when + * the view does not need to be updated. + *

+ * This method can only be called after {@link #setRenderer(Renderer)} + * + * @param renderMode one of the RENDERMODE_X constants + * @see #RENDERMODE_CONTINUOUSLY + * @see #RENDERMODE_WHEN_DIRTY + */ + public void setRenderMode (int renderMode) { + mGLThread.setRenderMode(renderMode); + } + + /** + * Get the current rendering mode. May be called from any thread. Must not be called before a renderer has been set. + * @return the current rendering mode. + * @see #RENDERMODE_CONTINUOUSLY + * @see #RENDERMODE_WHEN_DIRTY + */ + public int getRenderMode () { + return mGLThread.getRenderMode(); + } + + /** + * Request that the renderer render a frame. This method is typically used when the render mode has been set to + * {@link #RENDERMODE_WHEN_DIRTY}, so that frames are only rendered on demand. May be called from any thread. Must not be + * called before a renderer has been set. + */ + public void requestRender () { + mGLThread.requestRender(); + } + + /** + * This method is part of the SurfaceHolder.Callback interface, and is not normally called or subclassed by clients of + * GLSurfaceView. + */ + public void surfaceCreated (SurfaceHolder holder) { + mGLThread.surfaceCreated(); + } + + /** + * This method is part of the SurfaceHolder.Callback interface, and is not normally called or subclassed by clients of + * GLSurfaceView. + */ + public void surfaceDestroyed (SurfaceHolder holder) { + // Surface will be destroyed when we return + mGLThread.surfaceDestroyed(); + } + + /** + * This method is part of the SurfaceHolder.Callback interface, and is not normally called or subclassed by clients of + * GLSurfaceView. + */ + public void surfaceChanged (SurfaceHolder holder, int format, int w, int h) { + mGLThread.onWindowResize(w, h); + } + + /** + * Inform the view that the activity is paused. The owner of this view must call this method when the activity is paused. + * Calling this method will pause the rendering thread. Must not be called before a renderer has been set. + */ + public void onPause () { + mGLThread.onPause(); + } + + /** + * Inform the view that the activity is resumed. The owner of this view must call this method when the activity is resumed. + * Calling this method will recreate the OpenGL display and resume the rendering thread. Must not be called before a renderer + * has been set. + */ + public void onResume () { + mGLThread.onResume(); + } + + /** + * Queue a runnable to be run on the GL rendering thread. This can be used to communicate with the Renderer on the rendering + * thread. Must not be called before a renderer has been set. + * @param r the runnable to be run on the GL rendering thread. + */ + public void queueEvent (Runnable r) { + mGLThread.queueEvent(r); + } + + /** + * This method is used as part of the View class and is not normally called or subclassed by clients of GLSurfaceView. Must not + * be called before a renderer has been set. + */ + @Override protected void onDetachedFromWindow () { + super.onDetachedFromWindow(); + mGLThread.requestExitAndWait(); + } + + // ---------------------------------------------------------------------- + + /** + * An interface used to wrap a GL interface. + *

+ * Typically used for implementing debugging and tracing on top of the default GL interface. You would typically use this by + * creating your own class that implemented all the GL methods by delegating to another GL instance. Then you could add your + * own behavior before or after calling the delegate. All the GLWrapper would do was instantiate and return the wrapper GL + * instance: + * + *

+	 * class MyGLWrapper implements GLWrapper {
+	 *     GL wrap(GL gl) {
+	 *         return new MyGLImplementation(gl);
+	 *     }
+	 *     static class MyGLImplementation implements GL,GL10,GL11,... {
+	 *         ...
+	 *     }
+	 * }
+	 * 
+ * @see #setGLWrapper(GLWrapper) + */ + public interface GLWrapper { + /** + * Wraps a gl interface in another gl interface. + * @param gl a GL interface that is to be wrapped. + * @return either the input argument or another GL object that wraps the input argument. + */ + GL wrap (GL gl); + } + + /** + * An interface for customizing the eglCreateContext and eglDestroyContext calls. + *

+ * This interface must be implemented by clients wishing to call + * {@link GLBaseSurfaceView#setEGLContextFactory(EGLContextFactory)} + */ + public interface EGLContextFactory { + EGLContext createContext (EGL10 egl, EGLDisplay display, EGLConfig eglConfig); + + void destroyContext (EGL10 egl, EGLDisplay display, EGLContext context); + } + + private static class DefaultContextFactory implements EGLContextFactory { + + public EGLContext createContext (EGL10 egl, EGLDisplay display, EGLConfig config) { + return egl.eglCreateContext(display, config, EGL10.EGL_NO_CONTEXT, null); + } + + public void destroyContext (EGL10 egl, EGLDisplay display, EGLContext context) { + egl.eglDestroyContext(display, context); + } + } + + /** + * An interface for customizing the eglCreateWindowSurface and eglDestroySurface calls. + *

+ * This interface must be implemented by clients wishing to call + * {@link GLBaseSurfaceView#setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory)} + */ + public interface EGLWindowSurfaceFactory { + EGLSurface createWindowSurface (EGL10 egl, EGLDisplay display, EGLConfig config, Object nativeWindow); + + void destroySurface (EGL10 egl, EGLDisplay display, EGLSurface surface); + } + + private static class DefaultWindowSurfaceFactory implements EGLWindowSurfaceFactory { + + public EGLSurface createWindowSurface (EGL10 egl, EGLDisplay display, EGLConfig config, Object nativeWindow) { + return egl.eglCreateWindowSurface(display, config, nativeWindow, null); + } + + public void destroySurface (EGL10 egl, EGLDisplay display, EGLSurface surface) { + egl.eglDestroySurface(display, surface); + } + } + + /** + * An interface for choosing an EGLConfig configuration from a list of potential configurations. + *

+ * This interface must be implemented by clients wishing to call + * {@link GLBaseSurfaceView#setEGLConfigChooser(EGLConfigChooser)} + */ + public interface EGLConfigChooser { + /** + * Choose a configuration from the list. Implementors typically implement this method by calling + * {@link EGL10#eglChooseConfig} and iterating through the results. Please consult the EGL specification available from The + * Khronos Group to learn how to call eglChooseConfig. + * @param egl the EGL10 for the current display. + * @param display the current display. + * @return the chosen configuration. + */ + EGLConfig chooseConfig (EGL10 egl, EGLDisplay display); + } + + private static abstract class BaseConfigChooser implements EGLConfigChooser { + public BaseConfigChooser (int[] configSpec) { + mConfigSpec = configSpec; + } + + public EGLConfig chooseConfig (EGL10 egl, EGLDisplay display) { + int[] num_config = new int[1]; + egl.eglChooseConfig(display, mConfigSpec, null, 0, num_config); + + int numConfigs = num_config[0]; + + if (numConfigs <= 0) { + throw new IllegalArgumentException("No configs match configSpec"); + } + + EGLConfig[] configs = new EGLConfig[numConfigs]; + egl.eglChooseConfig(display, mConfigSpec, configs, numConfigs, num_config); + EGLConfig config = chooseConfig(egl, display, configs); + if (config == null) { + throw new IllegalArgumentException("No config chosen"); + } + return config; + } + + abstract EGLConfig chooseConfig (EGL10 egl, EGLDisplay display, EGLConfig[] configs); + + protected int[] mConfigSpec; + } + + private static class ComponentSizeChooser extends BaseConfigChooser { + public ComponentSizeChooser (int redSize, int greenSize, int blueSize, int alphaSize, int depthSize, int stencilSize) { + super( + new int[] {EGL10.EGL_RED_SIZE, redSize, EGL10.EGL_GREEN_SIZE, greenSize, EGL10.EGL_BLUE_SIZE, blueSize, + EGL10.EGL_ALPHA_SIZE, alphaSize, EGL10.EGL_DEPTH_SIZE, depthSize, EGL10.EGL_STENCIL_SIZE, stencilSize, + EGL10.EGL_NONE}); + mValue = new int[1]; + mRedSize = redSize; + mGreenSize = greenSize; + mBlueSize = blueSize; + mAlphaSize = alphaSize; + mDepthSize = depthSize; + mStencilSize = stencilSize; + } + + @Override public EGLConfig chooseConfig (EGL10 egl, EGLDisplay display, EGLConfig[] configs) { + EGLConfig closestConfig = null; + int closestDistance = 1000; + for (EGLConfig config : configs) { + int d = findConfigAttrib(egl, display, config, EGL10.EGL_DEPTH_SIZE, 0); + int s = findConfigAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0); + if (d >= mDepthSize && s >= mStencilSize) { + int r = findConfigAttrib(egl, display, config, EGL10.EGL_RED_SIZE, 0); + int g = findConfigAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0); + int b = findConfigAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0); + int a = findConfigAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0); + int distance = Math.abs(r - mRedSize) + Math.abs(g - mGreenSize) + Math.abs(b - mBlueSize) + + Math.abs(a - mAlphaSize); + if (distance < closestDistance) { + closestDistance = distance; + closestConfig = config; + } + } + } + return closestConfig; + } + + private int findConfigAttrib (EGL10 egl, EGLDisplay display, EGLConfig config, int attribute, int defaultValue) { + + if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) { + return mValue[0]; + } + return defaultValue; + } + + private int[] mValue; + // Subclasses can adjust these values: + protected int mRedSize; + protected int mGreenSize; + protected int mBlueSize; + protected int mAlphaSize; + protected int mDepthSize; + protected int mStencilSize; + } + + /** + * This class will choose a supported surface as close to RGB565 as possible, with or without a depth buffer. + * + */ + private static class SimpleEGLConfigChooser extends ComponentSizeChooser { + public SimpleEGLConfigChooser (boolean withDepthBuffer) { + super(4, 4, 4, 0, withDepthBuffer ? 16 : 0, 0); + // Adjust target values. This way we'll accept a 4444 or + // 555 buffer if there's no 565 buffer available. + mRedSize = 5; + mGreenSize = 6; + mBlueSize = 5; + } + } + + /** + * An EGL helper class. + */ + + private class EglHelper { + public EglHelper () { + + } + + /** + * Initialize EGL for a given configuration spec. + * @param configSpec + */ + public void start () { + /* + * Get an EGL instance + */ + mEgl = (EGL10)EGLContext.getEGL(); + + /* + * Get to the default display. + */ + mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); + + /* + * We can now initialize EGL for that display + */ + int[] version = new int[2]; + mEgl.eglInitialize(mEglDisplay, version); + mEglConfig = mEGLConfigChooser.chooseConfig(mEgl, mEglDisplay); + + /* + * Create an OpenGL ES context. This must be done only once, an OpenGL context is a somewhat heavy object. + */ + mEglContext = mEGLContextFactory.createContext(mEgl, mEglDisplay, mEglConfig); + if (mEglContext == null || mEglContext == EGL10.EGL_NO_CONTEXT) { + throw new RuntimeException("createContext failed"); + } + + mEglSurface = null; + } + + /* + * React to the creation of a new surface by creating and returning an OpenGL interface that renders to that surface. + */ + public GL createSurface (SurfaceHolder holder) { + /* + * The window size has changed, so we need to create a new surface. + */ + if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) { + + /* + * Unbind and destroy the old EGL surface, if there is one. + */ + mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); + mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, mEglSurface); + } + + /* + * Create an EGL surface we can render into. + */ + mEglSurface = mEGLWindowSurfaceFactory.createWindowSurface(mEgl, mEglDisplay, mEglConfig, holder); + + if (mEglSurface == null || mEglSurface == EGL10.EGL_NO_SURFACE) { + throwEglException("createWindowSurface"); + } + + /* + * Before we can issue GL commands, we need to make sure the context is current and bound to a surface. + */ + if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)) { + throwEglException("eglMakeCurrent"); + } + + GL gl = mEglContext.getGL(); + if (mGLWrapper != null) { + gl = mGLWrapper.wrap(gl); + } + + if ((mDebugFlags & (DEBUG_CHECK_GL_ERROR | DEBUG_LOG_GL_CALLS)) != 0) { + int configFlags = 0; + Writer log = null; + if ((mDebugFlags & DEBUG_CHECK_GL_ERROR) != 0) { + configFlags |= GLDebugHelper.CONFIG_CHECK_GL_ERROR; + } + if ((mDebugFlags & DEBUG_LOG_GL_CALLS) != 0) { + log = new LogWriter(); + } + gl = GLDebugHelper.wrap(gl, configFlags, log); + } + return gl; + } + + /** + * Display the current render surface. + * @return false if the context has been lost. + */ + public boolean swap () { + mEgl.eglSwapBuffers(mEglDisplay, mEglSurface); + + /* + * Always check for EGL_CONTEXT_LOST, which means the context and all associated data were lost (For instance because the + * device went to sleep). We need to sleep until we get a new surface. + */ + return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST; + } + + public void destroySurface () { + if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) { + mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); + mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, mEglSurface); + mEglSurface = null; + } + } + + public void finish () { + if (mEglContext != null) { + mEGLContextFactory.destroyContext(mEgl, mEglDisplay, mEglContext); + mEglContext = null; + } + if (mEglDisplay != null) { + mEgl.eglTerminate(mEglDisplay); + mEglDisplay = null; + } + } + + private void throwEglException (String function) { + throw new RuntimeException(function + " failed: " + mEgl.eglGetError()); + } + + EGL10 mEgl; + EGLDisplay mEglDisplay; + EGLSurface mEglSurface; + EGLConfig mEglConfig; + EGLContext mEglContext; + } + + /** + * A generic GL Thread. Takes care of initializing EGL and GL. Delegates to a Renderer instance to do the actual drawing. Can + * be configured to render continuously or on request. + * + * All potentially blocking synchronization is done through the sGLThreadManager object. This avoids multiple-lock ordering + * issues. + * + */ + class GLThread extends Thread { + GLThread (Renderer renderer) { + super(); + mWidth = 0; + mHeight = 0; + mRequestRender = true; + mRenderMode = RENDERMODE_CONTINUOUSLY; + mRenderer = renderer; + } + + @Override public void run () { + setName("GLThread " + getId()); + if (LOG_THREADS) { + Log.i("GLThread", "starting tid=" + getId()); + } + + try { + guardedRun(); + } catch (InterruptedException e) { + // fall thru and exit normally + } finally { + sGLThreadManager.threadExiting(this); + } + } + + /* + * This private method should only be called inside a synchronized(sGLThreadManager) block. + */ + private void stopEglLocked () { + if (mHaveEgl) { + mHaveEgl = false; + mEglHelper.destroySurface(); + mEglHelper.finish(); + sGLThreadManager.releaseEglSurfaceLocked(this); + } + } + + private void guardedRun () throws InterruptedException { + mEglHelper = new EglHelper(); + try { + GL10 gl = null; + boolean createEglSurface = false; + boolean sizeChanged = false; + boolean wantRenderNotification = false; + boolean doRenderNotification = false; + int w = 0; + int h = 0; + Runnable event = null; + + while (true) { + synchronized (sGLThreadManager) { + while (true) { + if (mShouldExit) { + return; + } + + if (!mEventQueue.isEmpty()) { + event = mEventQueue.remove(0); + break; + } + + // Do we need to release the EGL surface? + if (mHaveEgl && mPaused) { + if (LOG_SURFACE) { + Log.i("GLThread", "releasing EGL surface because paused tid=" + getId()); + } + stopEglLocked(); + } + + // Have we lost the surface view surface? + if ((!mHasSurface) && (!mWaitingForSurface)) { + if (LOG_SURFACE) { + Log.i("GLThread", "noticed surfaceView surface lost tid=" + getId()); + } + if (mHaveEgl) { + stopEglLocked(); + } + mWaitingForSurface = true; + sGLThreadManager.notifyAll(); + } + + // Have we acquired the surface view surface? + if (mHasSurface && mWaitingForSurface) { + if (LOG_SURFACE) { + Log.i("GLThread", "noticed surfaceView surface acquired tid=" + getId()); + } + mWaitingForSurface = false; + sGLThreadManager.notifyAll(); + } + + if (doRenderNotification) { + wantRenderNotification = false; + doRenderNotification = false; + mRenderComplete = true; + sGLThreadManager.notifyAll(); + } + + // Ready to draw? + if ((!mPaused) && mHasSurface && (mWidth > 0) && (mHeight > 0) + && (mRequestRender || (mRenderMode == RENDERMODE_CONTINUOUSLY))) { + + // If we don't have an egl surface, try to acquire one. + if ((!mHaveEgl) && sGLThreadManager.tryAcquireEglSurfaceLocked(this)) { + mHaveEgl = true; + mEglHelper.start(); + createEglSurface = true; + sizeChanged = true; + sGLThreadManager.notifyAll(); + } + + if (mHaveEgl) { + if (mSizeChanged) { + sizeChanged = true; + w = mWidth; + h = mHeight; + wantRenderNotification = true; + + if (DRAW_TWICE_AFTER_SIZE_CHANGED) { + // We keep mRequestRender true so that we draw twice after the size changes. + // (Once because of mSizeChanged, the second time because of mRequestRender.) + // This forces the updated graphics onto the screen. + } else { + mRequestRender = false; + } + mSizeChanged = false; + } else { + mRequestRender = false; + } + sGLThreadManager.notifyAll(); + break; + } + } + + // By design, this is the only place in a GLThread thread where we wait(). + if (LOG_THREADS) { + Log.i("GLThread", "waiting tid=" + getId()); + } + sGLThreadManager.wait(); + } + } // end of synchronized(sGLThreadManager) + + if (event != null) { + event.run(); + event = null; + continue; + } + + if (createEglSurface) { + gl = (GL10)mEglHelper.createSurface(getHolder()); + if (LOG_RENDERER) { + Log.w("GLThread", "onSurfaceCreated"); + } + mRenderer.onSurfaceCreated(gl, mEglHelper.mEglConfig); + createEglSurface = false; + } + + if (sizeChanged) { + if (LOG_RENDERER) { + Log.w("GLThread", "onSurfaceChanged(" + w + ", " + h + ")"); + } + mRenderer.onSurfaceChanged(gl, w, h); + sizeChanged = false; + } + + if (LOG_RENDERER) { + Log.w("GLThread", "onDrawFrame"); + } + mRenderer.onDrawFrame(gl); + if (!mEglHelper.swap()) { + if (LOG_SURFACE) { + Log.i("GLThread", "egl surface lost tid=" + getId()); + } + } + + if (wantRenderNotification) { + doRenderNotification = true; + } + } + } finally { + /* + * clean-up everything... + */ + synchronized (sGLThreadManager) { + stopEglLocked(); + } + } + } + + public void setRenderMode (int renderMode) { + if (!((RENDERMODE_WHEN_DIRTY <= renderMode) && (renderMode <= RENDERMODE_CONTINUOUSLY))) { + throw new IllegalArgumentException("renderMode"); + } + synchronized (sGLThreadManager) { + mRenderMode = renderMode; + sGLThreadManager.notifyAll(); + } + } + + public int getRenderMode () { + synchronized (sGLThreadManager) { + return mRenderMode; + } + } + + public void requestRender () { + synchronized (sGLThreadManager) { + mRequestRender = true; + sGLThreadManager.notifyAll(); + } + } + + public void surfaceCreated () { + synchronized (sGLThreadManager) { + if (LOG_THREADS) { + Log.i("GLThread", "surfaceCreated tid=" + getId()); + } + mHasSurface = true; + sGLThreadManager.notifyAll(); + } + } + + public void surfaceDestroyed () { + synchronized (sGLThreadManager) { + if (LOG_THREADS) { + Log.i("GLThread", "surfaceDestroyed tid=" + getId()); + } + mHasSurface = false; + sGLThreadManager.notifyAll(); + while ((!mWaitingForSurface) && (!mExited)) { + try { + sGLThreadManager.wait(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + } + } + + public void onPause () { + synchronized (sGLThreadManager) { + mPaused = true; + sGLThreadManager.notifyAll(); + } + } + + public void onResume () { + synchronized (sGLThreadManager) { + mPaused = false; + mRequestRender = true; + sGLThreadManager.notifyAll(); + } + } + + public void onWindowResize (int w, int h) { + synchronized (sGLThreadManager) { + mWidth = w; + mHeight = h; + mSizeChanged = true; + mRequestRender = true; + mRenderComplete = false; + sGLThreadManager.notifyAll(); + + // Wait for thread to react to resize and render a frame + while (!mExited && !mPaused && !mRenderComplete) { + if (LOG_SURFACE) { + Log.i("Main thread", "onWindowResize waiting for render complete."); + } + try { + sGLThreadManager.wait(); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + } + } + } + + public void requestExitAndWait () { + // don't call this from GLThread thread or it is a guaranteed + // deadlock! + synchronized (sGLThreadManager) { + mShouldExit = true; + sGLThreadManager.notifyAll(); + while (!mExited) { + try { + sGLThreadManager.wait(); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + } + } + } + + /** + * Queue an "event" to be run on the GL rendering thread. + * @param r the runnable to be run on the GL rendering thread. + */ + public void queueEvent (Runnable r) { + if (r == null) { + throw new IllegalArgumentException("r must not be null"); + } + synchronized (sGLThreadManager) { + mEventQueue.add(r); + sGLThreadManager.notifyAll(); + } + } + + // Once the thread is started, all accesses to the following member + // variables are protected by the sGLThreadManager monitor + private boolean mShouldExit; + private boolean mExited; + private boolean mPaused; + private boolean mHasSurface; + private boolean mWaitingForSurface; + private boolean mHaveEgl; + private int mWidth; + private int mHeight; + private int mRenderMode; + private boolean mRequestRender; + private boolean mRenderComplete; + private ArrayList mEventQueue = new ArrayList(); + // End of member variables protected by the sGLThreadManager monitor. + + private Renderer mRenderer; + private EglHelper mEglHelper; + } + + static class LogWriter extends Writer { + + @Override public void close () { + flushBuilder(); + } + + @Override public void flush () { + flushBuilder(); + } + + @Override public void write (char[] buf, int offset, int count) { + for (int i = 0; i < count; i++) { + char c = buf[offset + i]; + if (c == '\n') { + flushBuilder(); + } else { + mBuilder.append(c); + } + } + } + + private void flushBuilder () { + if (mBuilder.length() > 0) { + Log.v("GLSurfaceView", mBuilder.toString()); + mBuilder.delete(0, mBuilder.length()); + } + } + + private StringBuilder mBuilder = new StringBuilder(); + } + + private void checkRenderThreadState () { + if (mGLThread != null) { + throw new IllegalStateException("setRenderer has already been called for this instance."); + } + } + + private static class GLThreadManager { + + public synchronized void threadExiting (GLThread thread) { + if (LOG_THREADS) { + Log.i("GLThread", "exiting tid=" + thread.getId()); + } + thread.mExited = true; + if (mEglOwner == thread) { + mEglOwner = null; + } + notifyAll(); + } + + /* + * Tries once to acquire the right to use an EGL surface. Does not block. Requires that we are already in the + * sGLThreadManager monitor when this is called. + * + * @return true if the right to use an EGL surface was acquired. + */ + public boolean tryAcquireEglSurfaceLocked (GLThread thread) { + if (mEglOwner == thread || mEglOwner == null) { + mEglOwner = thread; + notifyAll(); + return true; + } + return false; + } + + /* + * Releases the EGL surface. Requires that we are already in the sGLThreadManager monitor when this is called. + */ + public void releaseEglSurfaceLocked (GLThread thread) { + if (mEglOwner == thread) { + mEglOwner = null; + } + notifyAll(); + } + + private GLThread mEglOwner; + } + + private static final GLThreadManager sGLThreadManager = new GLThreadManager(); + private boolean mSizeChanged = true; + + private GLThread mGLThread; + private EGLConfigChooser mEGLConfigChooser; + private EGLContextFactory mEGLContextFactory; + private EGLWindowSurfaceFactory mEGLWindowSurfaceFactory; + private GLWrapper mGLWrapper; + private int mDebugFlags; } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLDebugHelper.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLDebugHelper.java index 92889b291..73050b2ac 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLDebugHelper.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLDebugHelper.java @@ -1,18 +1,16 @@ /* * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. */ + package com.badlogic.gdx.backends.android.surfaceview; import java.io.Writer; @@ -22,84 +20,73 @@ import javax.microedition.khronos.opengles.GL; /** * A helper class for debugging OpenGL ES applications. - * - * Wraps the supplied GL interface with a new GL interface that adds support for - * error checking and logging. - * + * + * Wraps the supplied GL interface with a new GL interface that adds support for error checking and logging. + * */ public class GLDebugHelper { - /** - * Wrap an existing GL interface in a new GL interface that adds support for - * error checking and/or logging. - *

- * Wrapping means that the GL instance that is passed in to this method is - * wrapped inside a new GL instance that optionally performs additional - * operations before and after calling the wrapped GL instance. - *

- * Error checking means that the wrapper will automatically call - * glError after each GL operation, - * and throw a GLException if an error occurs. (By design, calling glError - * itself will not cause an exception to be thrown.) Enabling error checking - * is an alternative to manually calling glError after every GL operation. - *

- * Logging means writing a text representation of each GL method call to - * a log. - *

- * @param gl the existing GL interface. Must implement GL and GL10. May - * optionally implement GL11 as well. - * @param configFlags A bitmask of error checking flags. - * @param log - null to disable logging, non-null to enable logging. - * @return the wrapped GL instance. - */ + /** + * Wrap an existing GL interface in a new GL interface that adds support for error checking and/or logging. + *

+ * Wrapping means that the GL instance that is passed in to this method is wrapped inside a new GL instance that optionally + * performs additional operations before and after calling the wrapped GL instance. + *

+ * Error checking means that the wrapper will automatically call glError after each GL operation, and throw a GLException if an + * error occurs. (By design, calling glError itself will not cause an exception to be thrown.) Enabling error checking is an + * alternative to manually calling glError after every GL operation. + *

+ * Logging means writing a text representation of each GL method call to a log. + *

+ * @param gl the existing GL interface. Must implement GL and GL10. May optionally implement GL11 as well. + * @param configFlags A bitmask of error checking flags. + * @param log - null to disable logging, non-null to enable logging. + * @return the wrapped GL instance. + */ - /** - * Check glError() after every call. - */ - public static final int CONFIG_CHECK_GL_ERROR = (1 << 0); + /** + * Check glError() after every call. + */ + public static final int CONFIG_CHECK_GL_ERROR = (1 << 0); - /** - * Check if all calls are on the same thread. - */ - public static final int CONFIG_CHECK_THREAD = (1 << 1); + /** + * Check if all calls are on the same thread. + */ + public static final int CONFIG_CHECK_THREAD = (1 << 1); - /** - * Print argument names when logging GL Calls. - */ - public static final int CONFIG_LOG_ARGUMENT_NAMES = (1 << 2); + /** + * Print argument names when logging GL Calls. + */ + public static final int CONFIG_LOG_ARGUMENT_NAMES = (1 << 2); - /** - * The Error number used in the GLException that is thrown if - * CONFIG_CHECK_THREAD is enabled and you call OpenGL ES on the - * a different thread. - */ - public static final int ERROR_WRONG_THREAD = 0x7000; + /** + * The Error number used in the GLException that is thrown if CONFIG_CHECK_THREAD is enabled and you call OpenGL ES on the a + * different thread. + */ + public static final int ERROR_WRONG_THREAD = 0x7000; - public static GL wrap(GL gl, int configFlags, Writer log) { - if ( configFlags != 0 ) { - gl = new GLErrorWrapper(gl, configFlags); - } - if ( log != null ) { - boolean logArgumentNames = - (CONFIG_LOG_ARGUMENT_NAMES & configFlags) != 0; - gl = new GLLogWrapper(gl, log, logArgumentNames); - } - return gl; - } + public static GL wrap (GL gl, int configFlags, Writer log) { + if (configFlags != 0) { + gl = new GLErrorWrapper(gl, configFlags); + } + if (log != null) { + boolean logArgumentNames = (CONFIG_LOG_ARGUMENT_NAMES & configFlags) != 0; + gl = new GLLogWrapper(gl, log, logArgumentNames); + } + return gl; + } - /** - * Wrap an existing EGL interface in a new EGL interface that adds - * support for error checking and/or logging. - * @param egl the existing GL interface. Must implement EGL and EGL10. May - * optionally implement EGL11 as well. - * @param configFlags A bitmask of error checking flags. - * @param log - null to disable logging, non-null to enable logging. - * @return the wrapped EGL interface. - */ - public static EGL wrap(EGL egl, int configFlags, Writer log) { - if (log != null) { - egl = new EGLLogWrapper(egl, configFlags, log); - } - return egl; - } + /** + * Wrap an existing EGL interface in a new EGL interface that adds support for error checking and/or logging. + * @param egl the existing GL interface. Must implement EGL and EGL10. May optionally implement EGL11 as well. + * @param configFlags A bitmask of error checking flags. + * @param log - null to disable logging, non-null to enable logging. + * @return the wrapped EGL interface. + */ + public static EGL wrap (EGL egl, int configFlags, Writer log) { + if (log != null) { + egl = new EGLLogWrapper(egl, configFlags, log); + } + return egl; + } } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLErrorWrapper.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLErrorWrapper.java index dd43792f5..77affb55f 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLErrorWrapper.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLErrorWrapper.java @@ -1,17 +1,14 @@ /* * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. */ package com.badlogic.gdx.backends.android.surfaceview; @@ -24,938 +21,910 @@ import java.nio.ShortBuffer; import javax.microedition.khronos.opengles.GL; /** - * Implement an error checking wrapper. The wrapper will automatically call - * glError after each GL operation, and throw a GLException if an error - * occurs. (By design, calling glError itself will not cause an exception - * to be thrown.) Enabling error checking is an alternative to manually - * calling glError after every GL operation. + * Implement an error checking wrapper. The wrapper will automatically call glError after each GL operation, and throw a + * GLException if an error occurs. (By design, calling glError itself will not cause an exception to be thrown.) Enabling error + * checking is an alternative to manually calling glError after every GL operation. */ class GLErrorWrapper extends GLWrapperBase { - boolean mCheckError; - boolean mCheckThread; - Thread mOurThread; - - public GLErrorWrapper(GL gl, int configFlags) { - super(gl); - mCheckError = (configFlags & GLDebugHelper.CONFIG_CHECK_GL_ERROR) != 0; - mCheckThread = (configFlags & GLDebugHelper.CONFIG_CHECK_THREAD) != 0; - } - - private void checkThread() { - if (mCheckThread) { - Thread currentThread = Thread.currentThread(); - if (mOurThread == null) { - mOurThread = currentThread; - } else { - if (!mOurThread.equals(currentThread)) { - throw new GLException(GLDebugHelper.ERROR_WRONG_THREAD, - "OpenGL method called from wrong thread."); - } - } - } - } - - private void checkError() { - if (mCheckError) { - int glError; - if ((glError = mgl.glGetError()) != 0) { - throw new GLException(glError); - } - } - } - - // --------------------------------------------------------------------- - // GL10 methods: - - public void glActiveTexture(int texture) { - checkThread(); - mgl.glActiveTexture(texture); - checkError(); - } - - public void glAlphaFunc(int func, float ref) { - checkThread(); - mgl.glAlphaFunc(func, ref); - checkError(); - } - - public void glAlphaFuncx(int func, int ref) { - checkThread(); - mgl.glAlphaFuncx(func, ref); - checkError(); - } - - public void glBindTexture(int target, int texture) { - checkThread(); - mgl.glBindTexture(target, texture); - checkError(); - } - - public void glBlendFunc(int sfactor, int dfactor) { - checkThread(); - mgl.glBlendFunc(sfactor, dfactor); - checkError(); - } - - public void glClear(int mask) { - checkThread(); - mgl.glClear(mask); - checkError(); - } - - public void glClearColor(float red, float green, float blue, float alpha) { - checkThread(); - mgl.glClearColor(red, green, blue, alpha); - checkError(); - } - - public void glClearColorx(int red, int green, int blue, int alpha) { - checkThread(); - mgl.glClearColorx(red, green, blue, alpha); - checkError(); - } - - public void glClearDepthf(float depth) { - checkThread(); - mgl.glClearDepthf(depth); - checkError(); - } - - public void glClearDepthx(int depth) { - checkThread(); - mgl.glClearDepthx(depth); - checkError(); - } - - public void glClearStencil(int s) { - checkThread(); - mgl.glClearStencil(s); - checkError(); - } - - public void glClientActiveTexture(int texture) { - checkThread(); - mgl.glClientActiveTexture(texture); - checkError(); - } - - public void glColor4f(float red, float green, float blue, float alpha) { - checkThread(); - mgl.glColor4f(red, green, blue, alpha); - checkError(); - } - - public void glColor4x(int red, int green, int blue, int alpha) { - checkThread(); - mgl.glColor4x(red, green, blue, alpha); - checkError(); - } - - public void glColorMask(boolean red, boolean green, boolean blue, - boolean alpha) { - checkThread(); - mgl.glColorMask(red, green, blue, alpha); - checkError(); - } - - public void glColorPointer(int size, int type, int stride, Buffer pointer) { - checkThread(); - mgl.glColorPointer(size, type, stride, pointer); - checkError(); - } - - public void glCompressedTexImage2D(int target, int level, - int internalformat, int width, int height, int border, - int imageSize, Buffer data) { - checkThread(); - mgl.glCompressedTexImage2D(target, level, internalformat, width, - height, border, imageSize, data); - checkError(); - } - - public void glCompressedTexSubImage2D(int target, int level, int xoffset, - int yoffset, int width, int height, int format, int imageSize, - Buffer data) { - checkThread(); - mgl.glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, - height, format, imageSize, data); - checkError(); - } - - public void glCopyTexImage2D(int target, int level, int internalformat, - int x, int y, int width, int height, int border) { - checkThread(); - mgl.glCopyTexImage2D(target, level, internalformat, x, y, width, - height, border); - checkError(); - } - - public void glCopyTexSubImage2D(int target, int level, int xoffset, - int yoffset, int x, int y, int width, int height) { - checkThread(); - mgl.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, - height); - checkError(); - } - - public void glCullFace(int mode) { - checkThread(); - mgl.glCullFace(mode); - checkError(); - } - - public void glDeleteTextures(int n, int[] textures, int offset) { - checkThread(); - mgl.glDeleteTextures(n, textures, offset); - checkError(); - } - - public void glDeleteTextures(int n, IntBuffer textures) { - checkThread(); - mgl.glDeleteTextures(n, textures); - checkError(); - } - - public void glDepthFunc(int func) { - checkThread(); - mgl.glDepthFunc(func); - checkError(); - } - - public void glDepthMask(boolean flag) { - checkThread(); - mgl.glDepthMask(flag); - checkError(); - } - - public void glDepthRangef(float near, float far) { - checkThread(); - mgl.glDepthRangef(near, far); - checkError(); - } - - public void glDepthRangex(int near, int far) { - checkThread(); - mgl.glDepthRangex(near, far); - checkError(); - } - - public void glDisable(int cap) { - checkThread(); - mgl.glDisable(cap); - checkError(); - } - - public void glDisableClientState(int array) { - checkThread(); - mgl.glDisableClientState(array); - checkError(); - } - - public void glDrawArrays(int mode, int first, int count) { - checkThread(); - mgl.glDrawArrays(mode, first, count); - checkError(); - } - - public void glDrawElements(int mode, int count, int type, Buffer indices) { - checkThread(); - mgl.glDrawElements(mode, count, type, indices); - checkError(); - } - - public void glEnable(int cap) { - checkThread(); - mgl.glEnable(cap); - checkError(); - } - - public void glEnableClientState(int array) { - checkThread(); - mgl.glEnableClientState(array); - checkError(); - } - - public void glFinish() { - checkThread(); - mgl.glFinish(); - checkError(); - } - - public void glFlush() { - checkThread(); - mgl.glFlush(); - checkError(); - } - - public void glFogf(int pname, float param) { - checkThread(); - mgl.glFogf(pname, param); - checkError(); - } - - public void glFogfv(int pname, float[] params, int offset) { - checkThread(); - mgl.glFogfv(pname, params, offset); - checkError(); - } - - public void glFogfv(int pname, FloatBuffer params) { - checkThread(); - mgl.glFogfv(pname, params); - checkError(); - } - - public void glFogx(int pname, int param) { - checkThread(); - mgl.glFogx(pname, param); - checkError(); - } - - public void glFogxv(int pname, int[] params, int offset) { - checkThread(); - mgl.glFogxv(pname, params, offset); - checkError(); - } - - public void glFogxv(int pname, IntBuffer params) { - checkThread(); - mgl.glFogxv(pname, params); - checkError(); - } - - public void glFrontFace(int mode) { - checkThread(); - mgl.glFrontFace(mode); - checkError(); - } - - public void glFrustumf(float left, float right, float bottom, float top, - float near, float far) { - checkThread(); - mgl.glFrustumf(left, right, bottom, top, near, far); - checkError(); - } - - public void glFrustumx(int left, int right, int bottom, int top, int near, - int far) { - checkThread(); - mgl.glFrustumx(left, right, bottom, top, near, far); - checkError(); - } - - public void glGenTextures(int n, int[] textures, int offset) { - checkThread(); - mgl.glGenTextures(n, textures, offset); - checkError(); - } - - public void glGenTextures(int n, IntBuffer textures) { - checkThread(); - mgl.glGenTextures(n, textures); - checkError(); - } - - public int glGetError() { - checkThread(); - int result = mgl.glGetError(); - return result; - } - - public void glGetIntegerv(int pname, int[] params, int offset) { - checkThread(); - mgl.glGetIntegerv(pname, params, offset); - checkError(); - } - - public void glGetIntegerv(int pname, IntBuffer params) { - checkThread(); - mgl.glGetIntegerv(pname, params); - checkError(); - } - - public String glGetString(int name) { - checkThread(); - String result = mgl.glGetString(name); - checkError(); - return result; - } - - public void glHint(int target, int mode) { - checkThread(); - mgl.glHint(target, mode); - checkError(); - } - - public void glLightModelf(int pname, float param) { - checkThread(); - mgl.glLightModelf(pname, param); - checkError(); - } - - public void glLightModelfv(int pname, float[] params, int offset) { - checkThread(); - mgl.glLightModelfv(pname, params, offset); - checkError(); - } - - public void glLightModelfv(int pname, FloatBuffer params) { - checkThread(); - mgl.glLightModelfv(pname, params); - checkError(); - } - - public void glLightModelx(int pname, int param) { - checkThread(); - mgl.glLightModelx(pname, param); - checkError(); - } - - public void glLightModelxv(int pname, int[] params, int offset) { - checkThread(); - mgl.glLightModelxv(pname, params, offset); - checkError(); - } - - public void glLightModelxv(int pname, IntBuffer params) { - checkThread(); - mgl.glLightModelxv(pname, params); - checkError(); - } - - public void glLightf(int light, int pname, float param) { - checkThread(); - mgl.glLightf(light, pname, param); - checkError(); - } - - public void glLightfv(int light, int pname, float[] params, int offset) { - checkThread(); - mgl.glLightfv(light, pname, params, offset); - checkError(); - } - - public void glLightfv(int light, int pname, FloatBuffer params) { - checkThread(); - mgl.glLightfv(light, pname, params); - checkError(); - } - - public void glLightx(int light, int pname, int param) { - checkThread(); - mgl.glLightx(light, pname, param); - checkError(); - } - - public void glLightxv(int light, int pname, int[] params, int offset) { - checkThread(); - mgl.glLightxv(light, pname, params, offset); - checkError(); - } - - public void glLightxv(int light, int pname, IntBuffer params) { - checkThread(); - mgl.glLightxv(light, pname, params); - checkError(); - } - - public void glLineWidth(float width) { - checkThread(); - mgl.glLineWidth(width); - checkError(); - } - - public void glLineWidthx(int width) { - checkThread(); - mgl.glLineWidthx(width); - checkError(); - } - - public void glLoadIdentity() { - checkThread(); - mgl.glLoadIdentity(); - checkError(); - } - - public void glLoadMatrixf(float[] m, int offset) { - checkThread(); - mgl.glLoadMatrixf(m, offset); - checkError(); - } - - public void glLoadMatrixf(FloatBuffer m) { - checkThread(); - mgl.glLoadMatrixf(m); - checkError(); - } - - public void glLoadMatrixx(int[] m, int offset) { - checkThread(); - mgl.glLoadMatrixx(m, offset); - checkError(); - } - - public void glLoadMatrixx(IntBuffer m) { - checkThread(); - mgl.glLoadMatrixx(m); - checkError(); - } - - public void glLogicOp(int opcode) { - checkThread(); - mgl.glLogicOp(opcode); - checkError(); - } - - public void glMaterialf(int face, int pname, float param) { - checkThread(); - mgl.glMaterialf(face, pname, param); - checkError(); - } - - public void glMaterialfv(int face, int pname, float[] params, int offset) { - checkThread(); - mgl.glMaterialfv(face, pname, params, offset); - checkError(); - } - - public void glMaterialfv(int face, int pname, FloatBuffer params) { - checkThread(); - mgl.glMaterialfv(face, pname, params); - checkError(); - } - - public void glMaterialx(int face, int pname, int param) { - checkThread(); - mgl.glMaterialx(face, pname, param); - checkError(); - } - - public void glMaterialxv(int face, int pname, int[] params, int offset) { - checkThread(); - mgl.glMaterialxv(face, pname, params, offset); - checkError(); - } - - public void glMaterialxv(int face, int pname, IntBuffer params) { - checkThread(); - mgl.glMaterialxv(face, pname, params); - checkError(); - } - - public void glMatrixMode(int mode) { - checkThread(); - mgl.glMatrixMode(mode); - checkError(); - } - - public void glMultMatrixf(float[] m, int offset) { - checkThread(); - mgl.glMultMatrixf(m, offset); - checkError(); - } - - public void glMultMatrixf(FloatBuffer m) { - checkThread(); - mgl.glMultMatrixf(m); - checkError(); - } - - public void glMultMatrixx(int[] m, int offset) { - checkThread(); - mgl.glMultMatrixx(m, offset); - checkError(); - } - - public void glMultMatrixx(IntBuffer m) { - checkThread(); - mgl.glMultMatrixx(m); - checkError(); - } - - public void glMultiTexCoord4f(int target, - float s, float t, float r, float q) { - checkThread(); - mgl.glMultiTexCoord4f(target, s, t, r, q); - checkError(); - } - - public void glMultiTexCoord4x(int target, int s, int t, int r, int q) { - checkThread(); - mgl.glMultiTexCoord4x(target, s, t, r, q); - checkError(); - } - - public void glNormal3f(float nx, float ny, float nz) { - checkThread(); - mgl.glNormal3f(nx, ny, nz); - checkError(); - } - - public void glNormal3x(int nx, int ny, int nz) { - checkThread(); - mgl.glNormal3x(nx, ny, nz); - checkError(); - } - - public void glNormalPointer(int type, int stride, Buffer pointer) { - checkThread(); - mgl.glNormalPointer(type, stride, pointer); - checkError(); - } - - public void glOrthof(float left, float right, float bottom, float top, - float near, float far) { - checkThread(); - mgl.glOrthof(left, right, bottom, top, near, far); - checkError(); - } - - public void glOrthox(int left, int right, int bottom, int top, int near, - int far) { - checkThread(); - mgl.glOrthox(left, right, bottom, top, near, far); - checkError(); - } - - public void glPixelStorei(int pname, int param) { - checkThread(); - mgl.glPixelStorei(pname, param); - checkError(); - } - - public void glPointSize(float size) { - checkThread(); - mgl.glPointSize(size); - checkError(); - } - - public void glPointSizex(int size) { - checkThread(); - mgl.glPointSizex(size); - checkError(); - } - - public void glPolygonOffset(float factor, float units) { - checkThread(); - mgl.glPolygonOffset(factor, units); - checkError(); - } - - public void glPolygonOffsetx(int factor, int units) { - checkThread(); - mgl.glPolygonOffsetx(factor, units); - checkError(); - } - - public void glPopMatrix() { - checkThread(); - mgl.glPopMatrix(); - checkError(); - } - - public void glPushMatrix() { - checkThread(); - mgl.glPushMatrix(); - checkError(); - } - - public void glReadPixels(int x, int y, int width, int height, int format, - int type, Buffer pixels) { - checkThread(); - mgl.glReadPixels(x, y, width, height, format, type, pixels); - checkError(); - } - - public void glRotatef(float angle, float x, float y, float z) { - checkThread(); - mgl.glRotatef(angle, x, y, z); - checkError(); - } - - public void glRotatex(int angle, int x, int y, int z) { - checkThread(); - mgl.glRotatex(angle, x, y, z); - checkError(); - } - - public void glSampleCoverage(float value, boolean invert) { - checkThread(); - mgl.glSampleCoverage(value, invert); - checkError(); - } - - public void glSampleCoveragex(int value, boolean invert) { - checkThread(); - mgl.glSampleCoveragex(value, invert); - checkError(); - } - - public void glScalef(float x, float y, float z) { - checkThread(); - mgl.glScalef(x, y, z); - checkError(); - } - - public void glScalex(int x, int y, int z) { - checkThread(); - mgl.glScalex(x, y, z); - checkError(); - } - - public void glScissor(int x, int y, int width, int height) { - checkThread(); - mgl.glScissor(x, y, width, height); - checkError(); - } - - public void glShadeModel(int mode) { - checkThread(); - mgl.glShadeModel(mode); - checkError(); - } - - public void glStencilFunc(int func, int ref, int mask) { - checkThread(); - mgl.glStencilFunc(func, ref, mask); - checkError(); - } - - public void glStencilMask(int mask) { - checkThread(); - mgl.glStencilMask(mask); - checkError(); - } - - public void glStencilOp(int fail, int zfail, int zpass) { - checkThread(); - mgl.glStencilOp(fail, zfail, zpass); - checkError(); - } - - public void glTexCoordPointer(int size, int type, - int stride, Buffer pointer) { - checkThread(); - mgl.glTexCoordPointer(size, type, stride, pointer); - checkError(); - } - - public void glTexEnvf(int target, int pname, float param) { - checkThread(); - mgl.glTexEnvf(target, pname, param); - checkError(); - } - - public void glTexEnvfv(int target, int pname, float[] params, int offset) { - checkThread(); - mgl.glTexEnvfv(target, pname, params, offset); - checkError(); - } - - public void glTexEnvfv(int target, int pname, FloatBuffer params) { - checkThread(); - mgl.glTexEnvfv(target, pname, params); - checkError(); - } - - public void glTexEnvx(int target, int pname, int param) { - checkThread(); - mgl.glTexEnvx(target, pname, param); - checkError(); - } - - public void glTexEnvxv(int target, int pname, int[] params, int offset) { - checkThread(); - mgl.glTexEnvxv(target, pname, params, offset); - checkError(); - } - - public void glTexEnvxv(int target, int pname, IntBuffer params) { - checkThread(); - mgl.glTexEnvxv(target, pname, params); - checkError(); - } - - public void glTexImage2D(int target, int level, int internalformat, - int width, int height, int border, int format, int type, - Buffer pixels) { - checkThread(); - mgl.glTexImage2D(target, level, internalformat, width, height, border, - format, type, pixels); - checkError(); - } - - public void glTexParameterf(int target, int pname, float param) { - checkThread(); - mgl.glTexParameterf(target, pname, param); - checkError(); - } - - public void glTexParameterx(int target, int pname, int param) { - checkThread(); - mgl.glTexParameterx(target, pname, param); - checkError(); - } - - public void glTexParameteriv(int target, int pname, int[] params, int offset) { - checkThread(); - mgl11.glTexParameteriv(target, pname, params, offset); - checkError(); - } - - public void glTexParameteriv(int target, int pname, IntBuffer params) { - checkThread(); - mgl11.glTexParameteriv(target, pname, params); - checkError(); - } - - public void glTexSubImage2D(int target, int level, int xoffset, - int yoffset, int width, int height, int format, int type, - Buffer pixels) { - checkThread(); - mgl.glTexSubImage2D(target, level, xoffset, yoffset, width, height, - format, type, pixels); - checkError(); - } - - public void glTranslatef(float x, float y, float z) { - checkThread(); - mgl.glTranslatef(x, y, z); - checkError(); - } - - public void glTranslatex(int x, int y, int z) { - checkThread(); - mgl.glTranslatex(x, y, z); - checkError(); - } - - public void glVertexPointer(int size, int type, - int stride, Buffer pointer) { - checkThread(); - mgl.glVertexPointer(size, type, stride, pointer); - checkError(); - } - - public void glViewport(int x, int y, int width, int height) { - checkThread(); - mgl.glViewport(x, y, width, height); - checkError(); - } - - public void glClipPlanef(int plane, float[] equation, int offset) { - checkThread(); - mgl11.glClipPlanef(plane, equation, offset); - checkError(); - } - - public void glClipPlanef(int plane, FloatBuffer equation) { - checkThread(); - mgl11.glClipPlanef(plane, equation); - checkError(); - } - - public void glClipPlanex(int plane, int[] equation, int offset) { - checkThread(); - mgl11.glClipPlanex(plane, equation, offset); - checkError(); - } - - public void glClipPlanex(int plane, IntBuffer equation) { - checkThread(); - mgl11.glClipPlanex(plane, equation); - checkError(); - } - - // Draw Texture Extension - - public void glDrawTexfOES(float x, float y, float z, - float width, float height) { - checkThread(); - mgl11Ext.glDrawTexfOES(x, y, z, width, height); - checkError(); - } - - public void glDrawTexfvOES(float[] coords, int offset) { - checkThread(); - mgl11Ext.glDrawTexfvOES(coords, offset); - checkError(); - } - - public void glDrawTexfvOES(FloatBuffer coords) { - checkThread(); - mgl11Ext.glDrawTexfvOES(coords); - checkError(); - } - - public void glDrawTexiOES(int x, int y, int z, int width, int height) { - checkThread(); - mgl11Ext.glDrawTexiOES(x, y, z, width, height); - checkError(); - } - - public void glDrawTexivOES(int[] coords, int offset) { - checkThread(); - mgl11Ext.glDrawTexivOES(coords, offset); - checkError(); - } - - public void glDrawTexivOES(IntBuffer coords) { - checkThread(); - mgl11Ext.glDrawTexivOES(coords); - checkError(); - } - - public void glDrawTexsOES(short x, short y, short z, - short width, short height) { - checkThread(); - mgl11Ext.glDrawTexsOES(x, y, z, width, height); - checkError(); - } - - public void glDrawTexsvOES(short[] coords, int offset) { - checkThread(); - mgl11Ext.glDrawTexsvOES(coords, offset); - checkError(); - } - - public void glDrawTexsvOES(ShortBuffer coords) { - checkThread(); - mgl11Ext.glDrawTexsvOES(coords); - checkError(); - } - - public void glDrawTexxOES(int x, int y, int z, int width, int height) { - checkThread(); - mgl11Ext.glDrawTexxOES(x, y, z, width, height); - checkError(); - } - - public void glDrawTexxvOES(int[] coords, int offset) { - checkThread(); - mgl11Ext.glDrawTexxvOES(coords, offset); - checkError(); - } - - public void glDrawTexxvOES(IntBuffer coords) { - checkThread(); - mgl11Ext.glDrawTexxvOES(coords); - checkError(); - } - - public int glQueryMatrixxOES(int[] mantissa, int mantissaOffset, - int[] exponent, int exponentOffset) { - checkThread(); - int valid = mgl10Ext.glQueryMatrixxOES(mantissa, mantissaOffset, - exponent, exponentOffset); - checkError(); - return valid; - } - - public int glQueryMatrixxOES(IntBuffer mantissa, IntBuffer exponent) { - checkThread(); - int valid = mgl10Ext.glQueryMatrixxOES(mantissa, exponent); - checkError(); - return valid; - } -} \ No newline at end of file + boolean mCheckError; + boolean mCheckThread; + Thread mOurThread; + + public GLErrorWrapper (GL gl, int configFlags) { + super(gl); + mCheckError = (configFlags & GLDebugHelper.CONFIG_CHECK_GL_ERROR) != 0; + mCheckThread = (configFlags & GLDebugHelper.CONFIG_CHECK_THREAD) != 0; + } + + private void checkThread () { + if (mCheckThread) { + Thread currentThread = Thread.currentThread(); + if (mOurThread == null) { + mOurThread = currentThread; + } else { + if (!mOurThread.equals(currentThread)) { + throw new GLException(GLDebugHelper.ERROR_WRONG_THREAD, "OpenGL method called from wrong thread."); + } + } + } + } + + private void checkError () { + if (mCheckError) { + int glError; + if ((glError = mgl.glGetError()) != 0) { + throw new GLException(glError); + } + } + } + + // --------------------------------------------------------------------- + // GL10 methods: + + public void glActiveTexture (int texture) { + checkThread(); + mgl.glActiveTexture(texture); + checkError(); + } + + public void glAlphaFunc (int func, float ref) { + checkThread(); + mgl.glAlphaFunc(func, ref); + checkError(); + } + + public void glAlphaFuncx (int func, int ref) { + checkThread(); + mgl.glAlphaFuncx(func, ref); + checkError(); + } + + public void glBindTexture (int target, int texture) { + checkThread(); + mgl.glBindTexture(target, texture); + checkError(); + } + + public void glBlendFunc (int sfactor, int dfactor) { + checkThread(); + mgl.glBlendFunc(sfactor, dfactor); + checkError(); + } + + public void glClear (int mask) { + checkThread(); + mgl.glClear(mask); + checkError(); + } + + public void glClearColor (float red, float green, float blue, float alpha) { + checkThread(); + mgl.glClearColor(red, green, blue, alpha); + checkError(); + } + + public void glClearColorx (int red, int green, int blue, int alpha) { + checkThread(); + mgl.glClearColorx(red, green, blue, alpha); + checkError(); + } + + public void glClearDepthf (float depth) { + checkThread(); + mgl.glClearDepthf(depth); + checkError(); + } + + public void glClearDepthx (int depth) { + checkThread(); + mgl.glClearDepthx(depth); + checkError(); + } + + public void glClearStencil (int s) { + checkThread(); + mgl.glClearStencil(s); + checkError(); + } + + public void glClientActiveTexture (int texture) { + checkThread(); + mgl.glClientActiveTexture(texture); + checkError(); + } + + public void glColor4f (float red, float green, float blue, float alpha) { + checkThread(); + mgl.glColor4f(red, green, blue, alpha); + checkError(); + } + + public void glColor4x (int red, int green, int blue, int alpha) { + checkThread(); + mgl.glColor4x(red, green, blue, alpha); + checkError(); + } + + public void glColorMask (boolean red, boolean green, boolean blue, boolean alpha) { + checkThread(); + mgl.glColorMask(red, green, blue, alpha); + checkError(); + } + + public void glColorPointer (int size, int type, int stride, Buffer pointer) { + checkThread(); + mgl.glColorPointer(size, type, stride, pointer); + checkError(); + } + + public void glCompressedTexImage2D (int target, int level, int internalformat, int width, int height, int border, + int imageSize, Buffer data) { + checkThread(); + mgl.glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); + checkError(); + } + + public void glCompressedTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, int format, + int imageSize, Buffer data) { + checkThread(); + mgl.glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); + checkError(); + } + + public void glCopyTexImage2D (int target, int level, int internalformat, int x, int y, int width, int height, int border) { + checkThread(); + mgl.glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); + checkError(); + } + + public void glCopyTexSubImage2D (int target, int level, int xoffset, int yoffset, int x, int y, int width, int height) { + checkThread(); + mgl.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); + checkError(); + } + + public void glCullFace (int mode) { + checkThread(); + mgl.glCullFace(mode); + checkError(); + } + + public void glDeleteTextures (int n, int[] textures, int offset) { + checkThread(); + mgl.glDeleteTextures(n, textures, offset); + checkError(); + } + + public void glDeleteTextures (int n, IntBuffer textures) { + checkThread(); + mgl.glDeleteTextures(n, textures); + checkError(); + } + + public void glDepthFunc (int func) { + checkThread(); + mgl.glDepthFunc(func); + checkError(); + } + + public void glDepthMask (boolean flag) { + checkThread(); + mgl.glDepthMask(flag); + checkError(); + } + + public void glDepthRangef (float near, float far) { + checkThread(); + mgl.glDepthRangef(near, far); + checkError(); + } + + public void glDepthRangex (int near, int far) { + checkThread(); + mgl.glDepthRangex(near, far); + checkError(); + } + + public void glDisable (int cap) { + checkThread(); + mgl.glDisable(cap); + checkError(); + } + + public void glDisableClientState (int array) { + checkThread(); + mgl.glDisableClientState(array); + checkError(); + } + + public void glDrawArrays (int mode, int first, int count) { + checkThread(); + mgl.glDrawArrays(mode, first, count); + checkError(); + } + + public void glDrawElements (int mode, int count, int type, Buffer indices) { + checkThread(); + mgl.glDrawElements(mode, count, type, indices); + checkError(); + } + + public void glEnable (int cap) { + checkThread(); + mgl.glEnable(cap); + checkError(); + } + + public void glEnableClientState (int array) { + checkThread(); + mgl.glEnableClientState(array); + checkError(); + } + + public void glFinish () { + checkThread(); + mgl.glFinish(); + checkError(); + } + + public void glFlush () { + checkThread(); + mgl.glFlush(); + checkError(); + } + + public void glFogf (int pname, float param) { + checkThread(); + mgl.glFogf(pname, param); + checkError(); + } + + public void glFogfv (int pname, float[] params, int offset) { + checkThread(); + mgl.glFogfv(pname, params, offset); + checkError(); + } + + public void glFogfv (int pname, FloatBuffer params) { + checkThread(); + mgl.glFogfv(pname, params); + checkError(); + } + + public void glFogx (int pname, int param) { + checkThread(); + mgl.glFogx(pname, param); + checkError(); + } + + public void glFogxv (int pname, int[] params, int offset) { + checkThread(); + mgl.glFogxv(pname, params, offset); + checkError(); + } + + public void glFogxv (int pname, IntBuffer params) { + checkThread(); + mgl.glFogxv(pname, params); + checkError(); + } + + public void glFrontFace (int mode) { + checkThread(); + mgl.glFrontFace(mode); + checkError(); + } + + public void glFrustumf (float left, float right, float bottom, float top, float near, float far) { + checkThread(); + mgl.glFrustumf(left, right, bottom, top, near, far); + checkError(); + } + + public void glFrustumx (int left, int right, int bottom, int top, int near, int far) { + checkThread(); + mgl.glFrustumx(left, right, bottom, top, near, far); + checkError(); + } + + public void glGenTextures (int n, int[] textures, int offset) { + checkThread(); + mgl.glGenTextures(n, textures, offset); + checkError(); + } + + public void glGenTextures (int n, IntBuffer textures) { + checkThread(); + mgl.glGenTextures(n, textures); + checkError(); + } + + public int glGetError () { + checkThread(); + int result = mgl.glGetError(); + return result; + } + + public void glGetIntegerv (int pname, int[] params, int offset) { + checkThread(); + mgl.glGetIntegerv(pname, params, offset); + checkError(); + } + + public void glGetIntegerv (int pname, IntBuffer params) { + checkThread(); + mgl.glGetIntegerv(pname, params); + checkError(); + } + + public String glGetString (int name) { + checkThread(); + String result = mgl.glGetString(name); + checkError(); + return result; + } + + public void glHint (int target, int mode) { + checkThread(); + mgl.glHint(target, mode); + checkError(); + } + + public void glLightModelf (int pname, float param) { + checkThread(); + mgl.glLightModelf(pname, param); + checkError(); + } + + public void glLightModelfv (int pname, float[] params, int offset) { + checkThread(); + mgl.glLightModelfv(pname, params, offset); + checkError(); + } + + public void glLightModelfv (int pname, FloatBuffer params) { + checkThread(); + mgl.glLightModelfv(pname, params); + checkError(); + } + + public void glLightModelx (int pname, int param) { + checkThread(); + mgl.glLightModelx(pname, param); + checkError(); + } + + public void glLightModelxv (int pname, int[] params, int offset) { + checkThread(); + mgl.glLightModelxv(pname, params, offset); + checkError(); + } + + public void glLightModelxv (int pname, IntBuffer params) { + checkThread(); + mgl.glLightModelxv(pname, params); + checkError(); + } + + public void glLightf (int light, int pname, float param) { + checkThread(); + mgl.glLightf(light, pname, param); + checkError(); + } + + public void glLightfv (int light, int pname, float[] params, int offset) { + checkThread(); + mgl.glLightfv(light, pname, params, offset); + checkError(); + } + + public void glLightfv (int light, int pname, FloatBuffer params) { + checkThread(); + mgl.glLightfv(light, pname, params); + checkError(); + } + + public void glLightx (int light, int pname, int param) { + checkThread(); + mgl.glLightx(light, pname, param); + checkError(); + } + + public void glLightxv (int light, int pname, int[] params, int offset) { + checkThread(); + mgl.glLightxv(light, pname, params, offset); + checkError(); + } + + public void glLightxv (int light, int pname, IntBuffer params) { + checkThread(); + mgl.glLightxv(light, pname, params); + checkError(); + } + + public void glLineWidth (float width) { + checkThread(); + mgl.glLineWidth(width); + checkError(); + } + + public void glLineWidthx (int width) { + checkThread(); + mgl.glLineWidthx(width); + checkError(); + } + + public void glLoadIdentity () { + checkThread(); + mgl.glLoadIdentity(); + checkError(); + } + + public void glLoadMatrixf (float[] m, int offset) { + checkThread(); + mgl.glLoadMatrixf(m, offset); + checkError(); + } + + public void glLoadMatrixf (FloatBuffer m) { + checkThread(); + mgl.glLoadMatrixf(m); + checkError(); + } + + public void glLoadMatrixx (int[] m, int offset) { + checkThread(); + mgl.glLoadMatrixx(m, offset); + checkError(); + } + + public void glLoadMatrixx (IntBuffer m) { + checkThread(); + mgl.glLoadMatrixx(m); + checkError(); + } + + public void glLogicOp (int opcode) { + checkThread(); + mgl.glLogicOp(opcode); + checkError(); + } + + public void glMaterialf (int face, int pname, float param) { + checkThread(); + mgl.glMaterialf(face, pname, param); + checkError(); + } + + public void glMaterialfv (int face, int pname, float[] params, int offset) { + checkThread(); + mgl.glMaterialfv(face, pname, params, offset); + checkError(); + } + + public void glMaterialfv (int face, int pname, FloatBuffer params) { + checkThread(); + mgl.glMaterialfv(face, pname, params); + checkError(); + } + + public void glMaterialx (int face, int pname, int param) { + checkThread(); + mgl.glMaterialx(face, pname, param); + checkError(); + } + + public void glMaterialxv (int face, int pname, int[] params, int offset) { + checkThread(); + mgl.glMaterialxv(face, pname, params, offset); + checkError(); + } + + public void glMaterialxv (int face, int pname, IntBuffer params) { + checkThread(); + mgl.glMaterialxv(face, pname, params); + checkError(); + } + + public void glMatrixMode (int mode) { + checkThread(); + mgl.glMatrixMode(mode); + checkError(); + } + + public void glMultMatrixf (float[] m, int offset) { + checkThread(); + mgl.glMultMatrixf(m, offset); + checkError(); + } + + public void glMultMatrixf (FloatBuffer m) { + checkThread(); + mgl.glMultMatrixf(m); + checkError(); + } + + public void glMultMatrixx (int[] m, int offset) { + checkThread(); + mgl.glMultMatrixx(m, offset); + checkError(); + } + + public void glMultMatrixx (IntBuffer m) { + checkThread(); + mgl.glMultMatrixx(m); + checkError(); + } + + public void glMultiTexCoord4f (int target, float s, float t, float r, float q) { + checkThread(); + mgl.glMultiTexCoord4f(target, s, t, r, q); + checkError(); + } + + public void glMultiTexCoord4x (int target, int s, int t, int r, int q) { + checkThread(); + mgl.glMultiTexCoord4x(target, s, t, r, q); + checkError(); + } + + public void glNormal3f (float nx, float ny, float nz) { + checkThread(); + mgl.glNormal3f(nx, ny, nz); + checkError(); + } + + public void glNormal3x (int nx, int ny, int nz) { + checkThread(); + mgl.glNormal3x(nx, ny, nz); + checkError(); + } + + public void glNormalPointer (int type, int stride, Buffer pointer) { + checkThread(); + mgl.glNormalPointer(type, stride, pointer); + checkError(); + } + + public void glOrthof (float left, float right, float bottom, float top, float near, float far) { + checkThread(); + mgl.glOrthof(left, right, bottom, top, near, far); + checkError(); + } + + public void glOrthox (int left, int right, int bottom, int top, int near, int far) { + checkThread(); + mgl.glOrthox(left, right, bottom, top, near, far); + checkError(); + } + + public void glPixelStorei (int pname, int param) { + checkThread(); + mgl.glPixelStorei(pname, param); + checkError(); + } + + public void glPointSize (float size) { + checkThread(); + mgl.glPointSize(size); + checkError(); + } + + public void glPointSizex (int size) { + checkThread(); + mgl.glPointSizex(size); + checkError(); + } + + public void glPolygonOffset (float factor, float units) { + checkThread(); + mgl.glPolygonOffset(factor, units); + checkError(); + } + + public void glPolygonOffsetx (int factor, int units) { + checkThread(); + mgl.glPolygonOffsetx(factor, units); + checkError(); + } + + public void glPopMatrix () { + checkThread(); + mgl.glPopMatrix(); + checkError(); + } + + public void glPushMatrix () { + checkThread(); + mgl.glPushMatrix(); + checkError(); + } + + public void glReadPixels (int x, int y, int width, int height, int format, int type, Buffer pixels) { + checkThread(); + mgl.glReadPixels(x, y, width, height, format, type, pixels); + checkError(); + } + + public void glRotatef (float angle, float x, float y, float z) { + checkThread(); + mgl.glRotatef(angle, x, y, z); + checkError(); + } + + public void glRotatex (int angle, int x, int y, int z) { + checkThread(); + mgl.glRotatex(angle, x, y, z); + checkError(); + } + + public void glSampleCoverage (float value, boolean invert) { + checkThread(); + mgl.glSampleCoverage(value, invert); + checkError(); + } + + public void glSampleCoveragex (int value, boolean invert) { + checkThread(); + mgl.glSampleCoveragex(value, invert); + checkError(); + } + + public void glScalef (float x, float y, float z) { + checkThread(); + mgl.glScalef(x, y, z); + checkError(); + } + + public void glScalex (int x, int y, int z) { + checkThread(); + mgl.glScalex(x, y, z); + checkError(); + } + + public void glScissor (int x, int y, int width, int height) { + checkThread(); + mgl.glScissor(x, y, width, height); + checkError(); + } + + public void glShadeModel (int mode) { + checkThread(); + mgl.glShadeModel(mode); + checkError(); + } + + public void glStencilFunc (int func, int ref, int mask) { + checkThread(); + mgl.glStencilFunc(func, ref, mask); + checkError(); + } + + public void glStencilMask (int mask) { + checkThread(); + mgl.glStencilMask(mask); + checkError(); + } + + public void glStencilOp (int fail, int zfail, int zpass) { + checkThread(); + mgl.glStencilOp(fail, zfail, zpass); + checkError(); + } + + public void glTexCoordPointer (int size, int type, int stride, Buffer pointer) { + checkThread(); + mgl.glTexCoordPointer(size, type, stride, pointer); + checkError(); + } + + public void glTexEnvf (int target, int pname, float param) { + checkThread(); + mgl.glTexEnvf(target, pname, param); + checkError(); + } + + public void glTexEnvfv (int target, int pname, float[] params, int offset) { + checkThread(); + mgl.glTexEnvfv(target, pname, params, offset); + checkError(); + } + + public void glTexEnvfv (int target, int pname, FloatBuffer params) { + checkThread(); + mgl.glTexEnvfv(target, pname, params); + checkError(); + } + + public void glTexEnvx (int target, int pname, int param) { + checkThread(); + mgl.glTexEnvx(target, pname, param); + checkError(); + } + + public void glTexEnvxv (int target, int pname, int[] params, int offset) { + checkThread(); + mgl.glTexEnvxv(target, pname, params, offset); + checkError(); + } + + public void glTexEnvxv (int target, int pname, IntBuffer params) { + checkThread(); + mgl.glTexEnvxv(target, pname, params); + checkError(); + } + + public void glTexImage2D (int target, int level, int internalformat, int width, int height, int border, int format, int type, + Buffer pixels) { + checkThread(); + mgl.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); + checkError(); + } + + public void glTexParameterf (int target, int pname, float param) { + checkThread(); + mgl.glTexParameterf(target, pname, param); + checkError(); + } + + public void glTexParameterx (int target, int pname, int param) { + checkThread(); + mgl.glTexParameterx(target, pname, param); + checkError(); + } + + public void glTexParameteriv (int target, int pname, int[] params, int offset) { + checkThread(); + mgl11.glTexParameteriv(target, pname, params, offset); + checkError(); + } + + public void glTexParameteriv (int target, int pname, IntBuffer params) { + checkThread(); + mgl11.glTexParameteriv(target, pname, params); + checkError(); + } + + public void glTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, + Buffer pixels) { + checkThread(); + mgl.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); + checkError(); + } + + public void glTranslatef (float x, float y, float z) { + checkThread(); + mgl.glTranslatef(x, y, z); + checkError(); + } + + public void glTranslatex (int x, int y, int z) { + checkThread(); + mgl.glTranslatex(x, y, z); + checkError(); + } + + public void glVertexPointer (int size, int type, int stride, Buffer pointer) { + checkThread(); + mgl.glVertexPointer(size, type, stride, pointer); + checkError(); + } + + public void glViewport (int x, int y, int width, int height) { + checkThread(); + mgl.glViewport(x, y, width, height); + checkError(); + } + + public void glClipPlanef (int plane, float[] equation, int offset) { + checkThread(); + mgl11.glClipPlanef(plane, equation, offset); + checkError(); + } + + public void glClipPlanef (int plane, FloatBuffer equation) { + checkThread(); + mgl11.glClipPlanef(plane, equation); + checkError(); + } + + public void glClipPlanex (int plane, int[] equation, int offset) { + checkThread(); + mgl11.glClipPlanex(plane, equation, offset); + checkError(); + } + + public void glClipPlanex (int plane, IntBuffer equation) { + checkThread(); + mgl11.glClipPlanex(plane, equation); + checkError(); + } + + // Draw Texture Extension + + public void glDrawTexfOES (float x, float y, float z, float width, float height) { + checkThread(); + mgl11Ext.glDrawTexfOES(x, y, z, width, height); + checkError(); + } + + public void glDrawTexfvOES (float[] coords, int offset) { + checkThread(); + mgl11Ext.glDrawTexfvOES(coords, offset); + checkError(); + } + + public void glDrawTexfvOES (FloatBuffer coords) { + checkThread(); + mgl11Ext.glDrawTexfvOES(coords); + checkError(); + } + + public void glDrawTexiOES (int x, int y, int z, int width, int height) { + checkThread(); + mgl11Ext.glDrawTexiOES(x, y, z, width, height); + checkError(); + } + + public void glDrawTexivOES (int[] coords, int offset) { + checkThread(); + mgl11Ext.glDrawTexivOES(coords, offset); + checkError(); + } + + public void glDrawTexivOES (IntBuffer coords) { + checkThread(); + mgl11Ext.glDrawTexivOES(coords); + checkError(); + } + + public void glDrawTexsOES (short x, short y, short z, short width, short height) { + checkThread(); + mgl11Ext.glDrawTexsOES(x, y, z, width, height); + checkError(); + } + + public void glDrawTexsvOES (short[] coords, int offset) { + checkThread(); + mgl11Ext.glDrawTexsvOES(coords, offset); + checkError(); + } + + public void glDrawTexsvOES (ShortBuffer coords) { + checkThread(); + mgl11Ext.glDrawTexsvOES(coords); + checkError(); + } + + public void glDrawTexxOES (int x, int y, int z, int width, int height) { + checkThread(); + mgl11Ext.glDrawTexxOES(x, y, z, width, height); + checkError(); + } + + public void glDrawTexxvOES (int[] coords, int offset) { + checkThread(); + mgl11Ext.glDrawTexxvOES(coords, offset); + checkError(); + } + + public void glDrawTexxvOES (IntBuffer coords) { + checkThread(); + mgl11Ext.glDrawTexxvOES(coords); + checkError(); + } + + public int glQueryMatrixxOES (int[] mantissa, int mantissaOffset, int[] exponent, int exponentOffset) { + checkThread(); + int valid = mgl10Ext.glQueryMatrixxOES(mantissa, mantissaOffset, exponent, exponentOffset); + checkError(); + return valid; + } + + public int glQueryMatrixxOES (IntBuffer mantissa, IntBuffer exponent) { + checkThread(); + int valid = mgl10Ext.glQueryMatrixxOES(mantissa, exponent); + checkError(); + return valid; + } +} diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLException.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLException.java index 83b0f17ca..cad8f8c5c 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLException.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLException.java @@ -1,17 +1,14 @@ /* * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. */ package com.badlogic.gdx.backends.android.surfaceview; @@ -20,31 +17,30 @@ import android.opengl.GLU; /** * An exception class for OpenGL errors. - * + * */ -@SuppressWarnings("serial") -public class GLException extends RuntimeException { - public GLException(final int error) { - super(getErrorString(error)); - mError = error; - } +@SuppressWarnings("serial") public class GLException extends RuntimeException { + public GLException (final int error) { + super(getErrorString(error)); + mError = error; + } - public GLException(final int error, final String string) { - super(string); - mError = error; - } + public GLException (final int error, final String string) { + super(string); + mError = error; + } - private static String getErrorString(int error) { - String errorString = GLU.gluErrorString(error); - if ( errorString == null ) { - errorString = "Unknown error 0x" + Integer.toHexString(error); - } - return errorString; - } + private static String getErrorString (int error) { + String errorString = GLU.gluErrorString(error); + if (errorString == null) { + errorString = "Unknown error 0x" + Integer.toHexString(error); + } + return errorString; + } - int getError() { - return mError; - } + int getError () { + return mError; + } - private final int mError; + private final int mError; } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLLogWrapper.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLLogWrapper.java index 96afe89d1..05e329365 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLLogWrapper.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLLogWrapper.java @@ -1,17 +1,14 @@ /* * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. */ package com.badlogic.gdx.backends.android.surfaceview; @@ -33,3033 +30,2995 @@ import javax.microedition.khronos.opengles.GL; /** * A wrapper that logs all GL calls (and results) in human-readable form. - * + * */ class GLLogWrapper extends GLWrapperBase { - private static final int FORMAT_INT = 0; - private static final int FORMAT_FLOAT = 1; - private static final int FORMAT_FIXED = 2; - - public GLLogWrapper(GL gl, Writer log, boolean logArgumentNames) { - super(gl); - mLog = log; - mLogArgumentNames = logArgumentNames; - } - - private void checkError() { - int glError; - if ((glError = mgl.glGetError()) != 0) { - String errorMessage = "glError: " + Integer.toString(glError); - logLine(errorMessage); - } - } - - private void logLine(String message) { - log(message + '\n'); - } - - private void log(String message) { - try { - mLog.write(message); - } catch (IOException e) { - // Ignore exception, keep on trying - } - } - - private void begin(String name) { - log(name + '('); - mArgCount = 0; - } - - private void arg(String name, String value) { - if (mArgCount++ > 0) { - log(", "); - } - if (mLogArgumentNames) { - log(name + "="); - } - log(value); - } - - private void end() { - log(");\n"); - flush(); - } - - private void flush() { - try { - mLog.flush(); - } catch (IOException e) { - mLog = null; - } - } - - private void arg(String name, boolean value) { - arg(name, Boolean.toString(value)); - } - - private void arg(String name, int value) { - arg(name, Integer.toString(value)); - } - - private void arg(String name, float value) { - arg(name, Float.toString(value)); - } - - private void returns(String result) { - log(") returns " + result + ";\n"); - flush(); - } - - private void returns(int result) { - returns(Integer.toString(result)); - } - - private void arg(String name, int n, int[] arr, int offset) { - arg(name, toString(n, FORMAT_INT, arr, offset)); - } - - private void arg(String name, int n, short[] arr, int offset) { - arg(name, toString(n, arr, offset)); - } - - private void arg(String name, int n, float[] arr, int offset) { - arg(name, toString(n, arr, offset)); - } - - private void formattedAppend(StringBuilder buf, int value, int format) { - switch (format) { - case FORMAT_INT: - buf.append(value); - break; - case FORMAT_FLOAT: - buf.append(Float.intBitsToFloat(value)); - break; - case FORMAT_FIXED: - buf.append(value / 65536.0f); - break; - } - } - - private String toString(int n, int format, int[] arr, int offset) { - StringBuilder buf = new StringBuilder(); - buf.append("{\n"); - int arrLen = arr.length; - for (int i = 0; i < n; i++) { - int index = offset + i; - buf.append(" [" + index + "] = "); - if (index < 0 || index >= arrLen) { - buf.append("out of bounds"); - } else { - formattedAppend(buf, arr[index], format); - } - buf.append('\n'); - } - buf.append("}"); - return buf.toString(); - } - - private String toString(int n, short[] arr, int offset) { - StringBuilder buf = new StringBuilder(); - buf.append("{\n"); - int arrLen = arr.length; - for (int i = 0; i < n; i++) { - int index = offset + i; - buf.append(" [" + index + "] = "); - if (index < 0 || index >= arrLen) { - buf.append("out of bounds"); - } else { - buf.append(arr[index]); - } - buf.append('\n'); - } - buf.append("}"); - return buf.toString(); - } - - private String toString(int n, float[] arr, int offset) { - StringBuilder buf = new StringBuilder(); - buf.append("{\n"); - int arrLen = arr.length; - for (int i = 0; i < n; i++) { - int index = offset + i; - buf.append("[" + index + "] = "); - if (index < 0 || index >= arrLen) { - buf.append("out of bounds"); - } else { - buf.append(arr[index]); - } - buf.append('\n'); - } - buf.append("}"); - return buf.toString(); - } - - private String toString(int n, FloatBuffer buf) { - StringBuilder builder = new StringBuilder(); - builder.append("{\n"); - for (int i = 0; i < n; i++) { - builder.append(" [" + i + "] = " + buf.get(i) + '\n'); - } - builder.append("}"); - return builder.toString(); - } - - private String toString(int n, int format, IntBuffer buf) { - StringBuilder builder = new StringBuilder(); - builder.append("{\n"); - for (int i = 0; i < n; i++) { - builder.append(" [" + i + "] = "); - formattedAppend(builder, buf.get(i), format); - builder.append('\n'); - } - builder.append("}"); - return builder.toString(); - } - - private String toString(int n, ShortBuffer buf) { - StringBuilder builder = new StringBuilder(); - builder.append("{\n"); - for (int i = 0; i < n; i++) { - builder.append(" [" + i + "] = " + buf.get(i) + '\n'); - } - builder.append("}"); - return builder.toString(); - } - - private void arg(String name, int n, FloatBuffer buf) { - arg(name, toString(n, buf)); - } - - private void arg(String name, int n, IntBuffer buf) { - arg(name, toString(n, FORMAT_INT, buf)); - } - - private void arg(String name, int n, ShortBuffer buf) { - arg(name, toString(n, buf)); - } - - private void argPointer(int size, int type, int stride, Buffer pointer) { - arg("size", size); - arg("type", getPointerTypeName(type)); - arg("stride", stride); - arg("pointer", pointer.toString()); - } - - private static String getHex(int value) { - return "0x" + Integer.toHexString(value); - } - - public static String getErrorString(int error) { - switch (error) { - case GL_NO_ERROR: - return "GL_NO_ERROR"; - case GL_INVALID_ENUM: - return "GL_INVALID_ENUM"; - case GL_INVALID_VALUE: - return "GL_INVALID_VALUE"; - case GL_INVALID_OPERATION: - return "GL_INVALID_OPERATION"; - case GL_STACK_OVERFLOW: - return "GL_STACK_OVERFLOW"; - case GL_STACK_UNDERFLOW: - return "GL_STACK_UNDERFLOW"; - case GL_OUT_OF_MEMORY: - return "GL_OUT_OF_MEMORY"; - default: - return getHex(error); - } - } - - private String getClearBufferMask(int mask) { - StringBuilder b = new StringBuilder(); - if ((mask & GL_DEPTH_BUFFER_BIT) != 0) { - b.append("GL_DEPTH_BUFFER_BIT"); - mask &= ~GL_DEPTH_BUFFER_BIT; - } - if ((mask & GL_STENCIL_BUFFER_BIT) != 0) { - if (b.length() > 0) { - b.append(" | "); - } - b.append("GL_STENCIL_BUFFER_BIT"); - mask &= ~GL_STENCIL_BUFFER_BIT; - } - if ((mask & GL_COLOR_BUFFER_BIT) != 0) { - if (b.length() > 0) { - b.append(" | "); - } - b.append("GL_COLOR_BUFFER_BIT"); - mask &= ~GL_COLOR_BUFFER_BIT; - } - if (mask != 0) { - if (b.length() > 0) { - b.append(" | "); - } - b.append(getHex(mask)); - } - return b.toString(); - } - - private String getFactor(int factor) { - switch(factor) { - case GL_ZERO: - return "GL_ZERO"; - case GL_ONE: - return "GL_ONE"; - case GL_SRC_COLOR: - return "GL_SRC_COLOR"; - case GL_ONE_MINUS_SRC_COLOR: - return "GL_ONE_MINUS_SRC_COLOR"; - case GL_DST_COLOR: - return "GL_DST_COLOR"; - case GL_ONE_MINUS_DST_COLOR: - return "GL_ONE_MINUS_DST_COLOR"; - case GL_SRC_ALPHA: - return "GL_SRC_ALPHA"; - case GL_ONE_MINUS_SRC_ALPHA: - return "GL_ONE_MINUS_SRC_ALPHA"; - case GL_DST_ALPHA: - return "GL_DST_ALPHA"; - case GL_ONE_MINUS_DST_ALPHA: - return "GL_ONE_MINUS_DST_ALPHA"; - case GL_SRC_ALPHA_SATURATE: - return "GL_SRC_ALPHA_SATURATE"; - - default: - return getHex(factor); - } - } - - private String getShadeModel(int model) { - switch(model) { - case GL_FLAT: - return "GL_FLAT"; - case GL_SMOOTH: - return "GL_SMOOTH"; - default: - return getHex(model); - } - } - - private String getTextureTarget(int target) { - switch (target) { - case GL_TEXTURE_2D: - return "GL_TEXTURE_2D"; - default: - return getHex(target); - } - } - - private String getTextureEnvTarget(int target) { - switch (target) { - case GL_TEXTURE_ENV: - return "GL_TEXTURE_ENV"; - default: - return getHex(target); - } - } - - private String getTextureEnvPName(int pname) { - switch (pname) { - case GL_TEXTURE_ENV_MODE: - return "GL_TEXTURE_ENV_MODE"; - case GL_TEXTURE_ENV_COLOR: - return "GL_TEXTURE_ENV_COLOR"; - default: - return getHex(pname); - } - } - - private int getTextureEnvParamCount(int pname) { - switch (pname) { - case GL_TEXTURE_ENV_MODE: - return 1; - case GL_TEXTURE_ENV_COLOR: - return 4; - default: - return 0; - } - } - - private String getTextureEnvParamName(float param) { - int iparam = (int) param; - if (param == (float) iparam) { - switch (iparam) { - case GL_REPLACE: - return "GL_REPLACE"; - case GL_MODULATE: - return "GL_MODULATE"; - case GL_DECAL: - return "GL_DECAL"; - case GL_BLEND: - return "GL_BLEND"; - case GL_ADD: - return "GL_ADD"; - case GL_COMBINE: - return "GL_COMBINE"; - default: - return getHex(iparam); - } - } - return Float.toString(param); - } - - private String getMatrixMode(int matrixMode) { - switch (matrixMode) { - case GL_MODELVIEW: - return "GL_MODELVIEW"; - case GL_PROJECTION: - return "GL_PROJECTION"; - case GL_TEXTURE: - return "GL_TEXTURE"; - default: - return getHex(matrixMode); - } - } - - private String getClientState(int clientState) { - switch (clientState) { - case GL_COLOR_ARRAY: - return "GL_COLOR_ARRAY"; - case GL_VERTEX_ARRAY: - return "GL_VERTEX_ARRAY"; - case GL_NORMAL_ARRAY: - return "GL_NORMAL_ARRAY"; - case GL_TEXTURE_COORD_ARRAY: - return "GL_TEXTURE_COORD_ARRAY"; - default: - return getHex(clientState); - } - } - - private String getCap(int cap) { - switch (cap) { - case GL_FOG: - return "GL_FOG"; - case GL_LIGHTING: - return "GL_LIGHTING"; - case GL_TEXTURE_2D: - return "GL_TEXTURE_2D"; - case GL_CULL_FACE: - return "GL_CULL_FACE"; - case GL_ALPHA_TEST: - return "GL_ALPHA_TEST"; - case GL_BLEND: - return "GL_BLEND"; - case GL_COLOR_LOGIC_OP: - return "GL_COLOR_LOGIC_OP"; - case GL_DITHER: - return "GL_DITHER"; - case GL_STENCIL_TEST: - return "GL_STENCIL_TEST"; - case GL_DEPTH_TEST: - return "GL_DEPTH_TEST"; - case GL_LIGHT0: - return "GL_LIGHT0"; - case GL_LIGHT1: - return "GL_LIGHT1"; - case GL_LIGHT2: - return "GL_LIGHT2"; - case GL_LIGHT3: - return "GL_LIGHT3"; - case GL_LIGHT4: - return "GL_LIGHT4"; - case GL_LIGHT5: - return "GL_LIGHT5"; - case GL_LIGHT6: - return "GL_LIGHT6"; - case GL_LIGHT7: - return "GL_LIGHT7"; - case GL_POINT_SMOOTH: - return "GL_POINT_SMOOTH"; - case GL_LINE_SMOOTH: - return "GL_LINE_SMOOTH"; - case GL_COLOR_MATERIAL: - return "GL_COLOR_MATERIAL"; - case GL_NORMALIZE: - return "GL_NORMALIZE"; - case GL_RESCALE_NORMAL: - return "GL_RESCALE_NORMAL"; - case GL_VERTEX_ARRAY: - return "GL_VERTEX_ARRAY"; - case GL_NORMAL_ARRAY: - return "GL_NORMAL_ARRAY"; - case GL_COLOR_ARRAY: - return "GL_COLOR_ARRAY"; - case GL_TEXTURE_COORD_ARRAY: - return "GL_TEXTURE_COORD_ARRAY"; - case GL_MULTISAMPLE: - return "GL_MULTISAMPLE"; - case GL_SAMPLE_ALPHA_TO_COVERAGE: - return "GL_SAMPLE_ALPHA_TO_COVERAGE"; - case GL_SAMPLE_ALPHA_TO_ONE: - return "GL_SAMPLE_ALPHA_TO_ONE"; - case GL_SAMPLE_COVERAGE: - return "GL_SAMPLE_COVERAGE"; - case GL_SCISSOR_TEST: - return "GL_SCISSOR_TEST"; - default: - return getHex(cap); - } - } - - private String getTexturePName(int pname) { - switch (pname) { - case GL_TEXTURE_MAG_FILTER: - return "GL_TEXTURE_MAG_FILTER"; - case GL_TEXTURE_MIN_FILTER: - return "GL_TEXTURE_MIN_FILTER"; - case GL_TEXTURE_WRAP_S: - return "GL_TEXTURE_WRAP_S"; - case GL_TEXTURE_WRAP_T: - return "GL_TEXTURE_WRAP_T"; - case GL_GENERATE_MIPMAP: - return "GL_GENERATE_MIPMAP"; - case GL_TEXTURE_CROP_RECT_OES: - return "GL_TEXTURE_CROP_RECT_OES"; - default: - return getHex(pname); - } - } - - private String getTextureParamName(float param) { - int iparam = (int) param; - if (param == (float) iparam) { - switch (iparam) { - case GL_CLAMP_TO_EDGE: - return "GL_CLAMP_TO_EDGE"; - case GL_REPEAT: - return "GL_REPEAT"; - case GL_NEAREST: - return "GL_NEAREST"; - case GL_LINEAR: - return "GL_LINEAR"; - case GL_NEAREST_MIPMAP_NEAREST: - return "GL_NEAREST_MIPMAP_NEAREST"; - case GL_LINEAR_MIPMAP_NEAREST: - return "GL_LINEAR_MIPMAP_NEAREST"; - case GL_NEAREST_MIPMAP_LINEAR: - return "GL_NEAREST_MIPMAP_LINEAR"; - case GL_LINEAR_MIPMAP_LINEAR: - return "GL_LINEAR_MIPMAP_LINEAR"; - default: - return getHex(iparam); - } - } - return Float.toString(param); - } - - private String getFogPName(int pname) { - switch (pname) { - case GL_FOG_DENSITY: - return "GL_FOG_DENSITY"; - case GL_FOG_START: - return "GL_FOG_START"; - case GL_FOG_END: - return "GL_FOG_END"; - case GL_FOG_MODE: - return "GL_FOG_MODE"; - case GL_FOG_COLOR: - return "GL_FOG_COLOR"; - default: - return getHex(pname); - } - } - - private int getFogParamCount(int pname) { - switch (pname) { - case GL_FOG_DENSITY: - return 1; - case GL_FOG_START: - return 1; - case GL_FOG_END: - return 1; - case GL_FOG_MODE: - return 1; - case GL_FOG_COLOR: - return 4; - default: - return 0; - } - } - - private String getBeginMode(int mode) { - switch (mode) { - case GL_POINTS: - return "GL_POINTS"; - case GL_LINES: - return "GL_LINES"; - case GL_LINE_LOOP: - return "GL_LINE_LOOP"; - case GL_LINE_STRIP: - return "GL_LINE_STRIP"; - case GL_TRIANGLES: - return "GL_TRIANGLES"; - case GL_TRIANGLE_STRIP: - return "GL_TRIANGLE_STRIP"; - case GL_TRIANGLE_FAN: - return "GL_TRIANGLE_FAN"; - default: - return getHex(mode); - } - } - - private String getIndexType(int type) { - switch (type) { - case GL_UNSIGNED_SHORT: - return "GL_UNSIGNED_SHORT"; - case GL_UNSIGNED_BYTE: - return "GL_UNSIGNED_BYTE"; - default: - return getHex(type); - } - } - - private String getIntegerStateName(int pname) { - switch (pname) { - case GL_ALPHA_BITS: - return "GL_ALPHA_BITS"; - case GL_ALIASED_LINE_WIDTH_RANGE: - return "GL_ALIASED_LINE_WIDTH_RANGE"; - case GL_ALIASED_POINT_SIZE_RANGE: - return "GL_ALIASED_POINT_SIZE_RANGE"; - case GL_BLUE_BITS: - return "GL_BLUE_BITS"; - case GL_COMPRESSED_TEXTURE_FORMATS: - return "GL_COMPRESSED_TEXTURE_FORMATS"; - case GL_DEPTH_BITS: - return "GL_DEPTH_BITS"; - case GL_GREEN_BITS: - return "GL_GREEN_BITS"; - case GL_MAX_ELEMENTS_INDICES: - return "GL_MAX_ELEMENTS_INDICES"; - case GL_MAX_ELEMENTS_VERTICES: - return "GL_MAX_ELEMENTS_VERTICES"; - case GL_MAX_LIGHTS: - return "GL_MAX_LIGHTS"; - case GL_MAX_TEXTURE_SIZE: - return "GL_MAX_TEXTURE_SIZE"; - case GL_MAX_VIEWPORT_DIMS: - return "GL_MAX_VIEWPORT_DIMS"; - case GL_MAX_MODELVIEW_STACK_DEPTH: - return "GL_MAX_MODELVIEW_STACK_DEPTH"; - case GL_MAX_PROJECTION_STACK_DEPTH: - return "GL_MAX_PROJECTION_STACK_DEPTH"; - case GL_MAX_TEXTURE_STACK_DEPTH: - return "GL_MAX_TEXTURE_STACK_DEPTH"; - case GL_MAX_TEXTURE_UNITS: - return "GL_MAX_TEXTURE_UNITS"; - case GL_NUM_COMPRESSED_TEXTURE_FORMATS: - return "GL_NUM_COMPRESSED_TEXTURE_FORMATS"; - case GL_RED_BITS: - return "GL_RED_BITS"; - case GL_SMOOTH_LINE_WIDTH_RANGE: - return "GL_SMOOTH_LINE_WIDTH_RANGE"; - case GL_SMOOTH_POINT_SIZE_RANGE: - return "GL_SMOOTH_POINT_SIZE_RANGE"; - case GL_STENCIL_BITS: - return "GL_STENCIL_BITS"; - case GL_SUBPIXEL_BITS: - return "GL_SUBPIXEL_BITS"; - - case GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES: - return "GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES"; - case GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES: - return "GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES"; - case GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES: - return "GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES"; - - default: - return getHex(pname); - } - } - - private int getIntegerStateSize(int pname) { - switch (pname) { - case GL_ALPHA_BITS: - return 1; - case GL_ALIASED_LINE_WIDTH_RANGE: - return 2; - case GL_ALIASED_POINT_SIZE_RANGE: - return 2; - case GL_BLUE_BITS: - return 1; - case GL_COMPRESSED_TEXTURE_FORMATS: - // Have to ask the implementation for the size - { - int[] buffer = new int[1]; - mgl.glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, buffer, 0); - return buffer[0]; - } - case GL_DEPTH_BITS: - return 1; - case GL_GREEN_BITS: - return 1; - case GL_MAX_ELEMENTS_INDICES: - return 1; - case GL_MAX_ELEMENTS_VERTICES: - return 1; - case GL_MAX_LIGHTS: - return 1; - case GL_MAX_TEXTURE_SIZE: - return 1; - case GL_MAX_VIEWPORT_DIMS: - return 2; - case GL_MAX_MODELVIEW_STACK_DEPTH: - return 1; - case GL_MAX_PROJECTION_STACK_DEPTH: - return 1; - case GL_MAX_TEXTURE_STACK_DEPTH: - return 1; - case GL_MAX_TEXTURE_UNITS: - return 1; - case GL_NUM_COMPRESSED_TEXTURE_FORMATS: - return 1; - case GL_RED_BITS: - return 1; - case GL_SMOOTH_LINE_WIDTH_RANGE: - return 2; - case GL_SMOOTH_POINT_SIZE_RANGE: - return 2; - case GL_STENCIL_BITS: - return 1; - case GL_SUBPIXEL_BITS: - return 1; - - case GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES: - case GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES: - case GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES: - return 16; - - default: - return 0; - } - } - - private int getIntegerStateFormat(int pname) { - switch (pname) { - case GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES: - case GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES: - case GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES: - return FORMAT_FLOAT; - - default: - return FORMAT_INT; - } - } - - private String getHintTarget(int target) { - switch (target) { - case GL_FOG_HINT: - return "GL_FOG_HINT"; - case GL_LINE_SMOOTH_HINT: - return "GL_LINE_SMOOTH_HINT"; - case GL_PERSPECTIVE_CORRECTION_HINT: - return "GL_PERSPECTIVE_CORRECTION_HINT"; - case GL_POINT_SMOOTH_HINT: - return "GL_POINT_SMOOTH_HINT"; - case GL_POLYGON_SMOOTH_HINT: - return "GL_POLYGON_SMOOTH_HINT"; - case GL_GENERATE_MIPMAP_HINT: - return "GL_GENERATE_MIPMAP_HINT"; - default: - return getHex(target); - } - } - - private String getHintMode(int mode) { - switch (mode) { - case GL_FASTEST: - return "GL_FASTEST"; - case GL_NICEST: - return "GL_NICEST"; - case GL_DONT_CARE: - return "GL_DONT_CARE"; - default: - return getHex(mode); - } - } - - private String getFaceName(int face) { - switch (face) { - case GL_FRONT_AND_BACK: - return "GL_FRONT_AND_BACK"; - default: - return getHex(face); - } - } - - private String getMaterialPName(int pname) { - switch (pname) { - case GL_AMBIENT: - return "GL_AMBIENT"; - case GL_DIFFUSE: - return "GL_DIFFUSE"; - case GL_SPECULAR: - return "GL_SPECULAR"; - case GL_EMISSION: - return "GL_EMISSION"; - case GL_SHININESS: - return "GL_SHININESS"; - case GL_AMBIENT_AND_DIFFUSE: - return "GL_AMBIENT_AND_DIFFUSE"; - default: - return getHex(pname); - } - } - - private int getMaterialParamCount(int pname) { - switch (pname) { - case GL_AMBIENT: - return 4; - case GL_DIFFUSE: - return 4; - case GL_SPECULAR: - return 4; - case GL_EMISSION: - return 4; - case GL_SHININESS: - return 1; - case GL_AMBIENT_AND_DIFFUSE: - return 4; - default: - return 0; - } - } - - private String getLightName(int light) { - if (light >= GL_LIGHT0 && light <= GL_LIGHT7) { - return "GL_LIGHT" + Integer.toString(light); - } - return getHex(light); - } - - private String getLightPName(int pname) { - switch (pname) { - case GL_AMBIENT: - return "GL_AMBIENT"; - case GL_DIFFUSE: - return "GL_DIFFUSE"; - case GL_SPECULAR: - return "GL_SPECULAR"; - case GL_POSITION: - return "GL_POSITION"; - case GL_SPOT_DIRECTION: - return "GL_SPOT_DIRECTION"; - case GL_SPOT_EXPONENT: - return "GL_SPOT_EXPONENT"; - case GL_SPOT_CUTOFF: - return "GL_SPOT_CUTOFF"; - case GL_CONSTANT_ATTENUATION: - return "GL_CONSTANT_ATTENUATION"; - case GL_LINEAR_ATTENUATION: - return "GL_LINEAR_ATTENUATION"; - case GL_QUADRATIC_ATTENUATION: - return "GL_QUADRATIC_ATTENUATION"; - default: - return getHex(pname); - } - } - - private int getLightParamCount(int pname) { - switch (pname) { - case GL_AMBIENT: - return 4; - case GL_DIFFUSE: - return 4; - case GL_SPECULAR: - return 4; - case GL_POSITION: - return 4; - case GL_SPOT_DIRECTION: - return 3; - case GL_SPOT_EXPONENT: - return 1; - case GL_SPOT_CUTOFF: - return 1; - case GL_CONSTANT_ATTENUATION: - return 1; - case GL_LINEAR_ATTENUATION: - return 1; - case GL_QUADRATIC_ATTENUATION: - return 1; - default: - return 0; - } - } - - private String getLightModelPName(int pname) { - switch (pname) { - case GL_LIGHT_MODEL_AMBIENT: - return "GL_LIGHT_MODEL_AMBIENT"; - case GL_LIGHT_MODEL_TWO_SIDE: - return "GL_LIGHT_MODEL_TWO_SIDE"; - default: - return getHex(pname); - } - } - - private int getLightModelParamCount(int pname) { - switch (pname) { - case GL_LIGHT_MODEL_AMBIENT: - return 4; - case GL_LIGHT_MODEL_TWO_SIDE: - return 1; - default: - return 0; - } - } - - private String getPointerTypeName(int type) { - switch (type) { - case GL_BYTE: - return "GL_BYTE"; - case GL_UNSIGNED_BYTE: - return "GL_UNSIGNED_BYTE"; - case GL_SHORT: - return "GL_SHORT"; - case GL_FIXED: - return "GL_FIXED"; - case GL_FLOAT: - return "GL_FLOAT"; - default: - return getHex(type); - } - } - - private ByteBuffer toByteBuffer(int byteCount, Buffer input) { - ByteBuffer result = null; - boolean convertWholeBuffer = (byteCount < 0); - if (input instanceof ByteBuffer) { - ByteBuffer input2 = (ByteBuffer) input; - if (convertWholeBuffer) { - byteCount = input2.limit(); - } - result = ByteBuffer.allocate(byteCount).order(input2.order()); - int position = input2.position(); - for (int i = 0; i < byteCount; i++) { - result.put(input2.get()); - } - input2.position(position); - } else if (input instanceof CharBuffer) { - CharBuffer input2 = (CharBuffer) input; - if (convertWholeBuffer) { - byteCount = input2.limit() * 2; - } - result = ByteBuffer.allocate(byteCount).order(input2.order()); - CharBuffer result2 = result.asCharBuffer(); - int position = input2.position(); - for (int i = 0; i < byteCount / 2; i++) { - result2.put(input2.get()); - } - input2.position(position); - } else if (input instanceof ShortBuffer) { - ShortBuffer input2 = (ShortBuffer) input; - if (convertWholeBuffer) { - byteCount = input2.limit() * 2; - } - result = ByteBuffer.allocate(byteCount).order(input2.order()); - ShortBuffer result2 = result.asShortBuffer(); - int position = input2.position(); - for (int i = 0; i < byteCount / 2; i++) { - result2.put(input2.get()); - } - input2.position(position); - } else if (input instanceof IntBuffer) { - IntBuffer input2 = (IntBuffer) input; - if (convertWholeBuffer) { - byteCount = input2.limit() * 4; - } - result = ByteBuffer.allocate(byteCount).order(input2.order()); - IntBuffer result2 = result.asIntBuffer(); - int position = input2.position(); - for (int i = 0; i < byteCount / 4; i++) { - result2.put(input2.get()); - } - input2.position(position); - } else if (input instanceof FloatBuffer) { - FloatBuffer input2 = (FloatBuffer) input; - if (convertWholeBuffer) { - byteCount = input2.limit() * 4; - } - result = ByteBuffer.allocate(byteCount).order(input2.order()); - FloatBuffer result2 = result.asFloatBuffer(); - int position = input2.position(); - for (int i = 0; i < byteCount / 4; i++) { - result2.put(input2.get()); - } - input2.position(position); - } else if (input instanceof DoubleBuffer) { - DoubleBuffer input2 = (DoubleBuffer) input; - if (convertWholeBuffer) { - byteCount = input2.limit() * 8; - } - result = ByteBuffer.allocate(byteCount).order(input2.order()); - DoubleBuffer result2 = result.asDoubleBuffer(); - int position = input2.position(); - for (int i = 0; i < byteCount / 8; i++) { - result2.put(input2.get()); - } - input2.position(position); - } else if (input instanceof LongBuffer) { - LongBuffer input2 = (LongBuffer) input; - if (convertWholeBuffer) { - byteCount = input2.limit() * 8; - } - result = ByteBuffer.allocate(byteCount).order(input2.order()); - LongBuffer result2 = result.asLongBuffer(); - int position = input2.position(); - for (int i = 0; i < byteCount / 8; i++) { - result2.put(input2.get()); - } - input2.position(position); - } else { - throw new RuntimeException("Unimplemented Buffer subclass."); - } - result.rewind(); - // The OpenGL API will interpret the result in hardware byte order, - // so we better do that as well: - result.order(ByteOrder.nativeOrder()); - return result; - } - - private char[] toCharIndices(int count, int type, Buffer indices) { - char[] result = new char[count]; - switch (type) { - case GL_UNSIGNED_BYTE: { - ByteBuffer byteBuffer = toByteBuffer(count, indices); - byte[] array = byteBuffer.array(); - int offset = byteBuffer.arrayOffset(); - for (int i = 0; i < count; i++) { - result[i] = (char) (0xff & array[offset + i]); - } - } - break; - case GL_UNSIGNED_SHORT: { - CharBuffer charBuffer; - if (indices instanceof CharBuffer) { - charBuffer = (CharBuffer) indices; - } else { - ByteBuffer byteBuffer = toByteBuffer(count * 2, indices); - charBuffer = byteBuffer.asCharBuffer(); - } - int oldPosition = charBuffer.position(); - charBuffer.position(0); - charBuffer.get(result); - charBuffer.position(oldPosition); - } - break; - default: - // Don't throw an exception, because we don't want logging to - // change the behavior. - break; - } - return result; - } - - private void doArrayElement(StringBuilder builder, boolean enabled, - String name, PointerInfo pointer, int index) { - if (!enabled) { - return; - } - builder.append(" "); - builder.append(name + ":{"); - if (pointer == null) { - builder.append("undefined"); - return; - } - if (pointer.mStride < 0) { - builder.append("invalid stride"); - return; - } - - int stride = pointer.getStride(); - ByteBuffer byteBuffer = pointer.mTempByteBuffer; - int size = pointer.mSize; - int type = pointer.mType; - int sizeofType = pointer.sizeof(type); - int byteOffset = stride * index; - for (int i = 0; i < size; i++) { - if (i > 0) { - builder.append(", "); - } - switch (type) { - case GL_BYTE: { - byte d = byteBuffer.get(byteOffset); - builder.append(Integer.toString(d)); - } - break; - case GL_UNSIGNED_BYTE: { - byte d = byteBuffer.get(byteOffset); - builder.append(Integer.toString(0xff & d)); - } - break; - case GL_SHORT: { - ShortBuffer shortBuffer = byteBuffer.asShortBuffer(); - short d = shortBuffer.get(byteOffset / 2); - builder.append(Integer.toString(d)); - } - break; - case GL_FIXED: { - IntBuffer intBuffer = byteBuffer.asIntBuffer(); - int d = intBuffer.get(byteOffset / 4); - builder.append(Integer.toString(d)); - } - break; - case GL_FLOAT: { - FloatBuffer intBuffer = byteBuffer.asFloatBuffer(); - float d = intBuffer.get(byteOffset / 4); - builder.append(Float.toString(d)); - } - break; - default: - builder.append("?"); - break; - } - byteOffset += sizeofType; - } - builder.append("}"); - } - - private void doElement(StringBuilder builder, int ordinal, int vertexIndex) { - builder.append(" [" + ordinal + " : " + vertexIndex + "] ="); - doArrayElement(builder, mVertexArrayEnabled, "v", mVertexPointer, - vertexIndex); - doArrayElement(builder, mNormalArrayEnabled, "n", mNormalPointer, - vertexIndex); - doArrayElement(builder, mColorArrayEnabled, "c", mColorPointer, - vertexIndex); - doArrayElement(builder, mTextureCoordArrayEnabled, "t", - mTexCoordPointer, vertexIndex); - builder.append("\n"); - // Vertex - // Normal - // Color - // TexCoord - } - - private void bindArrays() { - if (mColorArrayEnabled) - mColorPointer.bindByteBuffer(); - if (mNormalArrayEnabled) - mNormalPointer.bindByteBuffer(); - if (mTextureCoordArrayEnabled) - mTexCoordPointer.bindByteBuffer(); - if (mVertexArrayEnabled) - mVertexPointer.bindByteBuffer(); - } - - private void unbindArrays() { - if (mColorArrayEnabled) - mColorPointer.unbindByteBuffer(); - if (mNormalArrayEnabled) - mNormalPointer.unbindByteBuffer(); - if (mTextureCoordArrayEnabled) - mTexCoordPointer.unbindByteBuffer(); - if (mVertexArrayEnabled) - mVertexPointer.unbindByteBuffer(); - } - - private void startLogIndices() { - mStringBuilder = new StringBuilder(); - mStringBuilder.append("\n"); - bindArrays(); - } - - private void endLogIndices() { - log(mStringBuilder.toString()); - unbindArrays(); - } - - // --------------------------------------------------------------------- - // GL10 methods: - - public void glActiveTexture(int texture) { - begin("glActiveTexture"); - arg("texture", texture); - end(); - mgl.glActiveTexture(texture); - checkError(); - } - - public void glAlphaFunc(int func, float ref) { - begin("glAlphaFunc"); - arg("func", func); - arg("ref", ref); - end(); - mgl.glAlphaFunc(func, ref); - checkError(); - } - - public void glAlphaFuncx(int func, int ref) { - begin("glAlphaFuncx"); - arg("func", func); - arg("ref", ref); - end(); - mgl.glAlphaFuncx(func, ref); - checkError(); - } - - public void glBindTexture(int target, int texture) { - begin("glBindTexture"); - arg("target", getTextureTarget(target)); - arg("texture", texture); - end(); - mgl.glBindTexture(target, texture); - checkError(); - } - - public void glBlendFunc(int sfactor, int dfactor) { - begin("glBlendFunc"); - arg("sfactor", getFactor(sfactor)); - arg("dfactor", getFactor(dfactor)); - end(); - - mgl.glBlendFunc(sfactor, dfactor); - checkError(); - } - - public void glClear(int mask) { - begin("glClear"); - arg("mask", getClearBufferMask(mask)); - end(); - - mgl.glClear(mask); - checkError(); - } - - public void glClearColor(float red, float green, float blue, float alpha) { - begin("glClearColor"); - arg("red", red); - arg("green", green); - arg("blue", blue); - arg("alpha", alpha); - end(); - - mgl.glClearColor(red, green, blue, alpha); - checkError(); - } - - public void glClearColorx(int red, int green, int blue, int alpha) { - begin("glClearColor"); - arg("red", red); - arg("green", green); - arg("blue", blue); - arg("alpha", alpha); - end(); - - mgl.glClearColorx(red, green, blue, alpha); - checkError(); - } - - public void glClearDepthf(float depth) { - begin("glClearDepthf"); - arg("depth", depth); - end(); - - mgl.glClearDepthf(depth); - checkError(); - } - - public void glClearDepthx(int depth) { - begin("glClearDepthx"); - arg("depth", depth); - end(); - - mgl.glClearDepthx(depth); - checkError(); - } - - public void glClearStencil(int s) { - begin("glClearStencil"); - arg("s", s); - end(); - - mgl.glClearStencil(s); - checkError(); - } - - public void glClientActiveTexture(int texture) { - begin("glClientActiveTexture"); - arg("texture", texture); - end(); - - mgl.glClientActiveTexture(texture); - checkError(); - } - - public void glColor4f(float red, float green, float blue, float alpha) { - begin("glColor4f"); - arg("red", red); - arg("green", green); - arg("blue", blue); - arg("alpha", alpha); - end(); - - mgl.glColor4f(red, green, blue, alpha); - checkError(); - } - - public void glColor4x(int red, int green, int blue, int alpha) { - begin("glColor4x"); - arg("red", red); - arg("green", green); - arg("blue", blue); - arg("alpha", alpha); - end(); - - mgl.glColor4x(red, green, blue, alpha); - checkError(); - } - - public void glColorMask(boolean red, boolean green, boolean blue, - boolean alpha) { - begin("glColorMask"); - arg("red", red); - arg("green", green); - arg("blue", blue); - arg("alpha", alpha); - end(); - - mgl.glColorMask(red, green, blue, alpha); - checkError(); - } - - public void glColorPointer(int size, int type, int stride, Buffer pointer) { - begin("glColorPointer"); - argPointer(size, type, stride, pointer); - end(); - mColorPointer = new PointerInfo(size, type, stride, pointer); - - mgl.glColorPointer(size, type, stride, pointer); - checkError(); - } - - public void glCompressedTexImage2D(int target, int level, - int internalformat, int width, int height, int border, - int imageSize, Buffer data) { - begin("glCompressedTexImage2D"); - arg("target", getTextureTarget(target)); - arg("level", level); - arg("internalformat", internalformat); - arg("width", width); - arg("height", height); - arg("border", border); - arg("imageSize", imageSize); - arg("data", data.toString()); - end(); - - mgl.glCompressedTexImage2D(target, level, internalformat, width, - height, border, imageSize, data); - checkError(); - } - - public void glCompressedTexSubImage2D(int target, int level, int xoffset, - int yoffset, int width, int height, int format, int imageSize, - Buffer data) { - begin("glCompressedTexSubImage2D"); - arg("target", getTextureTarget(target)); - arg("level", level); - arg("xoffset", xoffset); - arg("yoffset", yoffset); - arg("width", width); - arg("height", height); - arg("format", format); - arg("imageSize", imageSize); - arg("data", data.toString()); - end(); - - mgl.glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, - height, format, imageSize, data); - checkError(); - } - - public void glCopyTexImage2D(int target, int level, int internalformat, - int x, int y, int width, int height, int border) { - begin("glCopyTexImage2D"); - arg("target", getTextureTarget(target)); - arg("level", level); - arg("internalformat", internalformat); - arg("x", x); - arg("y", y); - arg("width", width); - arg("height", height); - arg("border", border); - end(); - - mgl.glCopyTexImage2D(target, level, internalformat, x, y, width, - height, border); - checkError(); - } - - public void glCopyTexSubImage2D(int target, int level, int xoffset, - int yoffset, int x, int y, int width, int height) { - begin("glCopyTexSubImage2D"); - arg("target", getTextureTarget(target)); - arg("level", level); - arg("xoffset", xoffset); - arg("yoffset", yoffset); - arg("x", x); - arg("y", y); - arg("width", width); - arg("height", height); - end(); - - mgl.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, - height); - checkError(); - } - - public void glCullFace(int mode) { - begin("glCullFace"); - arg("mode", mode); - end(); - - mgl.glCullFace(mode); - checkError(); - } - - public void glDeleteTextures(int n, int[] textures, int offset) { - begin("glDeleteTextures"); - arg("n", n); - arg("textures", n, textures, offset); - arg("offset", offset); - end(); - - mgl.glDeleteTextures(n, textures, offset); - checkError(); - } - - public void glDeleteTextures(int n, IntBuffer textures) { - begin("glDeleteTextures"); - arg("n", n); - arg("textures", n, textures); - end(); - - mgl.glDeleteTextures(n, textures); - checkError(); - } - - public void glDepthFunc(int func) { - begin("glDepthFunc"); - arg("func", func); - end(); - - mgl.glDepthFunc(func); - checkError(); - } - - public void glDepthMask(boolean flag) { - begin("glDepthMask"); - arg("flag", flag); - end(); - - mgl.glDepthMask(flag); - checkError(); - } - - public void glDepthRangef(float near, float far) { - begin("glDepthRangef"); - arg("near", near); - arg("far", far); - end(); - - mgl.glDepthRangef(near, far); - checkError(); - } - - public void glDepthRangex(int near, int far) { - begin("glDepthRangex"); - arg("near", near); - arg("far", far); - end(); - - mgl.glDepthRangex(near, far); - checkError(); - } - - public void glDisable(int cap) { - begin("glDisable"); - arg("cap", getCap(cap)); - end(); - - mgl.glDisable(cap); - checkError(); - } - - public void glDisableClientState(int array) { - begin("glDisableClientState"); - arg("array", getClientState(array)); - end(); - - switch (array) { - case GL_COLOR_ARRAY: - mColorArrayEnabled = false; - break; - case GL_NORMAL_ARRAY: - mNormalArrayEnabled = false; - break; - case GL_TEXTURE_COORD_ARRAY: - mTextureCoordArrayEnabled = false; - break; - case GL_VERTEX_ARRAY: - mVertexArrayEnabled = false; - break; - } - mgl.glDisableClientState(array); - checkError(); - } - - public void glDrawArrays(int mode, int first, int count) { - begin("glDrawArrays"); - arg("mode", mode); - arg("first", first); - arg("count", count); - startLogIndices(); - for (int i = 0; i < count; i++) { - doElement(mStringBuilder, i, first + i); - } - endLogIndices(); - end(); - - mgl.glDrawArrays(mode, first, count); - checkError(); - } - - public void glDrawElements(int mode, int count, int type, Buffer indices) { - begin("glDrawElements"); - arg("mode", getBeginMode(mode)); - arg("count", count); - arg("type", getIndexType(type)); - char[] indexArray = toCharIndices(count, type, indices); - int indexArrayLength = indexArray.length; - startLogIndices(); - for (int i = 0; i < indexArrayLength; i++) { - doElement(mStringBuilder, i, indexArray[i]); - } - endLogIndices(); - end(); - - mgl.glDrawElements(mode, count, type, indices); - checkError(); - } - - public void glEnable(int cap) { - begin("glEnable"); - arg("cap", getCap(cap)); - end(); - - mgl.glEnable(cap); - checkError(); - } - - public void glEnableClientState(int array) { - begin("glEnableClientState"); - arg("array", getClientState(array)); - end(); - - switch (array) { - case GL_COLOR_ARRAY: - mColorArrayEnabled = true; - break; - case GL_NORMAL_ARRAY: - mNormalArrayEnabled = true; - break; - case GL_TEXTURE_COORD_ARRAY: - mTextureCoordArrayEnabled = true; - break; - case GL_VERTEX_ARRAY: - mVertexArrayEnabled = true; - break; - } - mgl.glEnableClientState(array); - checkError(); - } - - public void glFinish() { - begin("glFinish"); - end(); - - mgl.glFinish(); - checkError(); - } - - public void glFlush() { - begin("glFlush"); - end(); - - mgl.glFlush(); - checkError(); - } - - public void glFogf(int pname, float param) { - begin("glFogf"); - arg("pname", pname); - arg("param", param); - end(); - - mgl.glFogf(pname, param); - checkError(); - } - - public void glFogfv(int pname, float[] params, int offset) { - begin("glFogfv"); - arg("pname", getFogPName(pname)); - arg("params", getFogParamCount(pname), params, offset); - arg("offset", offset); - end(); - - mgl.glFogfv(pname, params, offset); - checkError(); - } - - public void glFogfv(int pname, FloatBuffer params) { - begin("glFogfv"); - arg("pname", getFogPName(pname)); - arg("params", getFogParamCount(pname), params); - end(); - - mgl.glFogfv(pname, params); - checkError(); - } - - public void glFogx(int pname, int param) { - begin("glFogx"); - arg("pname", getFogPName(pname)); - arg("param", param); - end(); - - mgl.glFogx(pname, param); - checkError(); - } - - public void glFogxv(int pname, int[] params, int offset) { - begin("glFogxv"); - arg("pname", getFogPName(pname)); - arg("params", getFogParamCount(pname), params, offset); - arg("offset", offset); - end(); - - mgl.glFogxv(pname, params, offset); - checkError(); - } - - public void glFogxv(int pname, IntBuffer params) { - begin("glFogxv"); - arg("pname", getFogPName(pname)); - arg("params", getFogParamCount(pname), params); - end(); - - mgl.glFogxv(pname, params); - checkError(); - } - - public void glFrontFace(int mode) { - begin("glFrontFace"); - arg("mode", mode); - end(); - - mgl.glFrontFace(mode); - checkError(); - } - - public void glFrustumf(float left, float right, float bottom, float top, - float near, float far) { - begin("glFrustumf"); - arg("left", left); - arg("right", right); - arg("bottom", bottom); - arg("top", top); - arg("near", near); - arg("far", far); - end(); - - mgl.glFrustumf(left, right, bottom, top, near, far); - checkError(); - } - - public void glFrustumx(int left, int right, int bottom, int top, int near, - int far) { - begin("glFrustumx"); - arg("left", left); - arg("right", right); - arg("bottom", bottom); - arg("top", top); - arg("near", near); - arg("far", far); - end(); - - mgl.glFrustumx(left, right, bottom, top, near, far); - checkError(); - } - - public void glGenTextures(int n, int[] textures, int offset) { - begin("glGenTextures"); - arg("n", n); - arg("textures", Arrays.toString(textures)); - arg("offset", offset); - - mgl.glGenTextures(n, textures, offset); - - returns(toString(n, FORMAT_INT, textures, offset)); - - checkError(); - } - - public void glGenTextures(int n, IntBuffer textures) { - begin("glGenTextures"); - arg("n", n); - arg("textures", textures.toString()); - - mgl.glGenTextures(n, textures); - - returns(toString(n, FORMAT_INT, textures)); - - checkError(); - } - - public int glGetError() { - begin("glGetError"); - - int result = mgl.glGetError(); - - returns(result); - - return result; - } - - public void glGetIntegerv(int pname, int[] params, int offset) { - begin("glGetIntegerv"); - arg("pname", getIntegerStateName(pname)); - arg("params", Arrays.toString(params)); - arg("offset", offset); - - mgl.glGetIntegerv(pname, params, offset); - - returns(toString(getIntegerStateSize(pname), - getIntegerStateFormat(pname), params, offset)); - - checkError(); - } - - public void glGetIntegerv(int pname, IntBuffer params) { - begin("glGetIntegerv"); - arg("pname", getIntegerStateName(pname)); - arg("params", params.toString()); - - mgl.glGetIntegerv(pname, params); - - returns(toString(getIntegerStateSize(pname), - getIntegerStateFormat(pname), params)); - - checkError(); - } - - public String glGetString(int name) { - begin("glGetString"); - arg("name", name); - - String result = mgl.glGetString(name); - - returns(result); - - checkError(); - return result; - } - - public void glHint(int target, int mode) { - begin("glHint"); - arg("target", getHintTarget(target)); - arg("mode", getHintMode(mode)); - end(); - - mgl.glHint(target, mode); - checkError(); - } - - public void glLightModelf(int pname, float param) { - begin("glLightModelf"); - arg("pname", getLightModelPName(pname)); - arg("param", param); - end(); - - mgl.glLightModelf(pname, param); - checkError(); - } - - public void glLightModelfv(int pname, float[] params, int offset) { - begin("glLightModelfv"); - arg("pname", getLightModelPName(pname)); - arg("params", getLightModelParamCount(pname), params, offset); - arg("offset", offset); - end(); - - mgl.glLightModelfv(pname, params, offset); - checkError(); - } - - public void glLightModelfv(int pname, FloatBuffer params) { - begin("glLightModelfv"); - arg("pname", getLightModelPName(pname)); - arg("params", getLightModelParamCount(pname), params); - end(); - - mgl.glLightModelfv(pname, params); - checkError(); - } - - public void glLightModelx(int pname, int param) { - begin("glLightModelx"); - arg("pname", getLightModelPName(pname)); - arg("param", param); - end(); - - mgl.glLightModelx(pname, param); - checkError(); - } - - public void glLightModelxv(int pname, int[] params, int offset) { - begin("glLightModelxv"); - arg("pname", getLightModelPName(pname)); - arg("params", getLightModelParamCount(pname), params, offset); - arg("offset", offset); - end(); - - mgl.glLightModelxv(pname, params, offset); - checkError(); - } - - public void glLightModelxv(int pname, IntBuffer params) { - begin("glLightModelfv"); - arg("pname", getLightModelPName(pname)); - arg("params", getLightModelParamCount(pname), params); - end(); - - mgl.glLightModelxv(pname, params); - checkError(); - } - - public void glLightf(int light, int pname, float param) { - begin("glLightf"); - arg("light", getLightName(light)); - arg("pname", getLightPName(pname)); - arg("param", param); - end(); - - mgl.glLightf(light, pname, param); - checkError(); - } - - public void glLightfv(int light, int pname, float[] params, int offset) { - begin("glLightfv"); - arg("light", getLightName(light)); - arg("pname", getLightPName(pname)); - arg("params", getLightParamCount(pname), params, offset); - arg("offset", offset); - end(); - - mgl.glLightfv(light, pname, params, offset); - checkError(); - } - - public void glLightfv(int light, int pname, FloatBuffer params) { - begin("glLightfv"); - arg("light", getLightName(light)); - arg("pname", getLightPName(pname)); - arg("params", getLightParamCount(pname), params); - end(); - - mgl.glLightfv(light, pname, params); - checkError(); - } - - public void glLightx(int light, int pname, int param) { - begin("glLightx"); - arg("light", getLightName(light)); - arg("pname", getLightPName(pname)); - arg("param", param); - end(); - - mgl.glLightx(light, pname, param); - checkError(); - } - - public void glLightxv(int light, int pname, int[] params, int offset) { - begin("glLightxv"); - arg("light", getLightName(light)); - arg("pname", getLightPName(pname)); - arg("params", getLightParamCount(pname), params, offset); - arg("offset", offset); - end(); - - mgl.glLightxv(light, pname, params, offset); - checkError(); - } - - public void glLightxv(int light, int pname, IntBuffer params) { - begin("glLightxv"); - arg("light", getLightName(light)); - arg("pname", getLightPName(pname)); - arg("params", getLightParamCount(pname), params); - end(); - - mgl.glLightxv(light, pname, params); - checkError(); - } - - public void glLineWidth(float width) { - begin("glLineWidth"); - arg("width", width); - end(); - - mgl.glLineWidth(width); - checkError(); - } - - public void glLineWidthx(int width) { - begin("glLineWidthx"); - arg("width", width); - end(); - - mgl.glLineWidthx(width); - checkError(); - } - - public void glLoadIdentity() { - begin("glLoadIdentity"); - end(); - - mgl.glLoadIdentity(); - checkError(); - } - - public void glLoadMatrixf(float[] m, int offset) { - begin("glLoadMatrixf"); - arg("m", 16, m, offset); - arg("offset", offset); - end(); - - mgl.glLoadMatrixf(m, offset); - checkError(); - } - - public void glLoadMatrixf(FloatBuffer m) { - begin("glLoadMatrixf"); - arg("m", 16, m); - end(); - - mgl.glLoadMatrixf(m); - checkError(); - } - - public void glLoadMatrixx(int[] m, int offset) { - begin("glLoadMatrixx"); - arg("m", 16, m, offset); - arg("offset", offset); - end(); - - mgl.glLoadMatrixx(m, offset); - checkError(); - } - - public void glLoadMatrixx(IntBuffer m) { - begin("glLoadMatrixx"); - arg("m", 16, m); - end(); - - mgl.glLoadMatrixx(m); - checkError(); - } - - public void glLogicOp(int opcode) { - begin("glLogicOp"); - arg("opcode", opcode); - end(); - - mgl.glLogicOp(opcode); - checkError(); - } - - public void glMaterialf(int face, int pname, float param) { - begin("glMaterialf"); - arg("face", getFaceName(face)); - arg("pname", getMaterialPName(pname)); - arg("param", param); - end(); - - mgl.glMaterialf(face, pname, param); - checkError(); - } - - public void glMaterialfv(int face, int pname, float[] params, int offset) { - begin("glMaterialfv"); - arg("face", getFaceName(face)); - arg("pname", getMaterialPName(pname)); - arg("params", getMaterialParamCount(pname), params, offset); - arg("offset", offset); - end(); - - mgl.glMaterialfv(face, pname, params, offset); - checkError(); - } - - public void glMaterialfv(int face, int pname, FloatBuffer params) { - begin("glMaterialfv"); - arg("face", getFaceName(face)); - arg("pname", getMaterialPName(pname)); - arg("params", getMaterialParamCount(pname), params); - end(); - - mgl.glMaterialfv(face, pname, params); - checkError(); - } - - public void glMaterialx(int face, int pname, int param) { - begin("glMaterialx"); - arg("face", getFaceName(face)); - arg("pname", getMaterialPName(pname)); - arg("param", param); - end(); - - mgl.glMaterialx(face, pname, param); - checkError(); - } - - public void glMaterialxv(int face, int pname, int[] params, int offset) { - begin("glMaterialxv"); - arg("face", getFaceName(face)); - arg("pname", getMaterialPName(pname)); - arg("params", getMaterialParamCount(pname), params, offset); - arg("offset", offset); - end(); - - mgl.glMaterialxv(face, pname, params, offset); - checkError(); - } - - public void glMaterialxv(int face, int pname, IntBuffer params) { - begin("glMaterialxv"); - arg("face", getFaceName(face)); - arg("pname", getMaterialPName(pname)); - arg("params", getMaterialParamCount(pname), params); - end(); - - mgl.glMaterialxv(face, pname, params); - checkError(); - } - - public void glMatrixMode(int mode) { - begin("glMatrixMode"); - arg("mode", getMatrixMode(mode)); - end(); - - mgl.glMatrixMode(mode); - checkError(); - } - - public void glMultMatrixf(float[] m, int offset) { - begin("glMultMatrixf"); - arg("m", 16, m, offset); - arg("offset", offset); - end(); - - mgl.glMultMatrixf(m, offset); - checkError(); - } - - public void glMultMatrixf(FloatBuffer m) { - begin("glMultMatrixf"); - arg("m", 16, m); - end(); - - mgl.glMultMatrixf(m); - checkError(); - } - - public void glMultMatrixx(int[] m, int offset) { - begin("glMultMatrixx"); - arg("m", 16, m, offset); - arg("offset", offset); - end(); - - mgl.glMultMatrixx(m, offset); - checkError(); - } - - public void glMultMatrixx(IntBuffer m) { - begin("glMultMatrixx"); - arg("m", 16, m); - end(); - - mgl.glMultMatrixx(m); - checkError(); - } - - public void glMultiTexCoord4f(int target, float s, float t, float r, float q) { - begin("glMultiTexCoord4f"); - arg("target", target); - arg("s", s); - arg("t", t); - arg("r", r); - arg("q", q); - end(); - - mgl.glMultiTexCoord4f(target, s, t, r, q); - checkError(); - } - - public void glMultiTexCoord4x(int target, int s, int t, int r, int q) { - begin("glMultiTexCoord4x"); - arg("target", target); - arg("s", s); - arg("t", t); - arg("r", r); - arg("q", q); - end(); - - mgl.glMultiTexCoord4x(target, s, t, r, q); - checkError(); - } - - public void glNormal3f(float nx, float ny, float nz) { - begin("glNormal3f"); - arg("nx", nx); - arg("ny", ny); - arg("nz", nz); - end(); - - mgl.glNormal3f(nx, ny, nz); - checkError(); - } - - public void glNormal3x(int nx, int ny, int nz) { - begin("glNormal3x"); - arg("nx", nx); - arg("ny", ny); - arg("nz", nz); - end(); - - mgl.glNormal3x(nx, ny, nz); - checkError(); - } - - public void glNormalPointer(int type, int stride, Buffer pointer) { - begin("glNormalPointer"); - arg("type", type); - arg("stride", stride); - arg("pointer", pointer.toString()); - end(); - mNormalPointer = new PointerInfo(3, type, stride, pointer); - - mgl.glNormalPointer(type, stride, pointer); - checkError(); - } - - public void glOrthof(float left, float right, float bottom, float top, - float near, float far) { - begin("glOrthof"); - arg("left", left); - arg("right", right); - arg("bottom", bottom); - arg("top", top); - arg("near", near); - arg("far", far); - end(); - - mgl.glOrthof(left, right, bottom, top, near, far); - checkError(); - } - - public void glOrthox(int left, int right, int bottom, int top, int near, - int far) { - begin("glOrthox"); - arg("left", left); - arg("right", right); - arg("bottom", bottom); - arg("top", top); - arg("near", near); - arg("far", far); - end(); - - mgl.glOrthox(left, right, bottom, top, near, far); - checkError(); - } - - public void glPixelStorei(int pname, int param) { - begin("glPixelStorei"); - arg("pname", pname); - arg("param", param); - end(); - - mgl.glPixelStorei(pname, param); - checkError(); - } - - public void glPointSize(float size) { - begin("glPointSize"); - arg("size", size); - end(); - - mgl.glPointSize(size); - checkError(); - } - - public void glPointSizex(int size) { - begin("glPointSizex"); - arg("size", size); - end(); - - mgl.glPointSizex(size); - checkError(); - } - - public void glPolygonOffset(float factor, float units) { - begin("glPolygonOffset"); - arg("factor", factor); - arg("units", units); - end(); - mgl.glPolygonOffset(factor, units); - checkError(); - } - - public void glPolygonOffsetx(int factor, int units) { - begin("glPolygonOffsetx"); - arg("factor", factor); - arg("units", units); - end(); - - mgl.glPolygonOffsetx(factor, units); - checkError(); - } - - public void glPopMatrix() { - begin("glPopMatrix"); - end(); - - mgl.glPopMatrix(); - checkError(); - } - - public void glPushMatrix() { - begin("glPushMatrix"); - end(); - - mgl.glPushMatrix(); - checkError(); - } - - public void glReadPixels(int x, int y, int width, int height, int format, - int type, Buffer pixels) { - begin("glReadPixels"); - arg("x", x); - arg("y", y); - arg("width", width); - arg("height", height); - arg("format", format); - arg("type", type); - arg("pixels", pixels.toString()); - end(); - - mgl.glReadPixels(x, y, width, height, format, type, pixels); - checkError(); - } - - public void glRotatef(float angle, float x, float y, float z) { - begin("glRotatef"); - arg("angle", angle); - arg("x", x); - arg("y", y); - arg("z", z); - end(); - - mgl.glRotatef(angle, x, y, z); - checkError(); - } - - public void glRotatex(int angle, int x, int y, int z) { - begin("glRotatex"); - arg("angle", angle); - arg("x", x); - arg("y", y); - arg("z", z); - end(); - - mgl.glRotatex(angle, x, y, z); - checkError(); - } - - public void glSampleCoverage(float value, boolean invert) { - begin("glSampleCoveragex"); - arg("value", value); - arg("invert", invert); - end(); - - mgl.glSampleCoverage(value, invert); - checkError(); - } - - public void glSampleCoveragex(int value, boolean invert) { - begin("glSampleCoveragex"); - arg("value", value); - arg("invert", invert); - end(); - - mgl.glSampleCoveragex(value, invert); - checkError(); - } - - public void glScalef(float x, float y, float z) { - begin("glScalef"); - arg("x", x); - arg("y", y); - arg("z", z); - end(); - - mgl.glScalef(x, y, z); - checkError(); - } - - public void glScalex(int x, int y, int z) { - begin("glScalex"); - arg("x", x); - arg("y", y); - arg("z", z); - end(); - - mgl.glScalex(x, y, z); - checkError(); - } - - public void glScissor(int x, int y, int width, int height) { - begin("glScissor"); - arg("x", x); - arg("y", y); - arg("width", width); - arg("height", height); - end(); - - mgl.glScissor(x, y, width, height); - checkError(); - } - - public void glShadeModel(int mode) { - begin("glShadeModel"); - arg("mode", getShadeModel(mode)); - end(); - - mgl.glShadeModel(mode); - checkError(); - } - - public void glStencilFunc(int func, int ref, int mask) { - begin("glStencilFunc"); - arg("func", func); - arg("ref", ref); - arg("mask", mask); - end(); - - mgl.glStencilFunc(func, ref, mask); - checkError(); - } - - public void glStencilMask(int mask) { - begin("glStencilMask"); - arg("mask", mask); - end(); - - mgl.glStencilMask(mask); - checkError(); - } - - public void glStencilOp(int fail, int zfail, int zpass) { - begin("glStencilOp"); - arg("fail", fail); - arg("zfail", zfail); - arg("zpass", zpass); - end(); - - mgl.glStencilOp(fail, zfail, zpass); - checkError(); - } - - public void glTexCoordPointer(int size, int type, int stride, Buffer pointer) { - begin("glTexCoordPointer"); - argPointer(size, type, stride, pointer); - end(); - mTexCoordPointer = new PointerInfo(size, type, stride, pointer); - - mgl.glTexCoordPointer(size, type, stride, pointer); - checkError(); - } - - public void glTexEnvf(int target, int pname, float param) { - begin("glTexEnvf"); - arg("target", getTextureEnvTarget(target)); - arg("pname", getTextureEnvPName(pname)); - arg("param", getTextureEnvParamName(param)); - end(); - - mgl.glTexEnvf(target, pname, param); - checkError(); - } - - public void glTexEnvfv(int target, int pname, float[] params, int offset) { - begin("glTexEnvfv"); - arg("target", getTextureEnvTarget(target)); - arg("pname", getTextureEnvPName(pname)); - arg("params", getTextureEnvParamCount(pname), params, offset); - arg("offset", offset); - end(); - - mgl.glTexEnvfv(target, pname, params, offset); - checkError(); - } - - public void glTexEnvfv(int target, int pname, FloatBuffer params) { - begin("glTexEnvfv"); - arg("target", getTextureEnvTarget(target)); - arg("pname", getTextureEnvPName(pname)); - arg("params", getTextureEnvParamCount(pname), params); - end(); - - mgl.glTexEnvfv(target, pname, params); - checkError(); - } - - public void glTexEnvx(int target, int pname, int param) { - begin("glTexEnvx"); - arg("target", getTextureEnvTarget(target)); - arg("pname", getTextureEnvPName(pname)); - arg("param", param); - end(); - - mgl.glTexEnvx(target, pname, param); - checkError(); - } - - public void glTexEnvxv(int target, int pname, int[] params, int offset) { - begin("glTexEnvxv"); - arg("target", getTextureEnvTarget(target)); - arg("pname", getTextureEnvPName(pname)); - arg("params", getTextureEnvParamCount(pname), params, offset); - arg("offset", offset); - end(); - - mgl.glTexEnvxv(target, pname, params, offset); - checkError(); - } - - public void glTexEnvxv(int target, int pname, IntBuffer params) { - begin("glTexEnvxv"); - arg("target", getTextureEnvTarget(target)); - arg("pname", getTextureEnvPName(pname)); - arg("params", getTextureEnvParamCount(pname), params); - end(); - - mgl.glTexEnvxv(target, pname, params); - checkError(); - } - - public void glTexImage2D(int target, int level, int internalformat, - int width, int height, int border, int format, int type, - Buffer pixels) { - begin("glTexImage2D"); - arg("target", target); - arg("level", level); - arg("internalformat", internalformat); - arg("width", width); - arg("height", height); - arg("border", border); - arg("format", format); - arg("type", type); - arg("pixels", pixels.toString()); - end(); - - mgl.glTexImage2D(target, level, internalformat, width, height, border, - format, type, pixels); - checkError(); - } - - public void glTexParameterf(int target, int pname, float param) { - begin("glTexParameterf"); - arg("target", getTextureTarget(target)); - arg("pname", getTexturePName(pname)); - arg("param", getTextureParamName(param)); - end(); - - mgl.glTexParameterf(target, pname, param); - checkError(); - } - - public void glTexParameterx(int target, int pname, int param) { - begin("glTexParameterx"); - arg("target", getTextureTarget(target)); - arg("pname", getTexturePName(pname)); - arg("param", param); - end(); - - mgl.glTexParameterx(target, pname, param); - checkError(); - } - - public void glTexParameteriv(int target, int pname, int[] params, int offset) { - begin("glTexParameteriv"); - arg("target", getTextureTarget(target)); - arg("pname", getTexturePName(pname)); - arg("params", 4, params, offset); - end(); - - mgl11.glTexParameteriv(target, pname, params, offset); - checkError(); - } - - public void glTexParameteriv(int target, int pname, IntBuffer params) { - begin("glTexParameteriv"); - arg("target", getTextureTarget(target)); - arg("pname", getTexturePName(pname)); - arg("params", 4, params); - end(); - - mgl11.glTexParameteriv(target, pname, params); - checkError(); - } - - public void glTexSubImage2D(int target, int level, int xoffset, - int yoffset, int width, int height, int format, int type, - Buffer pixels) { - begin("glTexSubImage2D"); - arg("target", getTextureTarget(target)); - arg("level", level); - arg("xoffset", xoffset); - arg("yoffset", yoffset); - arg("width", width); - arg("height", height); - arg("format", format); - arg("type", type); - arg("pixels", pixels.toString()); - end(); - mgl.glTexSubImage2D(target, level, xoffset, yoffset, width, height, - format, type, pixels); - checkError(); - } - - public void glTranslatef(float x, float y, float z) { - begin("glTranslatef"); - arg("x", x); - arg("y", y); - arg("z", z); - end(); - mgl.glTranslatef(x, y, z); - checkError(); - } - - public void glTranslatex(int x, int y, int z) { - begin("glTranslatex"); - arg("x", x); - arg("y", y); - arg("z", z); - end(); - mgl.glTranslatex(x, y, z); - checkError(); - } - - public void glVertexPointer(int size, int type, int stride, Buffer pointer) { - begin("glVertexPointer"); - argPointer(size, type, stride, pointer); - end(); - mVertexPointer = new PointerInfo(size, type, stride, pointer); - mgl.glVertexPointer(size, type, stride, pointer); - checkError(); - } - - public void glViewport(int x, int y, int width, int height) { - begin("glViewport"); - arg("x", x); - arg("y", y); - arg("width", width); - arg("height", height); - end(); - mgl.glViewport(x, y, width, height); - checkError(); - } - - public void glClipPlanef(int plane, float[] equation, int offset) { - begin("glClipPlanef"); - arg("plane", plane); - arg("equation", 4, equation, offset); - arg("offset", offset); - end(); - mgl11.glClipPlanef(plane, equation, offset); - checkError(); - } - - public void glClipPlanef(int plane, FloatBuffer equation) { - begin("glClipPlanef"); - arg("plane", plane); - arg("equation", 4, equation); - end(); - mgl11.glClipPlanef(plane, equation); - checkError(); - } - - public void glClipPlanex(int plane, int[] equation, int offset) { - begin("glClipPlanex"); - arg("plane", plane); - arg("equation", 4, equation, offset); - arg("offset", offset); - end(); - mgl11.glClipPlanex(plane, equation, offset); - checkError(); - } - - public void glClipPlanex(int plane, IntBuffer equation) { - begin("glClipPlanef"); - arg("plane", plane); - arg("equation", 4, equation); - end(); - mgl11.glClipPlanex(plane, equation); - checkError(); - } - - // Draw Texture Extension - - public void glDrawTexfOES(float x, float y, float z, - float width, float height) { - begin("glDrawTexfOES"); - arg("x", x); - arg("y", y); - arg("z", z); - arg("width", width); - arg("height", height); - end(); - mgl11Ext.glDrawTexfOES(x, y, z, width, height); - checkError(); - } - - public void glDrawTexfvOES(float[] coords, int offset) { - begin("glDrawTexfvOES"); - arg("coords", 5, coords, offset); - arg("offset", offset); - end(); - mgl11Ext.glDrawTexfvOES(coords, offset); - checkError(); - } - - public void glDrawTexfvOES(FloatBuffer coords) { - begin("glDrawTexfvOES"); - arg("coords", 5, coords); - end(); - mgl11Ext.glDrawTexfvOES(coords); - checkError(); - } - - public void glDrawTexiOES(int x, int y, int z, int width, int height) { - begin("glDrawTexiOES"); - arg("x", x); - arg("y", y); - arg("z", z); - arg("width", width); - arg("height", height); - end(); - mgl11Ext.glDrawTexiOES(x, y, z, width, height); - checkError(); - } - - public void glDrawTexivOES(int[] coords, int offset) { - begin("glDrawTexivOES"); - arg("coords", 5, coords, offset); - arg("offset", offset); - end(); - mgl11Ext.glDrawTexivOES(coords, offset); - checkError(); - } - - public void glDrawTexivOES(IntBuffer coords) { - begin("glDrawTexivOES"); - arg("coords", 5, coords); - end(); - mgl11Ext.glDrawTexivOES(coords); - checkError(); - } - - public void glDrawTexsOES(short x, short y, short z, - short width, short height) { - begin("glDrawTexsOES"); - arg("x", x); - arg("y", y); - arg("z", z); - arg("width", width); - arg("height", height); - end(); - mgl11Ext.glDrawTexsOES(x, y, z, width, height); - checkError(); - } - - public void glDrawTexsvOES(short[] coords, int offset) { - begin("glDrawTexsvOES"); - arg("coords", 5, coords, offset); - arg("offset", offset); - end(); - mgl11Ext.glDrawTexsvOES(coords, offset); - checkError(); - } - - public void glDrawTexsvOES(ShortBuffer coords) { - begin("glDrawTexsvOES"); - arg("coords", 5, coords); - end(); - mgl11Ext.glDrawTexsvOES(coords); - checkError(); - } - - public void glDrawTexxOES(int x, int y, int z, int width, int height) { - begin("glDrawTexxOES"); - arg("x", x); - arg("y", y); - arg("z", z); - arg("width", width); - arg("height", height); - end(); - mgl11Ext.glDrawTexxOES(x, y, z, width, height); - checkError(); - } - - public void glDrawTexxvOES(int[] coords, int offset) { - begin("glDrawTexxvOES"); - arg("coords", 5, coords, offset); - arg("offset", offset); - end(); - mgl11Ext.glDrawTexxvOES(coords, offset); - checkError(); - } - - public void glDrawTexxvOES(IntBuffer coords) { - begin("glDrawTexxvOES"); - arg("coords", 5, coords); - end(); - mgl11Ext.glDrawTexxvOES(coords); - checkError(); - } - - public int glQueryMatrixxOES(int[] mantissa, int mantissaOffset, - int[] exponent, int exponentOffset) { - begin("glQueryMatrixxOES"); - arg("mantissa", Arrays.toString(mantissa)); - arg("exponent", Arrays.toString(exponent)); - end(); - int valid = mgl10Ext.glQueryMatrixxOES(mantissa, mantissaOffset, - exponent, exponentOffset); - returns(toString(16, FORMAT_FIXED, mantissa, mantissaOffset)); - returns(toString(16, FORMAT_INT, exponent, exponentOffset)); - checkError(); - return valid; - } - - public int glQueryMatrixxOES(IntBuffer mantissa, IntBuffer exponent) { - begin("glQueryMatrixxOES"); - arg("mantissa", mantissa.toString()); - arg("exponent", exponent.toString()); - end(); - int valid = mgl10Ext.glQueryMatrixxOES(mantissa, exponent); - returns(toString(16, FORMAT_FIXED, mantissa)); - returns(toString(16, FORMAT_INT, exponent)); - checkError(); - return valid; - } - - // Unsupported GL11 methods - - public void glBindBuffer(int target, int buffer) { - throw new UnsupportedOperationException(); - } - - public void glBufferData(int target, int size, Buffer data, int usage) { - throw new UnsupportedOperationException(); - } - - public void glBufferSubData(int target, int offset, int size, Buffer data) { - throw new UnsupportedOperationException(); - } - - public void glColor4ub(byte red, byte green, byte blue, byte alpha) { - throw new UnsupportedOperationException(); - } - - public void glDeleteBuffers(int n, int[] buffers, int offset) { - throw new UnsupportedOperationException(); - } - - public void glDeleteBuffers(int n, IntBuffer buffers) { - throw new UnsupportedOperationException(); - } - - public void glGenBuffers(int n, int[] buffers, int offset) { - throw new UnsupportedOperationException(); - } - - public void glGenBuffers(int n, IntBuffer buffers) { - throw new UnsupportedOperationException(); - } - - public void glGetBooleanv(int pname, boolean[] params, int offset) { - throw new UnsupportedOperationException(); - } - - public void glGetBooleanv(int pname, IntBuffer params) { - throw new UnsupportedOperationException(); - } - - public void glGetBufferParameteriv(int target, int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } - - public void glGetBufferParameteriv(int target, int pname, IntBuffer params) { - throw new UnsupportedOperationException(); - } - - public void glGetClipPlanef(int pname, float[] eqn, int offset) { - throw new UnsupportedOperationException(); - } - - public void glGetClipPlanef(int pname, FloatBuffer eqn) { - throw new UnsupportedOperationException(); - } - - public void glGetClipPlanex(int pname, int[] eqn, int offset) { - throw new UnsupportedOperationException(); - } - - public void glGetClipPlanex(int pname, IntBuffer eqn) { - throw new UnsupportedOperationException(); - } - - public void glGetFixedv(int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } - - public void glGetFixedv(int pname, IntBuffer params) { - throw new UnsupportedOperationException(); - } - - public void glGetFloatv(int pname, float[] params, int offset) { - throw new UnsupportedOperationException(); - } - - public void glGetFloatv(int pname, FloatBuffer params) { - throw new UnsupportedOperationException(); - } - - public void glGetLightfv(int light, int pname, float[] params, int offset) { - throw new UnsupportedOperationException(); - } - - public void glGetLightfv(int light, int pname, FloatBuffer params) { - throw new UnsupportedOperationException(); - } - - public void glGetLightxv(int light, int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } + private static final int FORMAT_INT = 0; + private static final int FORMAT_FLOAT = 1; + private static final int FORMAT_FIXED = 2; + + public GLLogWrapper (GL gl, Writer log, boolean logArgumentNames) { + super(gl); + mLog = log; + mLogArgumentNames = logArgumentNames; + } + + private void checkError () { + int glError; + if ((glError = mgl.glGetError()) != 0) { + String errorMessage = "glError: " + Integer.toString(glError); + logLine(errorMessage); + } + } + + private void logLine (String message) { + log(message + '\n'); + } + + private void log (String message) { + try { + mLog.write(message); + } catch (IOException e) { + // Ignore exception, keep on trying + } + } + + private void begin (String name) { + log(name + '('); + mArgCount = 0; + } + + private void arg (String name, String value) { + if (mArgCount++ > 0) { + log(", "); + } + if (mLogArgumentNames) { + log(name + "="); + } + log(value); + } + + private void end () { + log(");\n"); + flush(); + } + + private void flush () { + try { + mLog.flush(); + } catch (IOException e) { + mLog = null; + } + } + + private void arg (String name, boolean value) { + arg(name, Boolean.toString(value)); + } + + private void arg (String name, int value) { + arg(name, Integer.toString(value)); + } + + private void arg (String name, float value) { + arg(name, Float.toString(value)); + } + + private void returns (String result) { + log(") returns " + result + ";\n"); + flush(); + } + + private void returns (int result) { + returns(Integer.toString(result)); + } + + private void arg (String name, int n, int[] arr, int offset) { + arg(name, toString(n, FORMAT_INT, arr, offset)); + } + + private void arg (String name, int n, short[] arr, int offset) { + arg(name, toString(n, arr, offset)); + } + + private void arg (String name, int n, float[] arr, int offset) { + arg(name, toString(n, arr, offset)); + } + + private void formattedAppend (StringBuilder buf, int value, int format) { + switch (format) { + case FORMAT_INT: + buf.append(value); + break; + case FORMAT_FLOAT: + buf.append(Float.intBitsToFloat(value)); + break; + case FORMAT_FIXED: + buf.append(value / 65536.0f); + break; + } + } + + private String toString (int n, int format, int[] arr, int offset) { + StringBuilder buf = new StringBuilder(); + buf.append("{\n"); + int arrLen = arr.length; + for (int i = 0; i < n; i++) { + int index = offset + i; + buf.append(" [" + index + "] = "); + if (index < 0 || index >= arrLen) { + buf.append("out of bounds"); + } else { + formattedAppend(buf, arr[index], format); + } + buf.append('\n'); + } + buf.append("}"); + return buf.toString(); + } + + private String toString (int n, short[] arr, int offset) { + StringBuilder buf = new StringBuilder(); + buf.append("{\n"); + int arrLen = arr.length; + for (int i = 0; i < n; i++) { + int index = offset + i; + buf.append(" [" + index + "] = "); + if (index < 0 || index >= arrLen) { + buf.append("out of bounds"); + } else { + buf.append(arr[index]); + } + buf.append('\n'); + } + buf.append("}"); + return buf.toString(); + } + + private String toString (int n, float[] arr, int offset) { + StringBuilder buf = new StringBuilder(); + buf.append("{\n"); + int arrLen = arr.length; + for (int i = 0; i < n; i++) { + int index = offset + i; + buf.append("[" + index + "] = "); + if (index < 0 || index >= arrLen) { + buf.append("out of bounds"); + } else { + buf.append(arr[index]); + } + buf.append('\n'); + } + buf.append("}"); + return buf.toString(); + } + + private String toString (int n, FloatBuffer buf) { + StringBuilder builder = new StringBuilder(); + builder.append("{\n"); + for (int i = 0; i < n; i++) { + builder.append(" [" + i + "] = " + buf.get(i) + '\n'); + } + builder.append("}"); + return builder.toString(); + } + + private String toString (int n, int format, IntBuffer buf) { + StringBuilder builder = new StringBuilder(); + builder.append("{\n"); + for (int i = 0; i < n; i++) { + builder.append(" [" + i + "] = "); + formattedAppend(builder, buf.get(i), format); + builder.append('\n'); + } + builder.append("}"); + return builder.toString(); + } + + private String toString (int n, ShortBuffer buf) { + StringBuilder builder = new StringBuilder(); + builder.append("{\n"); + for (int i = 0; i < n; i++) { + builder.append(" [" + i + "] = " + buf.get(i) + '\n'); + } + builder.append("}"); + return builder.toString(); + } + + private void arg (String name, int n, FloatBuffer buf) { + arg(name, toString(n, buf)); + } + + private void arg (String name, int n, IntBuffer buf) { + arg(name, toString(n, FORMAT_INT, buf)); + } + + private void arg (String name, int n, ShortBuffer buf) { + arg(name, toString(n, buf)); + } + + private void argPointer (int size, int type, int stride, Buffer pointer) { + arg("size", size); + arg("type", getPointerTypeName(type)); + arg("stride", stride); + arg("pointer", pointer.toString()); + } + + private static String getHex (int value) { + return "0x" + Integer.toHexString(value); + } + + public static String getErrorString (int error) { + switch (error) { + case GL_NO_ERROR: + return "GL_NO_ERROR"; + case GL_INVALID_ENUM: + return "GL_INVALID_ENUM"; + case GL_INVALID_VALUE: + return "GL_INVALID_VALUE"; + case GL_INVALID_OPERATION: + return "GL_INVALID_OPERATION"; + case GL_STACK_OVERFLOW: + return "GL_STACK_OVERFLOW"; + case GL_STACK_UNDERFLOW: + return "GL_STACK_UNDERFLOW"; + case GL_OUT_OF_MEMORY: + return "GL_OUT_OF_MEMORY"; + default: + return getHex(error); + } + } + + private String getClearBufferMask (int mask) { + StringBuilder b = new StringBuilder(); + if ((mask & GL_DEPTH_BUFFER_BIT) != 0) { + b.append("GL_DEPTH_BUFFER_BIT"); + mask &= ~GL_DEPTH_BUFFER_BIT; + } + if ((mask & GL_STENCIL_BUFFER_BIT) != 0) { + if (b.length() > 0) { + b.append(" | "); + } + b.append("GL_STENCIL_BUFFER_BIT"); + mask &= ~GL_STENCIL_BUFFER_BIT; + } + if ((mask & GL_COLOR_BUFFER_BIT) != 0) { + if (b.length() > 0) { + b.append(" | "); + } + b.append("GL_COLOR_BUFFER_BIT"); + mask &= ~GL_COLOR_BUFFER_BIT; + } + if (mask != 0) { + if (b.length() > 0) { + b.append(" | "); + } + b.append(getHex(mask)); + } + return b.toString(); + } + + private String getFactor (int factor) { + switch (factor) { + case GL_ZERO: + return "GL_ZERO"; + case GL_ONE: + return "GL_ONE"; + case GL_SRC_COLOR: + return "GL_SRC_COLOR"; + case GL_ONE_MINUS_SRC_COLOR: + return "GL_ONE_MINUS_SRC_COLOR"; + case GL_DST_COLOR: + return "GL_DST_COLOR"; + case GL_ONE_MINUS_DST_COLOR: + return "GL_ONE_MINUS_DST_COLOR"; + case GL_SRC_ALPHA: + return "GL_SRC_ALPHA"; + case GL_ONE_MINUS_SRC_ALPHA: + return "GL_ONE_MINUS_SRC_ALPHA"; + case GL_DST_ALPHA: + return "GL_DST_ALPHA"; + case GL_ONE_MINUS_DST_ALPHA: + return "GL_ONE_MINUS_DST_ALPHA"; + case GL_SRC_ALPHA_SATURATE: + return "GL_SRC_ALPHA_SATURATE"; + + default: + return getHex(factor); + } + } + + private String getShadeModel (int model) { + switch (model) { + case GL_FLAT: + return "GL_FLAT"; + case GL_SMOOTH: + return "GL_SMOOTH"; + default: + return getHex(model); + } + } + + private String getTextureTarget (int target) { + switch (target) { + case GL_TEXTURE_2D: + return "GL_TEXTURE_2D"; + default: + return getHex(target); + } + } + + private String getTextureEnvTarget (int target) { + switch (target) { + case GL_TEXTURE_ENV: + return "GL_TEXTURE_ENV"; + default: + return getHex(target); + } + } + + private String getTextureEnvPName (int pname) { + switch (pname) { + case GL_TEXTURE_ENV_MODE: + return "GL_TEXTURE_ENV_MODE"; + case GL_TEXTURE_ENV_COLOR: + return "GL_TEXTURE_ENV_COLOR"; + default: + return getHex(pname); + } + } + + private int getTextureEnvParamCount (int pname) { + switch (pname) { + case GL_TEXTURE_ENV_MODE: + return 1; + case GL_TEXTURE_ENV_COLOR: + return 4; + default: + return 0; + } + } + + private String getTextureEnvParamName (float param) { + int iparam = (int)param; + if (param == (float)iparam) { + switch (iparam) { + case GL_REPLACE: + return "GL_REPLACE"; + case GL_MODULATE: + return "GL_MODULATE"; + case GL_DECAL: + return "GL_DECAL"; + case GL_BLEND: + return "GL_BLEND"; + case GL_ADD: + return "GL_ADD"; + case GL_COMBINE: + return "GL_COMBINE"; + default: + return getHex(iparam); + } + } + return Float.toString(param); + } + + private String getMatrixMode (int matrixMode) { + switch (matrixMode) { + case GL_MODELVIEW: + return "GL_MODELVIEW"; + case GL_PROJECTION: + return "GL_PROJECTION"; + case GL_TEXTURE: + return "GL_TEXTURE"; + default: + return getHex(matrixMode); + } + } + + private String getClientState (int clientState) { + switch (clientState) { + case GL_COLOR_ARRAY: + return "GL_COLOR_ARRAY"; + case GL_VERTEX_ARRAY: + return "GL_VERTEX_ARRAY"; + case GL_NORMAL_ARRAY: + return "GL_NORMAL_ARRAY"; + case GL_TEXTURE_COORD_ARRAY: + return "GL_TEXTURE_COORD_ARRAY"; + default: + return getHex(clientState); + } + } + + private String getCap (int cap) { + switch (cap) { + case GL_FOG: + return "GL_FOG"; + case GL_LIGHTING: + return "GL_LIGHTING"; + case GL_TEXTURE_2D: + return "GL_TEXTURE_2D"; + case GL_CULL_FACE: + return "GL_CULL_FACE"; + case GL_ALPHA_TEST: + return "GL_ALPHA_TEST"; + case GL_BLEND: + return "GL_BLEND"; + case GL_COLOR_LOGIC_OP: + return "GL_COLOR_LOGIC_OP"; + case GL_DITHER: + return "GL_DITHER"; + case GL_STENCIL_TEST: + return "GL_STENCIL_TEST"; + case GL_DEPTH_TEST: + return "GL_DEPTH_TEST"; + case GL_LIGHT0: + return "GL_LIGHT0"; + case GL_LIGHT1: + return "GL_LIGHT1"; + case GL_LIGHT2: + return "GL_LIGHT2"; + case GL_LIGHT3: + return "GL_LIGHT3"; + case GL_LIGHT4: + return "GL_LIGHT4"; + case GL_LIGHT5: + return "GL_LIGHT5"; + case GL_LIGHT6: + return "GL_LIGHT6"; + case GL_LIGHT7: + return "GL_LIGHT7"; + case GL_POINT_SMOOTH: + return "GL_POINT_SMOOTH"; + case GL_LINE_SMOOTH: + return "GL_LINE_SMOOTH"; + case GL_COLOR_MATERIAL: + return "GL_COLOR_MATERIAL"; + case GL_NORMALIZE: + return "GL_NORMALIZE"; + case GL_RESCALE_NORMAL: + return "GL_RESCALE_NORMAL"; + case GL_VERTEX_ARRAY: + return "GL_VERTEX_ARRAY"; + case GL_NORMAL_ARRAY: + return "GL_NORMAL_ARRAY"; + case GL_COLOR_ARRAY: + return "GL_COLOR_ARRAY"; + case GL_TEXTURE_COORD_ARRAY: + return "GL_TEXTURE_COORD_ARRAY"; + case GL_MULTISAMPLE: + return "GL_MULTISAMPLE"; + case GL_SAMPLE_ALPHA_TO_COVERAGE: + return "GL_SAMPLE_ALPHA_TO_COVERAGE"; + case GL_SAMPLE_ALPHA_TO_ONE: + return "GL_SAMPLE_ALPHA_TO_ONE"; + case GL_SAMPLE_COVERAGE: + return "GL_SAMPLE_COVERAGE"; + case GL_SCISSOR_TEST: + return "GL_SCISSOR_TEST"; + default: + return getHex(cap); + } + } + + private String getTexturePName (int pname) { + switch (pname) { + case GL_TEXTURE_MAG_FILTER: + return "GL_TEXTURE_MAG_FILTER"; + case GL_TEXTURE_MIN_FILTER: + return "GL_TEXTURE_MIN_FILTER"; + case GL_TEXTURE_WRAP_S: + return "GL_TEXTURE_WRAP_S"; + case GL_TEXTURE_WRAP_T: + return "GL_TEXTURE_WRAP_T"; + case GL_GENERATE_MIPMAP: + return "GL_GENERATE_MIPMAP"; + case GL_TEXTURE_CROP_RECT_OES: + return "GL_TEXTURE_CROP_RECT_OES"; + default: + return getHex(pname); + } + } + + private String getTextureParamName (float param) { + int iparam = (int)param; + if (param == (float)iparam) { + switch (iparam) { + case GL_CLAMP_TO_EDGE: + return "GL_CLAMP_TO_EDGE"; + case GL_REPEAT: + return "GL_REPEAT"; + case GL_NEAREST: + return "GL_NEAREST"; + case GL_LINEAR: + return "GL_LINEAR"; + case GL_NEAREST_MIPMAP_NEAREST: + return "GL_NEAREST_MIPMAP_NEAREST"; + case GL_LINEAR_MIPMAP_NEAREST: + return "GL_LINEAR_MIPMAP_NEAREST"; + case GL_NEAREST_MIPMAP_LINEAR: + return "GL_NEAREST_MIPMAP_LINEAR"; + case GL_LINEAR_MIPMAP_LINEAR: + return "GL_LINEAR_MIPMAP_LINEAR"; + default: + return getHex(iparam); + } + } + return Float.toString(param); + } + + private String getFogPName (int pname) { + switch (pname) { + case GL_FOG_DENSITY: + return "GL_FOG_DENSITY"; + case GL_FOG_START: + return "GL_FOG_START"; + case GL_FOG_END: + return "GL_FOG_END"; + case GL_FOG_MODE: + return "GL_FOG_MODE"; + case GL_FOG_COLOR: + return "GL_FOG_COLOR"; + default: + return getHex(pname); + } + } + + private int getFogParamCount (int pname) { + switch (pname) { + case GL_FOG_DENSITY: + return 1; + case GL_FOG_START: + return 1; + case GL_FOG_END: + return 1; + case GL_FOG_MODE: + return 1; + case GL_FOG_COLOR: + return 4; + default: + return 0; + } + } + + private String getBeginMode (int mode) { + switch (mode) { + case GL_POINTS: + return "GL_POINTS"; + case GL_LINES: + return "GL_LINES"; + case GL_LINE_LOOP: + return "GL_LINE_LOOP"; + case GL_LINE_STRIP: + return "GL_LINE_STRIP"; + case GL_TRIANGLES: + return "GL_TRIANGLES"; + case GL_TRIANGLE_STRIP: + return "GL_TRIANGLE_STRIP"; + case GL_TRIANGLE_FAN: + return "GL_TRIANGLE_FAN"; + default: + return getHex(mode); + } + } + + private String getIndexType (int type) { + switch (type) { + case GL_UNSIGNED_SHORT: + return "GL_UNSIGNED_SHORT"; + case GL_UNSIGNED_BYTE: + return "GL_UNSIGNED_BYTE"; + default: + return getHex(type); + } + } + + private String getIntegerStateName (int pname) { + switch (pname) { + case GL_ALPHA_BITS: + return "GL_ALPHA_BITS"; + case GL_ALIASED_LINE_WIDTH_RANGE: + return "GL_ALIASED_LINE_WIDTH_RANGE"; + case GL_ALIASED_POINT_SIZE_RANGE: + return "GL_ALIASED_POINT_SIZE_RANGE"; + case GL_BLUE_BITS: + return "GL_BLUE_BITS"; + case GL_COMPRESSED_TEXTURE_FORMATS: + return "GL_COMPRESSED_TEXTURE_FORMATS"; + case GL_DEPTH_BITS: + return "GL_DEPTH_BITS"; + case GL_GREEN_BITS: + return "GL_GREEN_BITS"; + case GL_MAX_ELEMENTS_INDICES: + return "GL_MAX_ELEMENTS_INDICES"; + case GL_MAX_ELEMENTS_VERTICES: + return "GL_MAX_ELEMENTS_VERTICES"; + case GL_MAX_LIGHTS: + return "GL_MAX_LIGHTS"; + case GL_MAX_TEXTURE_SIZE: + return "GL_MAX_TEXTURE_SIZE"; + case GL_MAX_VIEWPORT_DIMS: + return "GL_MAX_VIEWPORT_DIMS"; + case GL_MAX_MODELVIEW_STACK_DEPTH: + return "GL_MAX_MODELVIEW_STACK_DEPTH"; + case GL_MAX_PROJECTION_STACK_DEPTH: + return "GL_MAX_PROJECTION_STACK_DEPTH"; + case GL_MAX_TEXTURE_STACK_DEPTH: + return "GL_MAX_TEXTURE_STACK_DEPTH"; + case GL_MAX_TEXTURE_UNITS: + return "GL_MAX_TEXTURE_UNITS"; + case GL_NUM_COMPRESSED_TEXTURE_FORMATS: + return "GL_NUM_COMPRESSED_TEXTURE_FORMATS"; + case GL_RED_BITS: + return "GL_RED_BITS"; + case GL_SMOOTH_LINE_WIDTH_RANGE: + return "GL_SMOOTH_LINE_WIDTH_RANGE"; + case GL_SMOOTH_POINT_SIZE_RANGE: + return "GL_SMOOTH_POINT_SIZE_RANGE"; + case GL_STENCIL_BITS: + return "GL_STENCIL_BITS"; + case GL_SUBPIXEL_BITS: + return "GL_SUBPIXEL_BITS"; + + case GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES: + return "GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES"; + case GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES: + return "GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES"; + case GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES: + return "GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES"; + + default: + return getHex(pname); + } + } + + private int getIntegerStateSize (int pname) { + switch (pname) { + case GL_ALPHA_BITS: + return 1; + case GL_ALIASED_LINE_WIDTH_RANGE: + return 2; + case GL_ALIASED_POINT_SIZE_RANGE: + return 2; + case GL_BLUE_BITS: + return 1; + case GL_COMPRESSED_TEXTURE_FORMATS: + // Have to ask the implementation for the size + { + int[] buffer = new int[1]; + mgl.glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, buffer, 0); + return buffer[0]; + } + case GL_DEPTH_BITS: + return 1; + case GL_GREEN_BITS: + return 1; + case GL_MAX_ELEMENTS_INDICES: + return 1; + case GL_MAX_ELEMENTS_VERTICES: + return 1; + case GL_MAX_LIGHTS: + return 1; + case GL_MAX_TEXTURE_SIZE: + return 1; + case GL_MAX_VIEWPORT_DIMS: + return 2; + case GL_MAX_MODELVIEW_STACK_DEPTH: + return 1; + case GL_MAX_PROJECTION_STACK_DEPTH: + return 1; + case GL_MAX_TEXTURE_STACK_DEPTH: + return 1; + case GL_MAX_TEXTURE_UNITS: + return 1; + case GL_NUM_COMPRESSED_TEXTURE_FORMATS: + return 1; + case GL_RED_BITS: + return 1; + case GL_SMOOTH_LINE_WIDTH_RANGE: + return 2; + case GL_SMOOTH_POINT_SIZE_RANGE: + return 2; + case GL_STENCIL_BITS: + return 1; + case GL_SUBPIXEL_BITS: + return 1; + + case GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES: + case GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES: + case GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES: + return 16; + + default: + return 0; + } + } + + private int getIntegerStateFormat (int pname) { + switch (pname) { + case GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES: + case GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES: + case GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES: + return FORMAT_FLOAT; + + default: + return FORMAT_INT; + } + } + + private String getHintTarget (int target) { + switch (target) { + case GL_FOG_HINT: + return "GL_FOG_HINT"; + case GL_LINE_SMOOTH_HINT: + return "GL_LINE_SMOOTH_HINT"; + case GL_PERSPECTIVE_CORRECTION_HINT: + return "GL_PERSPECTIVE_CORRECTION_HINT"; + case GL_POINT_SMOOTH_HINT: + return "GL_POINT_SMOOTH_HINT"; + case GL_POLYGON_SMOOTH_HINT: + return "GL_POLYGON_SMOOTH_HINT"; + case GL_GENERATE_MIPMAP_HINT: + return "GL_GENERATE_MIPMAP_HINT"; + default: + return getHex(target); + } + } + + private String getHintMode (int mode) { + switch (mode) { + case GL_FASTEST: + return "GL_FASTEST"; + case GL_NICEST: + return "GL_NICEST"; + case GL_DONT_CARE: + return "GL_DONT_CARE"; + default: + return getHex(mode); + } + } + + private String getFaceName (int face) { + switch (face) { + case GL_FRONT_AND_BACK: + return "GL_FRONT_AND_BACK"; + default: + return getHex(face); + } + } + + private String getMaterialPName (int pname) { + switch (pname) { + case GL_AMBIENT: + return "GL_AMBIENT"; + case GL_DIFFUSE: + return "GL_DIFFUSE"; + case GL_SPECULAR: + return "GL_SPECULAR"; + case GL_EMISSION: + return "GL_EMISSION"; + case GL_SHININESS: + return "GL_SHININESS"; + case GL_AMBIENT_AND_DIFFUSE: + return "GL_AMBIENT_AND_DIFFUSE"; + default: + return getHex(pname); + } + } + + private int getMaterialParamCount (int pname) { + switch (pname) { + case GL_AMBIENT: + return 4; + case GL_DIFFUSE: + return 4; + case GL_SPECULAR: + return 4; + case GL_EMISSION: + return 4; + case GL_SHININESS: + return 1; + case GL_AMBIENT_AND_DIFFUSE: + return 4; + default: + return 0; + } + } + + private String getLightName (int light) { + if (light >= GL_LIGHT0 && light <= GL_LIGHT7) { + return "GL_LIGHT" + Integer.toString(light); + } + return getHex(light); + } + + private String getLightPName (int pname) { + switch (pname) { + case GL_AMBIENT: + return "GL_AMBIENT"; + case GL_DIFFUSE: + return "GL_DIFFUSE"; + case GL_SPECULAR: + return "GL_SPECULAR"; + case GL_POSITION: + return "GL_POSITION"; + case GL_SPOT_DIRECTION: + return "GL_SPOT_DIRECTION"; + case GL_SPOT_EXPONENT: + return "GL_SPOT_EXPONENT"; + case GL_SPOT_CUTOFF: + return "GL_SPOT_CUTOFF"; + case GL_CONSTANT_ATTENUATION: + return "GL_CONSTANT_ATTENUATION"; + case GL_LINEAR_ATTENUATION: + return "GL_LINEAR_ATTENUATION"; + case GL_QUADRATIC_ATTENUATION: + return "GL_QUADRATIC_ATTENUATION"; + default: + return getHex(pname); + } + } + + private int getLightParamCount (int pname) { + switch (pname) { + case GL_AMBIENT: + return 4; + case GL_DIFFUSE: + return 4; + case GL_SPECULAR: + return 4; + case GL_POSITION: + return 4; + case GL_SPOT_DIRECTION: + return 3; + case GL_SPOT_EXPONENT: + return 1; + case GL_SPOT_CUTOFF: + return 1; + case GL_CONSTANT_ATTENUATION: + return 1; + case GL_LINEAR_ATTENUATION: + return 1; + case GL_QUADRATIC_ATTENUATION: + return 1; + default: + return 0; + } + } + + private String getLightModelPName (int pname) { + switch (pname) { + case GL_LIGHT_MODEL_AMBIENT: + return "GL_LIGHT_MODEL_AMBIENT"; + case GL_LIGHT_MODEL_TWO_SIDE: + return "GL_LIGHT_MODEL_TWO_SIDE"; + default: + return getHex(pname); + } + } + + private int getLightModelParamCount (int pname) { + switch (pname) { + case GL_LIGHT_MODEL_AMBIENT: + return 4; + case GL_LIGHT_MODEL_TWO_SIDE: + return 1; + default: + return 0; + } + } + + private String getPointerTypeName (int type) { + switch (type) { + case GL_BYTE: + return "GL_BYTE"; + case GL_UNSIGNED_BYTE: + return "GL_UNSIGNED_BYTE"; + case GL_SHORT: + return "GL_SHORT"; + case GL_FIXED: + return "GL_FIXED"; + case GL_FLOAT: + return "GL_FLOAT"; + default: + return getHex(type); + } + } + + private ByteBuffer toByteBuffer (int byteCount, Buffer input) { + ByteBuffer result = null; + boolean convertWholeBuffer = (byteCount < 0); + if (input instanceof ByteBuffer) { + ByteBuffer input2 = (ByteBuffer)input; + if (convertWholeBuffer) { + byteCount = input2.limit(); + } + result = ByteBuffer.allocate(byteCount).order(input2.order()); + int position = input2.position(); + for (int i = 0; i < byteCount; i++) { + result.put(input2.get()); + } + input2.position(position); + } else if (input instanceof CharBuffer) { + CharBuffer input2 = (CharBuffer)input; + if (convertWholeBuffer) { + byteCount = input2.limit() * 2; + } + result = ByteBuffer.allocate(byteCount).order(input2.order()); + CharBuffer result2 = result.asCharBuffer(); + int position = input2.position(); + for (int i = 0; i < byteCount / 2; i++) { + result2.put(input2.get()); + } + input2.position(position); + } else if (input instanceof ShortBuffer) { + ShortBuffer input2 = (ShortBuffer)input; + if (convertWholeBuffer) { + byteCount = input2.limit() * 2; + } + result = ByteBuffer.allocate(byteCount).order(input2.order()); + ShortBuffer result2 = result.asShortBuffer(); + int position = input2.position(); + for (int i = 0; i < byteCount / 2; i++) { + result2.put(input2.get()); + } + input2.position(position); + } else if (input instanceof IntBuffer) { + IntBuffer input2 = (IntBuffer)input; + if (convertWholeBuffer) { + byteCount = input2.limit() * 4; + } + result = ByteBuffer.allocate(byteCount).order(input2.order()); + IntBuffer result2 = result.asIntBuffer(); + int position = input2.position(); + for (int i = 0; i < byteCount / 4; i++) { + result2.put(input2.get()); + } + input2.position(position); + } else if (input instanceof FloatBuffer) { + FloatBuffer input2 = (FloatBuffer)input; + if (convertWholeBuffer) { + byteCount = input2.limit() * 4; + } + result = ByteBuffer.allocate(byteCount).order(input2.order()); + FloatBuffer result2 = result.asFloatBuffer(); + int position = input2.position(); + for (int i = 0; i < byteCount / 4; i++) { + result2.put(input2.get()); + } + input2.position(position); + } else if (input instanceof DoubleBuffer) { + DoubleBuffer input2 = (DoubleBuffer)input; + if (convertWholeBuffer) { + byteCount = input2.limit() * 8; + } + result = ByteBuffer.allocate(byteCount).order(input2.order()); + DoubleBuffer result2 = result.asDoubleBuffer(); + int position = input2.position(); + for (int i = 0; i < byteCount / 8; i++) { + result2.put(input2.get()); + } + input2.position(position); + } else if (input instanceof LongBuffer) { + LongBuffer input2 = (LongBuffer)input; + if (convertWholeBuffer) { + byteCount = input2.limit() * 8; + } + result = ByteBuffer.allocate(byteCount).order(input2.order()); + LongBuffer result2 = result.asLongBuffer(); + int position = input2.position(); + for (int i = 0; i < byteCount / 8; i++) { + result2.put(input2.get()); + } + input2.position(position); + } else { + throw new RuntimeException("Unimplemented Buffer subclass."); + } + result.rewind(); + // The OpenGL API will interpret the result in hardware byte order, + // so we better do that as well: + result.order(ByteOrder.nativeOrder()); + return result; + } + + private char[] toCharIndices (int count, int type, Buffer indices) { + char[] result = new char[count]; + switch (type) { + case GL_UNSIGNED_BYTE: { + ByteBuffer byteBuffer = toByteBuffer(count, indices); + byte[] array = byteBuffer.array(); + int offset = byteBuffer.arrayOffset(); + for (int i = 0; i < count; i++) { + result[i] = (char)(0xff & array[offset + i]); + } + } + break; + case GL_UNSIGNED_SHORT: { + CharBuffer charBuffer; + if (indices instanceof CharBuffer) { + charBuffer = (CharBuffer)indices; + } else { + ByteBuffer byteBuffer = toByteBuffer(count * 2, indices); + charBuffer = byteBuffer.asCharBuffer(); + } + int oldPosition = charBuffer.position(); + charBuffer.position(0); + charBuffer.get(result); + charBuffer.position(oldPosition); + } + break; + default: + // Don't throw an exception, because we don't want logging to + // change the behavior. + break; + } + return result; + } + + private void doArrayElement (StringBuilder builder, boolean enabled, String name, PointerInfo pointer, int index) { + if (!enabled) { + return; + } + builder.append(" "); + builder.append(name + ":{"); + if (pointer == null) { + builder.append("undefined"); + return; + } + if (pointer.mStride < 0) { + builder.append("invalid stride"); + return; + } + + int stride = pointer.getStride(); + ByteBuffer byteBuffer = pointer.mTempByteBuffer; + int size = pointer.mSize; + int type = pointer.mType; + int sizeofType = pointer.sizeof(type); + int byteOffset = stride * index; + for (int i = 0; i < size; i++) { + if (i > 0) { + builder.append(", "); + } + switch (type) { + case GL_BYTE: { + byte d = byteBuffer.get(byteOffset); + builder.append(Integer.toString(d)); + } + break; + case GL_UNSIGNED_BYTE: { + byte d = byteBuffer.get(byteOffset); + builder.append(Integer.toString(0xff & d)); + } + break; + case GL_SHORT: { + ShortBuffer shortBuffer = byteBuffer.asShortBuffer(); + short d = shortBuffer.get(byteOffset / 2); + builder.append(Integer.toString(d)); + } + break; + case GL_FIXED: { + IntBuffer intBuffer = byteBuffer.asIntBuffer(); + int d = intBuffer.get(byteOffset / 4); + builder.append(Integer.toString(d)); + } + break; + case GL_FLOAT: { + FloatBuffer intBuffer = byteBuffer.asFloatBuffer(); + float d = intBuffer.get(byteOffset / 4); + builder.append(Float.toString(d)); + } + break; + default: + builder.append("?"); + break; + } + byteOffset += sizeofType; + } + builder.append("}"); + } + + private void doElement (StringBuilder builder, int ordinal, int vertexIndex) { + builder.append(" [" + ordinal + " : " + vertexIndex + "] ="); + doArrayElement(builder, mVertexArrayEnabled, "v", mVertexPointer, vertexIndex); + doArrayElement(builder, mNormalArrayEnabled, "n", mNormalPointer, vertexIndex); + doArrayElement(builder, mColorArrayEnabled, "c", mColorPointer, vertexIndex); + doArrayElement(builder, mTextureCoordArrayEnabled, "t", mTexCoordPointer, vertexIndex); + builder.append("\n"); + // Vertex + // Normal + // Color + // TexCoord + } + + private void bindArrays () { + if (mColorArrayEnabled) mColorPointer.bindByteBuffer(); + if (mNormalArrayEnabled) mNormalPointer.bindByteBuffer(); + if (mTextureCoordArrayEnabled) mTexCoordPointer.bindByteBuffer(); + if (mVertexArrayEnabled) mVertexPointer.bindByteBuffer(); + } + + private void unbindArrays () { + if (mColorArrayEnabled) mColorPointer.unbindByteBuffer(); + if (mNormalArrayEnabled) mNormalPointer.unbindByteBuffer(); + if (mTextureCoordArrayEnabled) mTexCoordPointer.unbindByteBuffer(); + if (mVertexArrayEnabled) mVertexPointer.unbindByteBuffer(); + } + + private void startLogIndices () { + mStringBuilder = new StringBuilder(); + mStringBuilder.append("\n"); + bindArrays(); + } + + private void endLogIndices () { + log(mStringBuilder.toString()); + unbindArrays(); + } + + // --------------------------------------------------------------------- + // GL10 methods: + + public void glActiveTexture (int texture) { + begin("glActiveTexture"); + arg("texture", texture); + end(); + mgl.glActiveTexture(texture); + checkError(); + } + + public void glAlphaFunc (int func, float ref) { + begin("glAlphaFunc"); + arg("func", func); + arg("ref", ref); + end(); + mgl.glAlphaFunc(func, ref); + checkError(); + } + + public void glAlphaFuncx (int func, int ref) { + begin("glAlphaFuncx"); + arg("func", func); + arg("ref", ref); + end(); + mgl.glAlphaFuncx(func, ref); + checkError(); + } + + public void glBindTexture (int target, int texture) { + begin("glBindTexture"); + arg("target", getTextureTarget(target)); + arg("texture", texture); + end(); + mgl.glBindTexture(target, texture); + checkError(); + } + + public void glBlendFunc (int sfactor, int dfactor) { + begin("glBlendFunc"); + arg("sfactor", getFactor(sfactor)); + arg("dfactor", getFactor(dfactor)); + end(); + + mgl.glBlendFunc(sfactor, dfactor); + checkError(); + } + + public void glClear (int mask) { + begin("glClear"); + arg("mask", getClearBufferMask(mask)); + end(); + + mgl.glClear(mask); + checkError(); + } + + public void glClearColor (float red, float green, float blue, float alpha) { + begin("glClearColor"); + arg("red", red); + arg("green", green); + arg("blue", blue); + arg("alpha", alpha); + end(); + + mgl.glClearColor(red, green, blue, alpha); + checkError(); + } + + public void glClearColorx (int red, int green, int blue, int alpha) { + begin("glClearColor"); + arg("red", red); + arg("green", green); + arg("blue", blue); + arg("alpha", alpha); + end(); + + mgl.glClearColorx(red, green, blue, alpha); + checkError(); + } + + public void glClearDepthf (float depth) { + begin("glClearDepthf"); + arg("depth", depth); + end(); + + mgl.glClearDepthf(depth); + checkError(); + } + + public void glClearDepthx (int depth) { + begin("glClearDepthx"); + arg("depth", depth); + end(); + + mgl.glClearDepthx(depth); + checkError(); + } + + public void glClearStencil (int s) { + begin("glClearStencil"); + arg("s", s); + end(); + + mgl.glClearStencil(s); + checkError(); + } + + public void glClientActiveTexture (int texture) { + begin("glClientActiveTexture"); + arg("texture", texture); + end(); + + mgl.glClientActiveTexture(texture); + checkError(); + } + + public void glColor4f (float red, float green, float blue, float alpha) { + begin("glColor4f"); + arg("red", red); + arg("green", green); + arg("blue", blue); + arg("alpha", alpha); + end(); + + mgl.glColor4f(red, green, blue, alpha); + checkError(); + } + + public void glColor4x (int red, int green, int blue, int alpha) { + begin("glColor4x"); + arg("red", red); + arg("green", green); + arg("blue", blue); + arg("alpha", alpha); + end(); + + mgl.glColor4x(red, green, blue, alpha); + checkError(); + } + + public void glColorMask (boolean red, boolean green, boolean blue, boolean alpha) { + begin("glColorMask"); + arg("red", red); + arg("green", green); + arg("blue", blue); + arg("alpha", alpha); + end(); + + mgl.glColorMask(red, green, blue, alpha); + checkError(); + } + + public void glColorPointer (int size, int type, int stride, Buffer pointer) { + begin("glColorPointer"); + argPointer(size, type, stride, pointer); + end(); + mColorPointer = new PointerInfo(size, type, stride, pointer); + + mgl.glColorPointer(size, type, stride, pointer); + checkError(); + } + + public void glCompressedTexImage2D (int target, int level, int internalformat, int width, int height, int border, + int imageSize, Buffer data) { + begin("glCompressedTexImage2D"); + arg("target", getTextureTarget(target)); + arg("level", level); + arg("internalformat", internalformat); + arg("width", width); + arg("height", height); + arg("border", border); + arg("imageSize", imageSize); + arg("data", data.toString()); + end(); + + mgl.glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); + checkError(); + } + + public void glCompressedTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, int format, + int imageSize, Buffer data) { + begin("glCompressedTexSubImage2D"); + arg("target", getTextureTarget(target)); + arg("level", level); + arg("xoffset", xoffset); + arg("yoffset", yoffset); + arg("width", width); + arg("height", height); + arg("format", format); + arg("imageSize", imageSize); + arg("data", data.toString()); + end(); + + mgl.glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); + checkError(); + } + + public void glCopyTexImage2D (int target, int level, int internalformat, int x, int y, int width, int height, int border) { + begin("glCopyTexImage2D"); + arg("target", getTextureTarget(target)); + arg("level", level); + arg("internalformat", internalformat); + arg("x", x); + arg("y", y); + arg("width", width); + arg("height", height); + arg("border", border); + end(); + + mgl.glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); + checkError(); + } + + public void glCopyTexSubImage2D (int target, int level, int xoffset, int yoffset, int x, int y, int width, int height) { + begin("glCopyTexSubImage2D"); + arg("target", getTextureTarget(target)); + arg("level", level); + arg("xoffset", xoffset); + arg("yoffset", yoffset); + arg("x", x); + arg("y", y); + arg("width", width); + arg("height", height); + end(); + + mgl.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); + checkError(); + } + + public void glCullFace (int mode) { + begin("glCullFace"); + arg("mode", mode); + end(); + + mgl.glCullFace(mode); + checkError(); + } + + public void glDeleteTextures (int n, int[] textures, int offset) { + begin("glDeleteTextures"); + arg("n", n); + arg("textures", n, textures, offset); + arg("offset", offset); + end(); + + mgl.glDeleteTextures(n, textures, offset); + checkError(); + } + + public void glDeleteTextures (int n, IntBuffer textures) { + begin("glDeleteTextures"); + arg("n", n); + arg("textures", n, textures); + end(); + + mgl.glDeleteTextures(n, textures); + checkError(); + } + + public void glDepthFunc (int func) { + begin("glDepthFunc"); + arg("func", func); + end(); + + mgl.glDepthFunc(func); + checkError(); + } + + public void glDepthMask (boolean flag) { + begin("glDepthMask"); + arg("flag", flag); + end(); + + mgl.glDepthMask(flag); + checkError(); + } + + public void glDepthRangef (float near, float far) { + begin("glDepthRangef"); + arg("near", near); + arg("far", far); + end(); + + mgl.glDepthRangef(near, far); + checkError(); + } + + public void glDepthRangex (int near, int far) { + begin("glDepthRangex"); + arg("near", near); + arg("far", far); + end(); + + mgl.glDepthRangex(near, far); + checkError(); + } + + public void glDisable (int cap) { + begin("glDisable"); + arg("cap", getCap(cap)); + end(); + + mgl.glDisable(cap); + checkError(); + } + + public void glDisableClientState (int array) { + begin("glDisableClientState"); + arg("array", getClientState(array)); + end(); + + switch (array) { + case GL_COLOR_ARRAY: + mColorArrayEnabled = false; + break; + case GL_NORMAL_ARRAY: + mNormalArrayEnabled = false; + break; + case GL_TEXTURE_COORD_ARRAY: + mTextureCoordArrayEnabled = false; + break; + case GL_VERTEX_ARRAY: + mVertexArrayEnabled = false; + break; + } + mgl.glDisableClientState(array); + checkError(); + } + + public void glDrawArrays (int mode, int first, int count) { + begin("glDrawArrays"); + arg("mode", mode); + arg("first", first); + arg("count", count); + startLogIndices(); + for (int i = 0; i < count; i++) { + doElement(mStringBuilder, i, first + i); + } + endLogIndices(); + end(); + + mgl.glDrawArrays(mode, first, count); + checkError(); + } + + public void glDrawElements (int mode, int count, int type, Buffer indices) { + begin("glDrawElements"); + arg("mode", getBeginMode(mode)); + arg("count", count); + arg("type", getIndexType(type)); + char[] indexArray = toCharIndices(count, type, indices); + int indexArrayLength = indexArray.length; + startLogIndices(); + for (int i = 0; i < indexArrayLength; i++) { + doElement(mStringBuilder, i, indexArray[i]); + } + endLogIndices(); + end(); + + mgl.glDrawElements(mode, count, type, indices); + checkError(); + } + + public void glEnable (int cap) { + begin("glEnable"); + arg("cap", getCap(cap)); + end(); + + mgl.glEnable(cap); + checkError(); + } + + public void glEnableClientState (int array) { + begin("glEnableClientState"); + arg("array", getClientState(array)); + end(); + + switch (array) { + case GL_COLOR_ARRAY: + mColorArrayEnabled = true; + break; + case GL_NORMAL_ARRAY: + mNormalArrayEnabled = true; + break; + case GL_TEXTURE_COORD_ARRAY: + mTextureCoordArrayEnabled = true; + break; + case GL_VERTEX_ARRAY: + mVertexArrayEnabled = true; + break; + } + mgl.glEnableClientState(array); + checkError(); + } + + public void glFinish () { + begin("glFinish"); + end(); + + mgl.glFinish(); + checkError(); + } + + public void glFlush () { + begin("glFlush"); + end(); + + mgl.glFlush(); + checkError(); + } + + public void glFogf (int pname, float param) { + begin("glFogf"); + arg("pname", pname); + arg("param", param); + end(); + + mgl.glFogf(pname, param); + checkError(); + } + + public void glFogfv (int pname, float[] params, int offset) { + begin("glFogfv"); + arg("pname", getFogPName(pname)); + arg("params", getFogParamCount(pname), params, offset); + arg("offset", offset); + end(); + + mgl.glFogfv(pname, params, offset); + checkError(); + } + + public void glFogfv (int pname, FloatBuffer params) { + begin("glFogfv"); + arg("pname", getFogPName(pname)); + arg("params", getFogParamCount(pname), params); + end(); + + mgl.glFogfv(pname, params); + checkError(); + } + + public void glFogx (int pname, int param) { + begin("glFogx"); + arg("pname", getFogPName(pname)); + arg("param", param); + end(); + + mgl.glFogx(pname, param); + checkError(); + } + + public void glFogxv (int pname, int[] params, int offset) { + begin("glFogxv"); + arg("pname", getFogPName(pname)); + arg("params", getFogParamCount(pname), params, offset); + arg("offset", offset); + end(); + + mgl.glFogxv(pname, params, offset); + checkError(); + } + + public void glFogxv (int pname, IntBuffer params) { + begin("glFogxv"); + arg("pname", getFogPName(pname)); + arg("params", getFogParamCount(pname), params); + end(); + + mgl.glFogxv(pname, params); + checkError(); + } + + public void glFrontFace (int mode) { + begin("glFrontFace"); + arg("mode", mode); + end(); + + mgl.glFrontFace(mode); + checkError(); + } + + public void glFrustumf (float left, float right, float bottom, float top, float near, float far) { + begin("glFrustumf"); + arg("left", left); + arg("right", right); + arg("bottom", bottom); + arg("top", top); + arg("near", near); + arg("far", far); + end(); + + mgl.glFrustumf(left, right, bottom, top, near, far); + checkError(); + } + + public void glFrustumx (int left, int right, int bottom, int top, int near, int far) { + begin("glFrustumx"); + arg("left", left); + arg("right", right); + arg("bottom", bottom); + arg("top", top); + arg("near", near); + arg("far", far); + end(); + + mgl.glFrustumx(left, right, bottom, top, near, far); + checkError(); + } + + public void glGenTextures (int n, int[] textures, int offset) { + begin("glGenTextures"); + arg("n", n); + arg("textures", Arrays.toString(textures)); + arg("offset", offset); + + mgl.glGenTextures(n, textures, offset); + + returns(toString(n, FORMAT_INT, textures, offset)); + + checkError(); + } + + public void glGenTextures (int n, IntBuffer textures) { + begin("glGenTextures"); + arg("n", n); + arg("textures", textures.toString()); + + mgl.glGenTextures(n, textures); + + returns(toString(n, FORMAT_INT, textures)); + + checkError(); + } + + public int glGetError () { + begin("glGetError"); + + int result = mgl.glGetError(); + + returns(result); + + return result; + } + + public void glGetIntegerv (int pname, int[] params, int offset) { + begin("glGetIntegerv"); + arg("pname", getIntegerStateName(pname)); + arg("params", Arrays.toString(params)); + arg("offset", offset); + + mgl.glGetIntegerv(pname, params, offset); + + returns(toString(getIntegerStateSize(pname), getIntegerStateFormat(pname), params, offset)); + + checkError(); + } + + public void glGetIntegerv (int pname, IntBuffer params) { + begin("glGetIntegerv"); + arg("pname", getIntegerStateName(pname)); + arg("params", params.toString()); + + mgl.glGetIntegerv(pname, params); + + returns(toString(getIntegerStateSize(pname), getIntegerStateFormat(pname), params)); + + checkError(); + } + + public String glGetString (int name) { + begin("glGetString"); + arg("name", name); + + String result = mgl.glGetString(name); + + returns(result); + + checkError(); + return result; + } + + public void glHint (int target, int mode) { + begin("glHint"); + arg("target", getHintTarget(target)); + arg("mode", getHintMode(mode)); + end(); + + mgl.glHint(target, mode); + checkError(); + } + + public void glLightModelf (int pname, float param) { + begin("glLightModelf"); + arg("pname", getLightModelPName(pname)); + arg("param", param); + end(); + + mgl.glLightModelf(pname, param); + checkError(); + } + + public void glLightModelfv (int pname, float[] params, int offset) { + begin("glLightModelfv"); + arg("pname", getLightModelPName(pname)); + arg("params", getLightModelParamCount(pname), params, offset); + arg("offset", offset); + end(); + + mgl.glLightModelfv(pname, params, offset); + checkError(); + } + + public void glLightModelfv (int pname, FloatBuffer params) { + begin("glLightModelfv"); + arg("pname", getLightModelPName(pname)); + arg("params", getLightModelParamCount(pname), params); + end(); + + mgl.glLightModelfv(pname, params); + checkError(); + } + + public void glLightModelx (int pname, int param) { + begin("glLightModelx"); + arg("pname", getLightModelPName(pname)); + arg("param", param); + end(); + + mgl.glLightModelx(pname, param); + checkError(); + } + + public void glLightModelxv (int pname, int[] params, int offset) { + begin("glLightModelxv"); + arg("pname", getLightModelPName(pname)); + arg("params", getLightModelParamCount(pname), params, offset); + arg("offset", offset); + end(); + + mgl.glLightModelxv(pname, params, offset); + checkError(); + } + + public void glLightModelxv (int pname, IntBuffer params) { + begin("glLightModelfv"); + arg("pname", getLightModelPName(pname)); + arg("params", getLightModelParamCount(pname), params); + end(); + + mgl.glLightModelxv(pname, params); + checkError(); + } + + public void glLightf (int light, int pname, float param) { + begin("glLightf"); + arg("light", getLightName(light)); + arg("pname", getLightPName(pname)); + arg("param", param); + end(); + + mgl.glLightf(light, pname, param); + checkError(); + } + + public void glLightfv (int light, int pname, float[] params, int offset) { + begin("glLightfv"); + arg("light", getLightName(light)); + arg("pname", getLightPName(pname)); + arg("params", getLightParamCount(pname), params, offset); + arg("offset", offset); + end(); + + mgl.glLightfv(light, pname, params, offset); + checkError(); + } + + public void glLightfv (int light, int pname, FloatBuffer params) { + begin("glLightfv"); + arg("light", getLightName(light)); + arg("pname", getLightPName(pname)); + arg("params", getLightParamCount(pname), params); + end(); + + mgl.glLightfv(light, pname, params); + checkError(); + } + + public void glLightx (int light, int pname, int param) { + begin("glLightx"); + arg("light", getLightName(light)); + arg("pname", getLightPName(pname)); + arg("param", param); + end(); + + mgl.glLightx(light, pname, param); + checkError(); + } + + public void glLightxv (int light, int pname, int[] params, int offset) { + begin("glLightxv"); + arg("light", getLightName(light)); + arg("pname", getLightPName(pname)); + arg("params", getLightParamCount(pname), params, offset); + arg("offset", offset); + end(); + + mgl.glLightxv(light, pname, params, offset); + checkError(); + } + + public void glLightxv (int light, int pname, IntBuffer params) { + begin("glLightxv"); + arg("light", getLightName(light)); + arg("pname", getLightPName(pname)); + arg("params", getLightParamCount(pname), params); + end(); + + mgl.glLightxv(light, pname, params); + checkError(); + } + + public void glLineWidth (float width) { + begin("glLineWidth"); + arg("width", width); + end(); + + mgl.glLineWidth(width); + checkError(); + } + + public void glLineWidthx (int width) { + begin("glLineWidthx"); + arg("width", width); + end(); + + mgl.glLineWidthx(width); + checkError(); + } + + public void glLoadIdentity () { + begin("glLoadIdentity"); + end(); + + mgl.glLoadIdentity(); + checkError(); + } + + public void glLoadMatrixf (float[] m, int offset) { + begin("glLoadMatrixf"); + arg("m", 16, m, offset); + arg("offset", offset); + end(); + + mgl.glLoadMatrixf(m, offset); + checkError(); + } + + public void glLoadMatrixf (FloatBuffer m) { + begin("glLoadMatrixf"); + arg("m", 16, m); + end(); + + mgl.glLoadMatrixf(m); + checkError(); + } + + public void glLoadMatrixx (int[] m, int offset) { + begin("glLoadMatrixx"); + arg("m", 16, m, offset); + arg("offset", offset); + end(); + + mgl.glLoadMatrixx(m, offset); + checkError(); + } + + public void glLoadMatrixx (IntBuffer m) { + begin("glLoadMatrixx"); + arg("m", 16, m); + end(); + + mgl.glLoadMatrixx(m); + checkError(); + } + + public void glLogicOp (int opcode) { + begin("glLogicOp"); + arg("opcode", opcode); + end(); + + mgl.glLogicOp(opcode); + checkError(); + } + + public void glMaterialf (int face, int pname, float param) { + begin("glMaterialf"); + arg("face", getFaceName(face)); + arg("pname", getMaterialPName(pname)); + arg("param", param); + end(); + + mgl.glMaterialf(face, pname, param); + checkError(); + } + + public void glMaterialfv (int face, int pname, float[] params, int offset) { + begin("glMaterialfv"); + arg("face", getFaceName(face)); + arg("pname", getMaterialPName(pname)); + arg("params", getMaterialParamCount(pname), params, offset); + arg("offset", offset); + end(); + + mgl.glMaterialfv(face, pname, params, offset); + checkError(); + } + + public void glMaterialfv (int face, int pname, FloatBuffer params) { + begin("glMaterialfv"); + arg("face", getFaceName(face)); + arg("pname", getMaterialPName(pname)); + arg("params", getMaterialParamCount(pname), params); + end(); + + mgl.glMaterialfv(face, pname, params); + checkError(); + } + + public void glMaterialx (int face, int pname, int param) { + begin("glMaterialx"); + arg("face", getFaceName(face)); + arg("pname", getMaterialPName(pname)); + arg("param", param); + end(); + + mgl.glMaterialx(face, pname, param); + checkError(); + } + + public void glMaterialxv (int face, int pname, int[] params, int offset) { + begin("glMaterialxv"); + arg("face", getFaceName(face)); + arg("pname", getMaterialPName(pname)); + arg("params", getMaterialParamCount(pname), params, offset); + arg("offset", offset); + end(); + + mgl.glMaterialxv(face, pname, params, offset); + checkError(); + } + + public void glMaterialxv (int face, int pname, IntBuffer params) { + begin("glMaterialxv"); + arg("face", getFaceName(face)); + arg("pname", getMaterialPName(pname)); + arg("params", getMaterialParamCount(pname), params); + end(); + + mgl.glMaterialxv(face, pname, params); + checkError(); + } + + public void glMatrixMode (int mode) { + begin("glMatrixMode"); + arg("mode", getMatrixMode(mode)); + end(); + + mgl.glMatrixMode(mode); + checkError(); + } + + public void glMultMatrixf (float[] m, int offset) { + begin("glMultMatrixf"); + arg("m", 16, m, offset); + arg("offset", offset); + end(); + + mgl.glMultMatrixf(m, offset); + checkError(); + } + + public void glMultMatrixf (FloatBuffer m) { + begin("glMultMatrixf"); + arg("m", 16, m); + end(); + + mgl.glMultMatrixf(m); + checkError(); + } + + public void glMultMatrixx (int[] m, int offset) { + begin("glMultMatrixx"); + arg("m", 16, m, offset); + arg("offset", offset); + end(); + + mgl.glMultMatrixx(m, offset); + checkError(); + } + + public void glMultMatrixx (IntBuffer m) { + begin("glMultMatrixx"); + arg("m", 16, m); + end(); + + mgl.glMultMatrixx(m); + checkError(); + } + + public void glMultiTexCoord4f (int target, float s, float t, float r, float q) { + begin("glMultiTexCoord4f"); + arg("target", target); + arg("s", s); + arg("t", t); + arg("r", r); + arg("q", q); + end(); + + mgl.glMultiTexCoord4f(target, s, t, r, q); + checkError(); + } + + public void glMultiTexCoord4x (int target, int s, int t, int r, int q) { + begin("glMultiTexCoord4x"); + arg("target", target); + arg("s", s); + arg("t", t); + arg("r", r); + arg("q", q); + end(); + + mgl.glMultiTexCoord4x(target, s, t, r, q); + checkError(); + } + + public void glNormal3f (float nx, float ny, float nz) { + begin("glNormal3f"); + arg("nx", nx); + arg("ny", ny); + arg("nz", nz); + end(); + + mgl.glNormal3f(nx, ny, nz); + checkError(); + } + + public void glNormal3x (int nx, int ny, int nz) { + begin("glNormal3x"); + arg("nx", nx); + arg("ny", ny); + arg("nz", nz); + end(); + + mgl.glNormal3x(nx, ny, nz); + checkError(); + } + + public void glNormalPointer (int type, int stride, Buffer pointer) { + begin("glNormalPointer"); + arg("type", type); + arg("stride", stride); + arg("pointer", pointer.toString()); + end(); + mNormalPointer = new PointerInfo(3, type, stride, pointer); + + mgl.glNormalPointer(type, stride, pointer); + checkError(); + } + + public void glOrthof (float left, float right, float bottom, float top, float near, float far) { + begin("glOrthof"); + arg("left", left); + arg("right", right); + arg("bottom", bottom); + arg("top", top); + arg("near", near); + arg("far", far); + end(); + + mgl.glOrthof(left, right, bottom, top, near, far); + checkError(); + } + + public void glOrthox (int left, int right, int bottom, int top, int near, int far) { + begin("glOrthox"); + arg("left", left); + arg("right", right); + arg("bottom", bottom); + arg("top", top); + arg("near", near); + arg("far", far); + end(); + + mgl.glOrthox(left, right, bottom, top, near, far); + checkError(); + } + + public void glPixelStorei (int pname, int param) { + begin("glPixelStorei"); + arg("pname", pname); + arg("param", param); + end(); + + mgl.glPixelStorei(pname, param); + checkError(); + } + + public void glPointSize (float size) { + begin("glPointSize"); + arg("size", size); + end(); + + mgl.glPointSize(size); + checkError(); + } + + public void glPointSizex (int size) { + begin("glPointSizex"); + arg("size", size); + end(); + + mgl.glPointSizex(size); + checkError(); + } + + public void glPolygonOffset (float factor, float units) { + begin("glPolygonOffset"); + arg("factor", factor); + arg("units", units); + end(); + mgl.glPolygonOffset(factor, units); + checkError(); + } + + public void glPolygonOffsetx (int factor, int units) { + begin("glPolygonOffsetx"); + arg("factor", factor); + arg("units", units); + end(); + + mgl.glPolygonOffsetx(factor, units); + checkError(); + } + + public void glPopMatrix () { + begin("glPopMatrix"); + end(); + + mgl.glPopMatrix(); + checkError(); + } + + public void glPushMatrix () { + begin("glPushMatrix"); + end(); + + mgl.glPushMatrix(); + checkError(); + } + + public void glReadPixels (int x, int y, int width, int height, int format, int type, Buffer pixels) { + begin("glReadPixels"); + arg("x", x); + arg("y", y); + arg("width", width); + arg("height", height); + arg("format", format); + arg("type", type); + arg("pixels", pixels.toString()); + end(); + + mgl.glReadPixels(x, y, width, height, format, type, pixels); + checkError(); + } + + public void glRotatef (float angle, float x, float y, float z) { + begin("glRotatef"); + arg("angle", angle); + arg("x", x); + arg("y", y); + arg("z", z); + end(); + + mgl.glRotatef(angle, x, y, z); + checkError(); + } + + public void glRotatex (int angle, int x, int y, int z) { + begin("glRotatex"); + arg("angle", angle); + arg("x", x); + arg("y", y); + arg("z", z); + end(); + + mgl.glRotatex(angle, x, y, z); + checkError(); + } + + public void glSampleCoverage (float value, boolean invert) { + begin("glSampleCoveragex"); + arg("value", value); + arg("invert", invert); + end(); + + mgl.glSampleCoverage(value, invert); + checkError(); + } + + public void glSampleCoveragex (int value, boolean invert) { + begin("glSampleCoveragex"); + arg("value", value); + arg("invert", invert); + end(); + + mgl.glSampleCoveragex(value, invert); + checkError(); + } + + public void glScalef (float x, float y, float z) { + begin("glScalef"); + arg("x", x); + arg("y", y); + arg("z", z); + end(); + + mgl.glScalef(x, y, z); + checkError(); + } + + public void glScalex (int x, int y, int z) { + begin("glScalex"); + arg("x", x); + arg("y", y); + arg("z", z); + end(); + + mgl.glScalex(x, y, z); + checkError(); + } + + public void glScissor (int x, int y, int width, int height) { + begin("glScissor"); + arg("x", x); + arg("y", y); + arg("width", width); + arg("height", height); + end(); + + mgl.glScissor(x, y, width, height); + checkError(); + } + + public void glShadeModel (int mode) { + begin("glShadeModel"); + arg("mode", getShadeModel(mode)); + end(); + + mgl.glShadeModel(mode); + checkError(); + } + + public void glStencilFunc (int func, int ref, int mask) { + begin("glStencilFunc"); + arg("func", func); + arg("ref", ref); + arg("mask", mask); + end(); + + mgl.glStencilFunc(func, ref, mask); + checkError(); + } + + public void glStencilMask (int mask) { + begin("glStencilMask"); + arg("mask", mask); + end(); + + mgl.glStencilMask(mask); + checkError(); + } + + public void glStencilOp (int fail, int zfail, int zpass) { + begin("glStencilOp"); + arg("fail", fail); + arg("zfail", zfail); + arg("zpass", zpass); + end(); + + mgl.glStencilOp(fail, zfail, zpass); + checkError(); + } + + public void glTexCoordPointer (int size, int type, int stride, Buffer pointer) { + begin("glTexCoordPointer"); + argPointer(size, type, stride, pointer); + end(); + mTexCoordPointer = new PointerInfo(size, type, stride, pointer); + + mgl.glTexCoordPointer(size, type, stride, pointer); + checkError(); + } + + public void glTexEnvf (int target, int pname, float param) { + begin("glTexEnvf"); + arg("target", getTextureEnvTarget(target)); + arg("pname", getTextureEnvPName(pname)); + arg("param", getTextureEnvParamName(param)); + end(); + + mgl.glTexEnvf(target, pname, param); + checkError(); + } + + public void glTexEnvfv (int target, int pname, float[] params, int offset) { + begin("glTexEnvfv"); + arg("target", getTextureEnvTarget(target)); + arg("pname", getTextureEnvPName(pname)); + arg("params", getTextureEnvParamCount(pname), params, offset); + arg("offset", offset); + end(); + + mgl.glTexEnvfv(target, pname, params, offset); + checkError(); + } + + public void glTexEnvfv (int target, int pname, FloatBuffer params) { + begin("glTexEnvfv"); + arg("target", getTextureEnvTarget(target)); + arg("pname", getTextureEnvPName(pname)); + arg("params", getTextureEnvParamCount(pname), params); + end(); + + mgl.glTexEnvfv(target, pname, params); + checkError(); + } + + public void glTexEnvx (int target, int pname, int param) { + begin("glTexEnvx"); + arg("target", getTextureEnvTarget(target)); + arg("pname", getTextureEnvPName(pname)); + arg("param", param); + end(); + + mgl.glTexEnvx(target, pname, param); + checkError(); + } + + public void glTexEnvxv (int target, int pname, int[] params, int offset) { + begin("glTexEnvxv"); + arg("target", getTextureEnvTarget(target)); + arg("pname", getTextureEnvPName(pname)); + arg("params", getTextureEnvParamCount(pname), params, offset); + arg("offset", offset); + end(); + + mgl.glTexEnvxv(target, pname, params, offset); + checkError(); + } + + public void glTexEnvxv (int target, int pname, IntBuffer params) { + begin("glTexEnvxv"); + arg("target", getTextureEnvTarget(target)); + arg("pname", getTextureEnvPName(pname)); + arg("params", getTextureEnvParamCount(pname), params); + end(); + + mgl.glTexEnvxv(target, pname, params); + checkError(); + } + + public void glTexImage2D (int target, int level, int internalformat, int width, int height, int border, int format, int type, + Buffer pixels) { + begin("glTexImage2D"); + arg("target", target); + arg("level", level); + arg("internalformat", internalformat); + arg("width", width); + arg("height", height); + arg("border", border); + arg("format", format); + arg("type", type); + arg("pixels", pixels.toString()); + end(); + + mgl.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); + checkError(); + } + + public void glTexParameterf (int target, int pname, float param) { + begin("glTexParameterf"); + arg("target", getTextureTarget(target)); + arg("pname", getTexturePName(pname)); + arg("param", getTextureParamName(param)); + end(); + + mgl.glTexParameterf(target, pname, param); + checkError(); + } + + public void glTexParameterx (int target, int pname, int param) { + begin("glTexParameterx"); + arg("target", getTextureTarget(target)); + arg("pname", getTexturePName(pname)); + arg("param", param); + end(); + + mgl.glTexParameterx(target, pname, param); + checkError(); + } + + public void glTexParameteriv (int target, int pname, int[] params, int offset) { + begin("glTexParameteriv"); + arg("target", getTextureTarget(target)); + arg("pname", getTexturePName(pname)); + arg("params", 4, params, offset); + end(); + + mgl11.glTexParameteriv(target, pname, params, offset); + checkError(); + } + + public void glTexParameteriv (int target, int pname, IntBuffer params) { + begin("glTexParameteriv"); + arg("target", getTextureTarget(target)); + arg("pname", getTexturePName(pname)); + arg("params", 4, params); + end(); + + mgl11.glTexParameteriv(target, pname, params); + checkError(); + } + + public void glTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, + Buffer pixels) { + begin("glTexSubImage2D"); + arg("target", getTextureTarget(target)); + arg("level", level); + arg("xoffset", xoffset); + arg("yoffset", yoffset); + arg("width", width); + arg("height", height); + arg("format", format); + arg("type", type); + arg("pixels", pixels.toString()); + end(); + mgl.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); + checkError(); + } + + public void glTranslatef (float x, float y, float z) { + begin("glTranslatef"); + arg("x", x); + arg("y", y); + arg("z", z); + end(); + mgl.glTranslatef(x, y, z); + checkError(); + } + + public void glTranslatex (int x, int y, int z) { + begin("glTranslatex"); + arg("x", x); + arg("y", y); + arg("z", z); + end(); + mgl.glTranslatex(x, y, z); + checkError(); + } + + public void glVertexPointer (int size, int type, int stride, Buffer pointer) { + begin("glVertexPointer"); + argPointer(size, type, stride, pointer); + end(); + mVertexPointer = new PointerInfo(size, type, stride, pointer); + mgl.glVertexPointer(size, type, stride, pointer); + checkError(); + } + + public void glViewport (int x, int y, int width, int height) { + begin("glViewport"); + arg("x", x); + arg("y", y); + arg("width", width); + arg("height", height); + end(); + mgl.glViewport(x, y, width, height); + checkError(); + } + + public void glClipPlanef (int plane, float[] equation, int offset) { + begin("glClipPlanef"); + arg("plane", plane); + arg("equation", 4, equation, offset); + arg("offset", offset); + end(); + mgl11.glClipPlanef(plane, equation, offset); + checkError(); + } + + public void glClipPlanef (int plane, FloatBuffer equation) { + begin("glClipPlanef"); + arg("plane", plane); + arg("equation", 4, equation); + end(); + mgl11.glClipPlanef(plane, equation); + checkError(); + } + + public void glClipPlanex (int plane, int[] equation, int offset) { + begin("glClipPlanex"); + arg("plane", plane); + arg("equation", 4, equation, offset); + arg("offset", offset); + end(); + mgl11.glClipPlanex(plane, equation, offset); + checkError(); + } + + public void glClipPlanex (int plane, IntBuffer equation) { + begin("glClipPlanef"); + arg("plane", plane); + arg("equation", 4, equation); + end(); + mgl11.glClipPlanex(plane, equation); + checkError(); + } + + // Draw Texture Extension + + public void glDrawTexfOES (float x, float y, float z, float width, float height) { + begin("glDrawTexfOES"); + arg("x", x); + arg("y", y); + arg("z", z); + arg("width", width); + arg("height", height); + end(); + mgl11Ext.glDrawTexfOES(x, y, z, width, height); + checkError(); + } + + public void glDrawTexfvOES (float[] coords, int offset) { + begin("glDrawTexfvOES"); + arg("coords", 5, coords, offset); + arg("offset", offset); + end(); + mgl11Ext.glDrawTexfvOES(coords, offset); + checkError(); + } + + public void glDrawTexfvOES (FloatBuffer coords) { + begin("glDrawTexfvOES"); + arg("coords", 5, coords); + end(); + mgl11Ext.glDrawTexfvOES(coords); + checkError(); + } + + public void glDrawTexiOES (int x, int y, int z, int width, int height) { + begin("glDrawTexiOES"); + arg("x", x); + arg("y", y); + arg("z", z); + arg("width", width); + arg("height", height); + end(); + mgl11Ext.glDrawTexiOES(x, y, z, width, height); + checkError(); + } + + public void glDrawTexivOES (int[] coords, int offset) { + begin("glDrawTexivOES"); + arg("coords", 5, coords, offset); + arg("offset", offset); + end(); + mgl11Ext.glDrawTexivOES(coords, offset); + checkError(); + } + + public void glDrawTexivOES (IntBuffer coords) { + begin("glDrawTexivOES"); + arg("coords", 5, coords); + end(); + mgl11Ext.glDrawTexivOES(coords); + checkError(); + } + + public void glDrawTexsOES (short x, short y, short z, short width, short height) { + begin("glDrawTexsOES"); + arg("x", x); + arg("y", y); + arg("z", z); + arg("width", width); + arg("height", height); + end(); + mgl11Ext.glDrawTexsOES(x, y, z, width, height); + checkError(); + } + + public void glDrawTexsvOES (short[] coords, int offset) { + begin("glDrawTexsvOES"); + arg("coords", 5, coords, offset); + arg("offset", offset); + end(); + mgl11Ext.glDrawTexsvOES(coords, offset); + checkError(); + } + + public void glDrawTexsvOES (ShortBuffer coords) { + begin("glDrawTexsvOES"); + arg("coords", 5, coords); + end(); + mgl11Ext.glDrawTexsvOES(coords); + checkError(); + } + + public void glDrawTexxOES (int x, int y, int z, int width, int height) { + begin("glDrawTexxOES"); + arg("x", x); + arg("y", y); + arg("z", z); + arg("width", width); + arg("height", height); + end(); + mgl11Ext.glDrawTexxOES(x, y, z, width, height); + checkError(); + } + + public void glDrawTexxvOES (int[] coords, int offset) { + begin("glDrawTexxvOES"); + arg("coords", 5, coords, offset); + arg("offset", offset); + end(); + mgl11Ext.glDrawTexxvOES(coords, offset); + checkError(); + } + + public void glDrawTexxvOES (IntBuffer coords) { + begin("glDrawTexxvOES"); + arg("coords", 5, coords); + end(); + mgl11Ext.glDrawTexxvOES(coords); + checkError(); + } + + public int glQueryMatrixxOES (int[] mantissa, int mantissaOffset, int[] exponent, int exponentOffset) { + begin("glQueryMatrixxOES"); + arg("mantissa", Arrays.toString(mantissa)); + arg("exponent", Arrays.toString(exponent)); + end(); + int valid = mgl10Ext.glQueryMatrixxOES(mantissa, mantissaOffset, exponent, exponentOffset); + returns(toString(16, FORMAT_FIXED, mantissa, mantissaOffset)); + returns(toString(16, FORMAT_INT, exponent, exponentOffset)); + checkError(); + return valid; + } + + public int glQueryMatrixxOES (IntBuffer mantissa, IntBuffer exponent) { + begin("glQueryMatrixxOES"); + arg("mantissa", mantissa.toString()); + arg("exponent", exponent.toString()); + end(); + int valid = mgl10Ext.glQueryMatrixxOES(mantissa, exponent); + returns(toString(16, FORMAT_FIXED, mantissa)); + returns(toString(16, FORMAT_INT, exponent)); + checkError(); + return valid; + } + + // Unsupported GL11 methods + + public void glBindBuffer (int target, int buffer) { + throw new UnsupportedOperationException(); + } + + public void glBufferData (int target, int size, Buffer data, int usage) { + throw new UnsupportedOperationException(); + } + + public void glBufferSubData (int target, int offset, int size, Buffer data) { + throw new UnsupportedOperationException(); + } + + public void glColor4ub (byte red, byte green, byte blue, byte alpha) { + throw new UnsupportedOperationException(); + } + + public void glDeleteBuffers (int n, int[] buffers, int offset) { + throw new UnsupportedOperationException(); + } + + public void glDeleteBuffers (int n, IntBuffer buffers) { + throw new UnsupportedOperationException(); + } + + public void glGenBuffers (int n, int[] buffers, int offset) { + throw new UnsupportedOperationException(); + } + + public void glGenBuffers (int n, IntBuffer buffers) { + throw new UnsupportedOperationException(); + } + + public void glGetBooleanv (int pname, boolean[] params, int offset) { + throw new UnsupportedOperationException(); + } + + public void glGetBooleanv (int pname, IntBuffer params) { + throw new UnsupportedOperationException(); + } + + public void glGetBufferParameteriv (int target, int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } + + public void glGetBufferParameteriv (int target, int pname, IntBuffer params) { + throw new UnsupportedOperationException(); + } + + public void glGetClipPlanef (int pname, float[] eqn, int offset) { + throw new UnsupportedOperationException(); + } + + public void glGetClipPlanef (int pname, FloatBuffer eqn) { + throw new UnsupportedOperationException(); + } + + public void glGetClipPlanex (int pname, int[] eqn, int offset) { + throw new UnsupportedOperationException(); + } + + public void glGetClipPlanex (int pname, IntBuffer eqn) { + throw new UnsupportedOperationException(); + } + + public void glGetFixedv (int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } + + public void glGetFixedv (int pname, IntBuffer params) { + throw new UnsupportedOperationException(); + } + + public void glGetFloatv (int pname, float[] params, int offset) { + throw new UnsupportedOperationException(); + } + + public void glGetFloatv (int pname, FloatBuffer params) { + throw new UnsupportedOperationException(); + } + + public void glGetLightfv (int light, int pname, float[] params, int offset) { + throw new UnsupportedOperationException(); + } + + public void glGetLightfv (int light, int pname, FloatBuffer params) { + throw new UnsupportedOperationException(); + } + + public void glGetLightxv (int light, int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetLightxv(int light, int pname, IntBuffer params) { - throw new UnsupportedOperationException(); - } + public void glGetLightxv (int light, int pname, IntBuffer params) { + throw new UnsupportedOperationException(); + } - public void glGetMaterialfv(int face, int pname, float[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glGetMaterialfv (int face, int pname, float[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetMaterialfv(int face, int pname, FloatBuffer params) { - throw new UnsupportedOperationException(); - } + public void glGetMaterialfv (int face, int pname, FloatBuffer params) { + throw new UnsupportedOperationException(); + } - public void glGetMaterialxv(int face, int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glGetMaterialxv (int face, int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetMaterialxv(int face, int pname, IntBuffer params) { - throw new UnsupportedOperationException(); - } + public void glGetMaterialxv (int face, int pname, IntBuffer params) { + throw new UnsupportedOperationException(); + } - public void glGetTexEnviv(int env, int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glGetTexEnviv (int env, int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetTexEnviv(int env, int pname, IntBuffer params) { - throw new UnsupportedOperationException(); - } + public void glGetTexEnviv (int env, int pname, IntBuffer params) { + throw new UnsupportedOperationException(); + } - public void glGetTexEnvxv(int env, int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glGetTexEnvxv (int env, int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetTexEnvxv(int env, int pname, IntBuffer params) { - throw new UnsupportedOperationException(); - } + public void glGetTexEnvxv (int env, int pname, IntBuffer params) { + throw new UnsupportedOperationException(); + } - public void glGetTexParameterfv(int target, int pname, float[] params, int offset) { - throw new UnsupportedOperationException(); - } - - public void glGetTexParameterfv(int target, int pname, FloatBuffer params) { - throw new UnsupportedOperationException(); - } - - public void glGetTexParameteriv(int target, int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } - - public void glGetTexParameteriv(int target, int pname, IntBuffer params) { - throw new UnsupportedOperationException(); - } - - public void glGetTexParameterxv(int target, int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } - - public void glGetTexParameterxv(int target, int pname, IntBuffer params) { - throw new UnsupportedOperationException(); - } - - public boolean glIsBuffer(int buffer) { - throw new UnsupportedOperationException(); - } - - public boolean glIsEnabled(int cap) { - throw new UnsupportedOperationException(); - } - - public boolean glIsTexture(int texture) { - throw new UnsupportedOperationException(); - } - - public void glPointParameterf(int pname, float param) { - throw new UnsupportedOperationException(); - } - - public void glPointParameterfv(int pname, float[] params, int offset) { - throw new UnsupportedOperationException(); - } - - public void glPointParameterfv(int pname, FloatBuffer params) { - throw new UnsupportedOperationException(); - } - - public void glPointParameterx(int pname, int param) { - throw new UnsupportedOperationException(); - } - - public void glPointParameterxv(int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } - - public void glPointParameterxv(int pname, IntBuffer params) { - throw new UnsupportedOperationException(); - } - - public void glPointSizePointerOES(int type, int stride, Buffer pointer) { - throw new UnsupportedOperationException(); - } - - public void glTexEnvi(int target, int pname, int param) { - throw new UnsupportedOperationException(); - } - - public void glTexEnviv(int target, int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } - - public void glTexEnviv(int target, int pname, IntBuffer params) { - throw new UnsupportedOperationException(); - } - - public void glTexParameterfv(int target, int pname, float[] params, int offset) { - throw new UnsupportedOperationException(); - } - - public void glTexParameterfv(int target, int pname, FloatBuffer params) { - throw new UnsupportedOperationException(); - } - - public void glTexParameteri(int target, int pname, int param) { - throw new UnsupportedOperationException(); - } - - public void glTexParameterxv(int target, int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } - - public void glTexParameterxv(int target, int pname, IntBuffer params) { - throw new UnsupportedOperationException(); - } - - private class PointerInfo { - /** - * The number of coordinates per vertex. 1..4 - */ - public int mSize; - /** - * The type of each coordinate. - */ - public int mType; - /** - * The byte offset between consecutive vertices. 0 means mSize * - * sizeof(mType) - */ - public int mStride; - public Buffer mPointer; - public ByteBuffer mTempByteBuffer; // Only valid during glDrawXXX calls - - public PointerInfo(int size, int type, int stride, Buffer pointer) { - mSize = size; - mType = type; - mStride = stride; - mPointer = pointer; - } - - public int sizeof(int type) { - switch (type) { - case GL_UNSIGNED_BYTE: - return 1; - case GL_BYTE: - return 1; - case GL_SHORT: - return 2; - case GL_FIXED: - return 4; - case GL_FLOAT: - return 4; - default: - return 0; - } - } - - public int getStride() { - return mStride > 0 ? mStride : sizeof(mType) * mSize; - } - - public void bindByteBuffer() { - mTempByteBuffer = toByteBuffer(-1, mPointer); - } - - public void unbindByteBuffer() { - mTempByteBuffer = null; - } - } - - private Writer mLog; - private boolean mLogArgumentNames; - private int mArgCount; - - private PointerInfo mColorPointer; - private PointerInfo mNormalPointer; - private PointerInfo mTexCoordPointer; - private PointerInfo mVertexPointer; - - boolean mColorArrayEnabled; - boolean mNormalArrayEnabled; - boolean mTextureCoordArrayEnabled; - boolean mVertexArrayEnabled; - - StringBuilder mStringBuilder; -} \ No newline at end of file + public void glGetTexParameterfv (int target, int pname, float[] params, int offset) { + throw new UnsupportedOperationException(); + } + + public void glGetTexParameterfv (int target, int pname, FloatBuffer params) { + throw new UnsupportedOperationException(); + } + + public void glGetTexParameteriv (int target, int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } + + public void glGetTexParameteriv (int target, int pname, IntBuffer params) { + throw new UnsupportedOperationException(); + } + + public void glGetTexParameterxv (int target, int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } + + public void glGetTexParameterxv (int target, int pname, IntBuffer params) { + throw new UnsupportedOperationException(); + } + + public boolean glIsBuffer (int buffer) { + throw new UnsupportedOperationException(); + } + + public boolean glIsEnabled (int cap) { + throw new UnsupportedOperationException(); + } + + public boolean glIsTexture (int texture) { + throw new UnsupportedOperationException(); + } + + public void glPointParameterf (int pname, float param) { + throw new UnsupportedOperationException(); + } + + public void glPointParameterfv (int pname, float[] params, int offset) { + throw new UnsupportedOperationException(); + } + + public void glPointParameterfv (int pname, FloatBuffer params) { + throw new UnsupportedOperationException(); + } + + public void glPointParameterx (int pname, int param) { + throw new UnsupportedOperationException(); + } + + public void glPointParameterxv (int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } + + public void glPointParameterxv (int pname, IntBuffer params) { + throw new UnsupportedOperationException(); + } + + public void glPointSizePointerOES (int type, int stride, Buffer pointer) { + throw new UnsupportedOperationException(); + } + + public void glTexEnvi (int target, int pname, int param) { + throw new UnsupportedOperationException(); + } + + public void glTexEnviv (int target, int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } + + public void glTexEnviv (int target, int pname, IntBuffer params) { + throw new UnsupportedOperationException(); + } + + public void glTexParameterfv (int target, int pname, float[] params, int offset) { + throw new UnsupportedOperationException(); + } + + public void glTexParameterfv (int target, int pname, FloatBuffer params) { + throw new UnsupportedOperationException(); + } + + public void glTexParameteri (int target, int pname, int param) { + throw new UnsupportedOperationException(); + } + + public void glTexParameterxv (int target, int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } + + public void glTexParameterxv (int target, int pname, IntBuffer params) { + throw new UnsupportedOperationException(); + } + + private class PointerInfo { + /** + * The number of coordinates per vertex. 1..4 + */ + public int mSize; + /** + * The type of each coordinate. + */ + public int mType; + /** + * The byte offset between consecutive vertices. 0 means mSize * sizeof(mType) + */ + public int mStride; + public Buffer mPointer; + public ByteBuffer mTempByteBuffer; // Only valid during glDrawXXX calls + + public PointerInfo (int size, int type, int stride, Buffer pointer) { + mSize = size; + mType = type; + mStride = stride; + mPointer = pointer; + } + + public int sizeof (int type) { + switch (type) { + case GL_UNSIGNED_BYTE: + return 1; + case GL_BYTE: + return 1; + case GL_SHORT: + return 2; + case GL_FIXED: + return 4; + case GL_FLOAT: + return 4; + default: + return 0; + } + } + + public int getStride () { + return mStride > 0 ? mStride : sizeof(mType) * mSize; + } + + public void bindByteBuffer () { + mTempByteBuffer = toByteBuffer(-1, mPointer); + } + + public void unbindByteBuffer () { + mTempByteBuffer = null; + } + } + + private Writer mLog; + private boolean mLogArgumentNames; + private int mArgCount; + + private PointerInfo mColorPointer; + private PointerInfo mNormalPointer; + private PointerInfo mTexCoordPointer; + private PointerInfo mVertexPointer; + + boolean mColorArrayEnabled; + boolean mNormalArrayEnabled; + boolean mTextureCoordArrayEnabled; + boolean mVertexArrayEnabled; + + StringBuilder mStringBuilder; +} diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLSurfaceView20.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLSurfaceView20.java index f5f988e5a..739a85c37 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLSurfaceView20.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLSurfaceView20.java @@ -1,37 +1,31 @@ /* * Copyright (C) 2009 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. */ package com.badlogic.gdx.backends.android.surfaceview; + /* * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. */ - import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; @@ -43,278 +37,207 @@ import android.opengl.GLSurfaceView; import android.util.Log; /** - * A simple GLSurfaceView sub-class that demonstrate how to perform - * OpenGL ES 2.0 rendering into a GL Surface. Note the following important - * details: - * - * - The class must use a custom context factory to enable 2.0 rendering. - * See ContextFactory class definition below. - * - * - The class must use a custom EGLConfigChooser to be able to select - * an EGLConfig that supports 2.0. This is done by providing a config - * specification to eglChooseConfig() that has the attribute - * EGL10.ELG_RENDERABLE_TYPE containing the EGL_OPENGL_ES2_BIT flag - * set. See ConfigChooser class definition below. - * - * - The class must select the surface's format, then choose an EGLConfig - * that matches it exactly (with regards to red/green/blue/alpha channels - * bit depths). Failure to do so would result in an EGL_BAD_MATCH error. + * A simple GLSurfaceView sub-class that demonstrate how to perform OpenGL ES 2.0 rendering into a GL Surface. Note the following + * important details: + * + * - The class must use a custom context factory to enable 2.0 rendering. See ContextFactory class definition below. + * + * - The class must use a custom EGLConfigChooser to be able to select an EGLConfig that supports 2.0. This is done by providing a + * config specification to eglChooseConfig() that has the attribute EGL10.ELG_RENDERABLE_TYPE containing the EGL_OPENGL_ES2_BIT + * flag set. See ConfigChooser class definition below. + * + * - The class must select the surface's format, then choose an EGLConfig that matches it exactly (with regards to + * red/green/blue/alpha channels bit depths). Failure to do so would result in an EGL_BAD_MATCH error. */ public class GLSurfaceView20 extends GLSurfaceView { - private static String TAG = "GL2JNIView"; - private static final boolean DEBUG = false; - - public GLSurfaceView20(Context context) { - super(context); - init(false, 16, 0); - } - - public GLSurfaceView20(Context context, boolean translucent, int depth, int stencil) { - super(context); - init(translucent, depth, stencil); - } - - private void init(boolean translucent, int depth, int stencil) { - - /* By default, GLSurfaceView() creates a RGB_565 opaque surface. - * If we want a translucent one, we should change the surface's - * format here, using PixelFormat.TRANSLUCENT for GL Surfaces - * is interpreted as any 32-bit surface with alpha by SurfaceFlinger. - */ - if (translucent) { - this.getHolder().setFormat(PixelFormat.TRANSLUCENT); - } - - /* Setup the context factory for 2.0 rendering. - * See ContextFactory class definition below - */ - setEGLContextFactory(new ContextFactory()); - - /* We need to choose an EGLConfig that matches the format of - * our surface exactly. This is going to be done in our - * custom config chooser. See ConfigChooser class definition - * below. - */ - setEGLConfigChooser( translucent ? - new ConfigChooser(8, 8, 8, 8, depth, stencil) : - new ConfigChooser(5, 6, 5, 0, depth, stencil) ); - - /* Set the renderer responsible for frame rendering */ - } - - private static class ContextFactory implements GLSurfaceView.EGLContextFactory { - private static int EGL_CONTEXT_CLIENT_VERSION = 0x3098; - public EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig eglConfig) { - Log.w(TAG, "creating OpenGL ES 2.0 context"); - checkEglError("Before eglCreateContext", egl); - int[] attrib_list = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE }; - EGLContext context = egl.eglCreateContext(display, eglConfig, EGL10.EGL_NO_CONTEXT, attrib_list); - checkEglError("After eglCreateContext", egl); - return context; - } - - public void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context) { - egl.eglDestroyContext(display, context); - } - } - - private static void checkEglError(String prompt, EGL10 egl) { - int error; - while ((error = egl.eglGetError()) != EGL10.EGL_SUCCESS) { - Log.e(TAG, String.format("%s: EGL error: 0x%x", prompt, error)); - } - } - - private static class ConfigChooser implements GLSurfaceView.EGLConfigChooser { - - public ConfigChooser(int r, int g, int b, int a, int depth, int stencil) { - mRedSize = r; - mGreenSize = g; - mBlueSize = b; - mAlphaSize = a; - mDepthSize = depth; - mStencilSize = stencil; - } - - /* This EGL config specification is used to specify 2.0 rendering. - * We use a minimum size of 4 bits for red/green/blue, but will - * perform actual matching in chooseConfig() below. - */ - private static int EGL_OPENGL_ES2_BIT = 4; - private static int[] s_configAttribs2 = - { - EGL10.EGL_RED_SIZE, 4, - EGL10.EGL_GREEN_SIZE, 4, - EGL10.EGL_BLUE_SIZE, 4, - EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - EGL10.EGL_NONE - }; - - public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) { - - /* Get the number of minimally matching EGL configurations - */ - int[] num_config = new int[1]; - egl.eglChooseConfig(display, s_configAttribs2, null, 0, num_config); - - int numConfigs = num_config[0]; - - if (numConfigs <= 0) { - throw new IllegalArgumentException("No configs match configSpec"); - } - - /* Allocate then read the array of minimally matching EGL configs - */ - EGLConfig[] configs = new EGLConfig[numConfigs]; - egl.eglChooseConfig(display, s_configAttribs2, configs, numConfigs, num_config); - - if (DEBUG) { - printConfigs(egl, display, configs); - } - /* Now return the "best" one - */ - return chooseConfig(egl, display, configs); - } - - public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, - EGLConfig[] configs) { - for(EGLConfig config : configs) { - int d = findConfigAttrib(egl, display, config, - EGL10.EGL_DEPTH_SIZE, 0); - int s = findConfigAttrib(egl, display, config, - EGL10.EGL_STENCIL_SIZE, 0); - - // We need at least mDepthSize and mStencilSize bits - if (d < mDepthSize || s < mStencilSize) - continue; - - // We want an *exact* match for red/green/blue/alpha - int r = findConfigAttrib(egl, display, config, - EGL10.EGL_RED_SIZE, 0); - int g = findConfigAttrib(egl, display, config, - EGL10.EGL_GREEN_SIZE, 0); - int b = findConfigAttrib(egl, display, config, - EGL10.EGL_BLUE_SIZE, 0); - int a = findConfigAttrib(egl, display, config, - EGL10.EGL_ALPHA_SIZE, 0); - - if (r == mRedSize && g == mGreenSize && b == mBlueSize && a == mAlphaSize) - return config; - } - return null; - } - - private int findConfigAttrib(EGL10 egl, EGLDisplay display, - EGLConfig config, int attribute, int defaultValue) { - - if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) { - return mValue[0]; - } - return defaultValue; - } - - private void printConfigs(EGL10 egl, EGLDisplay display, - EGLConfig[] configs) { - int numConfigs = configs.length; - Log.w(TAG, String.format("%d configurations", numConfigs)); - for (int i = 0; i < numConfigs; i++) { - Log.w(TAG, String.format("Configuration %d:\n", i)); - printConfig(egl, display, configs[i]); - } - } - - private void printConfig(EGL10 egl, EGLDisplay display, - EGLConfig config) { - int[] attributes = { - EGL10.EGL_BUFFER_SIZE, - EGL10.EGL_ALPHA_SIZE, - EGL10.EGL_BLUE_SIZE, - EGL10.EGL_GREEN_SIZE, - EGL10.EGL_RED_SIZE, - EGL10.EGL_DEPTH_SIZE, - EGL10.EGL_STENCIL_SIZE, - EGL10.EGL_CONFIG_CAVEAT, - EGL10.EGL_CONFIG_ID, - EGL10.EGL_LEVEL, - EGL10.EGL_MAX_PBUFFER_HEIGHT, - EGL10.EGL_MAX_PBUFFER_PIXELS, - EGL10.EGL_MAX_PBUFFER_WIDTH, - EGL10.EGL_NATIVE_RENDERABLE, - EGL10.EGL_NATIVE_VISUAL_ID, - EGL10.EGL_NATIVE_VISUAL_TYPE, - 0x3030, // EGL10.EGL_PRESERVED_RESOURCES, - EGL10.EGL_SAMPLES, - EGL10.EGL_SAMPLE_BUFFERS, - EGL10.EGL_SURFACE_TYPE, - EGL10.EGL_TRANSPARENT_TYPE, - EGL10.EGL_TRANSPARENT_RED_VALUE, - EGL10.EGL_TRANSPARENT_GREEN_VALUE, - EGL10.EGL_TRANSPARENT_BLUE_VALUE, - 0x3039, // EGL10.EGL_BIND_TO_TEXTURE_RGB, - 0x303A, // EGL10.EGL_BIND_TO_TEXTURE_RGBA, - 0x303B, // EGL10.EGL_MIN_SWAP_INTERVAL, - 0x303C, // EGL10.EGL_MAX_SWAP_INTERVAL, - EGL10.EGL_LUMINANCE_SIZE, - EGL10.EGL_ALPHA_MASK_SIZE, - EGL10.EGL_COLOR_BUFFER_TYPE, - EGL10.EGL_RENDERABLE_TYPE, - 0x3042 // EGL10.EGL_CONFORMANT - }; - String[] names = { - "EGL_BUFFER_SIZE", - "EGL_ALPHA_SIZE", - "EGL_BLUE_SIZE", - "EGL_GREEN_SIZE", - "EGL_RED_SIZE", - "EGL_DEPTH_SIZE", - "EGL_STENCIL_SIZE", - "EGL_CONFIG_CAVEAT", - "EGL_CONFIG_ID", - "EGL_LEVEL", - "EGL_MAX_PBUFFER_HEIGHT", - "EGL_MAX_PBUFFER_PIXELS", - "EGL_MAX_PBUFFER_WIDTH", - "EGL_NATIVE_RENDERABLE", - "EGL_NATIVE_VISUAL_ID", - "EGL_NATIVE_VISUAL_TYPE", - "EGL_PRESERVED_RESOURCES", - "EGL_SAMPLES", - "EGL_SAMPLE_BUFFERS", - "EGL_SURFACE_TYPE", - "EGL_TRANSPARENT_TYPE", - "EGL_TRANSPARENT_RED_VALUE", - "EGL_TRANSPARENT_GREEN_VALUE", - "EGL_TRANSPARENT_BLUE_VALUE", - "EGL_BIND_TO_TEXTURE_RGB", - "EGL_BIND_TO_TEXTURE_RGBA", - "EGL_MIN_SWAP_INTERVAL", - "EGL_MAX_SWAP_INTERVAL", - "EGL_LUMINANCE_SIZE", - "EGL_ALPHA_MASK_SIZE", - "EGL_COLOR_BUFFER_TYPE", - "EGL_RENDERABLE_TYPE", - "EGL_CONFORMANT" - }; - int[] value = new int[1]; - for (int i = 0; i < attributes.length; i++) { - int attribute = attributes[i]; - String name = names[i]; - if ( egl.eglGetConfigAttrib(display, config, attribute, value)) { - Log.w(TAG, String.format(" %s: %d\n", name, value[0])); - } else { - // Log.w(TAG, String.format(" %s: failed\n", name)); - while (egl.eglGetError() != EGL10.EGL_SUCCESS); - } - } - } - - // Subclasses can adjust these values: - protected int mRedSize; - protected int mGreenSize; - protected int mBlueSize; - protected int mAlphaSize; - protected int mDepthSize; - protected int mStencilSize; - private int[] mValue = new int[1]; - } + private static String TAG = "GL2JNIView"; + private static final boolean DEBUG = false; + + public GLSurfaceView20 (Context context) { + super(context); + init(false, 16, 0); + } + + public GLSurfaceView20 (Context context, boolean translucent, int depth, int stencil) { + super(context); + init(translucent, depth, stencil); + } + + private void init (boolean translucent, int depth, int stencil) { + + /* + * By default, GLSurfaceView() creates a RGB_565 opaque surface. If we want a translucent one, we should change the + * surface's format here, using PixelFormat.TRANSLUCENT for GL Surfaces is interpreted as any 32-bit surface with alpha by + * SurfaceFlinger. + */ + if (translucent) { + this.getHolder().setFormat(PixelFormat.TRANSLUCENT); + } + + /* + * Setup the context factory for 2.0 rendering. See ContextFactory class definition below + */ + setEGLContextFactory(new ContextFactory()); + + /* + * We need to choose an EGLConfig that matches the format of our surface exactly. This is going to be done in our custom + * config chooser. See ConfigChooser class definition below. + */ + setEGLConfigChooser(translucent ? new ConfigChooser(8, 8, 8, 8, depth, stencil) : new ConfigChooser(5, 6, 5, 0, depth, + stencil)); + + /* Set the renderer responsible for frame rendering */ + } + + private static class ContextFactory implements GLSurfaceView.EGLContextFactory { + private static int EGL_CONTEXT_CLIENT_VERSION = 0x3098; + + public EGLContext createContext (EGL10 egl, EGLDisplay display, EGLConfig eglConfig) { + Log.w(TAG, "creating OpenGL ES 2.0 context"); + checkEglError("Before eglCreateContext", egl); + int[] attrib_list = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE}; + EGLContext context = egl.eglCreateContext(display, eglConfig, EGL10.EGL_NO_CONTEXT, attrib_list); + checkEglError("After eglCreateContext", egl); + return context; + } + + public void destroyContext (EGL10 egl, EGLDisplay display, EGLContext context) { + egl.eglDestroyContext(display, context); + } + } + + private static void checkEglError (String prompt, EGL10 egl) { + int error; + while ((error = egl.eglGetError()) != EGL10.EGL_SUCCESS) { + Log.e(TAG, String.format("%s: EGL error: 0x%x", prompt, error)); + } + } + + private static class ConfigChooser implements GLSurfaceView.EGLConfigChooser { + + public ConfigChooser (int r, int g, int b, int a, int depth, int stencil) { + mRedSize = r; + mGreenSize = g; + mBlueSize = b; + mAlphaSize = a; + mDepthSize = depth; + mStencilSize = stencil; + } + + /* + * This EGL config specification is used to specify 2.0 rendering. We use a minimum size of 4 bits for red/green/blue, but + * will perform actual matching in chooseConfig() below. + */ + private static int EGL_OPENGL_ES2_BIT = 4; + private static int[] s_configAttribs2 = {EGL10.EGL_RED_SIZE, 4, EGL10.EGL_GREEN_SIZE, 4, EGL10.EGL_BLUE_SIZE, 4, + EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL10.EGL_NONE}; + + public EGLConfig chooseConfig (EGL10 egl, EGLDisplay display) { + + /* + * Get the number of minimally matching EGL configurations + */ + int[] num_config = new int[1]; + egl.eglChooseConfig(display, s_configAttribs2, null, 0, num_config); + + int numConfigs = num_config[0]; + + if (numConfigs <= 0) { + throw new IllegalArgumentException("No configs match configSpec"); + } + + /* + * Allocate then read the array of minimally matching EGL configs + */ + EGLConfig[] configs = new EGLConfig[numConfigs]; + egl.eglChooseConfig(display, s_configAttribs2, configs, numConfigs, num_config); + + if (DEBUG) { + printConfigs(egl, display, configs); + } + /* + * Now return the "best" one + */ + return chooseConfig(egl, display, configs); + } + + public EGLConfig chooseConfig (EGL10 egl, EGLDisplay display, EGLConfig[] configs) { + for (EGLConfig config : configs) { + int d = findConfigAttrib(egl, display, config, EGL10.EGL_DEPTH_SIZE, 0); + int s = findConfigAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0); + + // We need at least mDepthSize and mStencilSize bits + if (d < mDepthSize || s < mStencilSize) continue; + + // We want an *exact* match for red/green/blue/alpha + int r = findConfigAttrib(egl, display, config, EGL10.EGL_RED_SIZE, 0); + int g = findConfigAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0); + int b = findConfigAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0); + int a = findConfigAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0); + + if (r == mRedSize && g == mGreenSize && b == mBlueSize && a == mAlphaSize) return config; + } + return null; + } + + private int findConfigAttrib (EGL10 egl, EGLDisplay display, EGLConfig config, int attribute, int defaultValue) { + + if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) { + return mValue[0]; + } + return defaultValue; + } + + private void printConfigs (EGL10 egl, EGLDisplay display, EGLConfig[] configs) { + int numConfigs = configs.length; + Log.w(TAG, String.format("%d configurations", numConfigs)); + for (int i = 0; i < numConfigs; i++) { + Log.w(TAG, String.format("Configuration %d:\n", i)); + printConfig(egl, display, configs[i]); + } + } + + private void printConfig (EGL10 egl, EGLDisplay display, EGLConfig config) { + int[] attributes = {EGL10.EGL_BUFFER_SIZE, EGL10.EGL_ALPHA_SIZE, EGL10.EGL_BLUE_SIZE, EGL10.EGL_GREEN_SIZE, + EGL10.EGL_RED_SIZE, EGL10.EGL_DEPTH_SIZE, EGL10.EGL_STENCIL_SIZE, EGL10.EGL_CONFIG_CAVEAT, EGL10.EGL_CONFIG_ID, + EGL10.EGL_LEVEL, EGL10.EGL_MAX_PBUFFER_HEIGHT, EGL10.EGL_MAX_PBUFFER_PIXELS, EGL10.EGL_MAX_PBUFFER_WIDTH, + EGL10.EGL_NATIVE_RENDERABLE, EGL10.EGL_NATIVE_VISUAL_ID, EGL10.EGL_NATIVE_VISUAL_TYPE, + 0x3030, // EGL10.EGL_PRESERVED_RESOURCES, + EGL10.EGL_SAMPLES, EGL10.EGL_SAMPLE_BUFFERS, EGL10.EGL_SURFACE_TYPE, EGL10.EGL_TRANSPARENT_TYPE, + EGL10.EGL_TRANSPARENT_RED_VALUE, EGL10.EGL_TRANSPARENT_GREEN_VALUE, EGL10.EGL_TRANSPARENT_BLUE_VALUE, 0x3039, // EGL10.EGL_BIND_TO_TEXTURE_RGB, + 0x303A, // EGL10.EGL_BIND_TO_TEXTURE_RGBA, + 0x303B, // EGL10.EGL_MIN_SWAP_INTERVAL, + 0x303C, // EGL10.EGL_MAX_SWAP_INTERVAL, + EGL10.EGL_LUMINANCE_SIZE, EGL10.EGL_ALPHA_MASK_SIZE, EGL10.EGL_COLOR_BUFFER_TYPE, EGL10.EGL_RENDERABLE_TYPE, 0x3042 // EGL10.EGL_CONFORMANT + }; + String[] names = {"EGL_BUFFER_SIZE", "EGL_ALPHA_SIZE", "EGL_BLUE_SIZE", "EGL_GREEN_SIZE", "EGL_RED_SIZE", + "EGL_DEPTH_SIZE", "EGL_STENCIL_SIZE", "EGL_CONFIG_CAVEAT", "EGL_CONFIG_ID", "EGL_LEVEL", "EGL_MAX_PBUFFER_HEIGHT", + "EGL_MAX_PBUFFER_PIXELS", "EGL_MAX_PBUFFER_WIDTH", "EGL_NATIVE_RENDERABLE", "EGL_NATIVE_VISUAL_ID", + "EGL_NATIVE_VISUAL_TYPE", "EGL_PRESERVED_RESOURCES", "EGL_SAMPLES", "EGL_SAMPLE_BUFFERS", "EGL_SURFACE_TYPE", + "EGL_TRANSPARENT_TYPE", "EGL_TRANSPARENT_RED_VALUE", "EGL_TRANSPARENT_GREEN_VALUE", "EGL_TRANSPARENT_BLUE_VALUE", + "EGL_BIND_TO_TEXTURE_RGB", "EGL_BIND_TO_TEXTURE_RGBA", "EGL_MIN_SWAP_INTERVAL", "EGL_MAX_SWAP_INTERVAL", + "EGL_LUMINANCE_SIZE", "EGL_ALPHA_MASK_SIZE", "EGL_COLOR_BUFFER_TYPE", "EGL_RENDERABLE_TYPE", "EGL_CONFORMANT"}; + int[] value = new int[1]; + for (int i = 0; i < attributes.length; i++) { + int attribute = attributes[i]; + String name = names[i]; + if (egl.eglGetConfigAttrib(display, config, attribute, value)) { + Log.w(TAG, String.format(" %s: %d\n", name, value[0])); + } else { + // Log.w(TAG, String.format(" %s: failed\n", name)); + while (egl.eglGetError() != EGL10.EGL_SUCCESS) + ; + } + } + } + + // Subclasses can adjust these values: + protected int mRedSize; + protected int mGreenSize; + protected int mBlueSize; + protected int mAlphaSize; + protected int mDepthSize; + protected int mStencilSize; + private int[] mValue = new int[1]; + } } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLSurfaceViewCupcake.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLSurfaceViewCupcake.java index 4681bbe5d..c92aa9e80 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLSurfaceViewCupcake.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLSurfaceViewCupcake.java @@ -1,17 +1,14 @@ /* * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. */ package com.badlogic.gdx.backends.android.surfaceview; @@ -37,36 +34,30 @@ import android.view.SurfaceHolder; import android.view.SurfaceView; /** - * An implementation of SurfaceView that uses the dedicated surface for - * displaying OpenGL rendering. + * An implementation of SurfaceView that uses the dedicated surface for displaying OpenGL rendering. *

* A GLSurfaceView provides the following features: *

*

    - *
  • Manages a surface, which is a special piece of memory that can be - * composited into the Android view system. + *
  • Manages a surface, which is a special piece of memory that can be composited into the Android view system. *
  • Manages an EGL display, which enables OpenGL to render into a surface. *
  • Accepts a user-provided Renderer object that does the actual rendering. - *
  • Renders on a dedicated thread to decouple rendering performance from the - * UI thread. + *
  • Renders on a dedicated thread to decouple rendering performance from the UI thread. *
  • Supports both on-demand and continuous rendering. *
  • Optionally wraps, traces, and/or error-checks the renderer's OpenGL calls. *
- * + * *

Using GLSurfaceView

*

- * Typically you use GLSurfaceView by subclassing it and overriding one or more of the - * View system input event methods. If your application does not need to override event - * methods then GLSurfaceView can be used as-is. For the most part - * GLSurfaceView behavior is customized by calling "set" methods rather than by subclassing. - * For example, unlike a regular View, drawing is delegated to a separate Renderer object which - * is registered with the GLSurfaceView - * using the {@link #setRenderer(Renderer)} call. + * Typically you use GLSurfaceView by subclassing it and overriding one or more of the View system input event methods. If your + * application does not need to override event methods then GLSurfaceView can be used as-is. For the most part GLSurfaceView + * behavior is customized by calling "set" methods rather than by subclassing. For example, unlike a regular View, drawing is + * delegated to a separate Renderer object which is registered with the GLSurfaceView using the {@link #setRenderer(Renderer)} + * call. *

*

Initializing GLSurfaceView

- * All you have to do to initialize a GLSurfaceView is call {@link #setRenderer(Renderer)}. - * However, if desired, you can modify the default behavior of GLSurfaceView by calling one or - * more of these methods before calling setRenderer: + * All you have to do to initialize a GLSurfaceView is call {@link #setRenderer(Renderer)}. However, if desired, you can modify + * the default behavior of GLSurfaceView by calling one or more of these methods before calling setRenderer: *
    *
  • {@link #setDebugFlags(int)} *
  • {@link #setEGLConfigChooser(boolean)} @@ -76,987 +67,893 @@ import android.view.SurfaceView; *
*

*

Choosing an EGL Configuration

- * A given Android device may support multiple possible types of drawing surfaces. - * The available surfaces may differ in how may channels of data are present, as - * well as how many bits are allocated to each channel. Therefore, the first thing - * GLSurfaceView has to do when starting to render is choose what type of surface to use. + * A given Android device may support multiple possible types of drawing surfaces. The available surfaces may differ in how may + * channels of data are present, as well as how many bits are allocated to each channel. Therefore, the first thing GLSurfaceView + * has to do when starting to render is choose what type of surface to use. *

- * By default GLSurfaceView chooses an available surface that's closest to a 16-bit R5G6B5 surface - * with a 16-bit depth buffer and no stencil. If you would prefer a different surface (for example, - * if you do not need a depth buffer) you can override the default behavior by calling one of the - * setEGLConfigChooser methods. + * By default GLSurfaceView chooses an available surface that's closest to a 16-bit R5G6B5 surface with a 16-bit depth buffer and + * no stencil. If you would prefer a different surface (for example, if you do not need a depth buffer) you can override the + * default behavior by calling one of the setEGLConfigChooser methods. *

*

Debug Behavior

- * You can optionally modify the behavior of GLSurfaceView by calling - * one or more of the debugging methods {@link #setDebugFlags(int)}, - * and {@link #setGLWrapper}. These methods may be called before and/or after setRenderer, but + * You can optionally modify the behavior of GLSurfaceView by calling one or more of the debugging methods + * {@link #setDebugFlags(int)}, and {@link #setGLWrapper}. These methods may be called before and/or after setRenderer, but * typically they are called before setRenderer so that they take effect immediately. *

*

Setting a Renderer

- * Finally, you must call {@link #setRenderer} to register a {@link Renderer}. - * The renderer is - * responsible for doing the actual OpenGL rendering. + * Finally, you must call {@link #setRenderer} to register a {@link Renderer}. The renderer is responsible for doing the actual + * OpenGL rendering. *

*

Rendering Mode

- * Once the renderer is set, you can control whether the renderer draws - * continuously or on-demand by calling + * Once the renderer is set, you can control whether the renderer draws continuously or on-demand by calling * {@link #setRenderMode}. The default is continuous rendering. *

*

Activity Life-cycle

- * A GLSurfaceView must be notified when the activity is paused and resumed. GLSurfaceView clients - * are required to call {@link #onPause()} when the activity pauses and - * {@link #onResume()} when the activity resumes. These calls allow GLSurfaceView to - * pause and resume the rendering thread, and also allow GLSurfaceView to release and recreate - * the OpenGL display. + * A GLSurfaceView must be notified when the activity is paused and resumed. GLSurfaceView clients are required to call + * {@link #onPause()} when the activity pauses and {@link #onResume()} when the activity resumes. These calls allow GLSurfaceView + * to pause and resume the rendering thread, and also allow GLSurfaceView to release and recreate the OpenGL display. *

*

Handling events

*

- * To handle an event you will typically subclass GLSurfaceView and override the - * appropriate method, just as you would with any other View. However, when handling - * the event, you may need to communicate with the Renderer object - * that's running in the rendering thread. You can do this using any - * standard Java cross-thread communication mechanism. In addition, - * one relatively easy way to communicate with your renderer is - * to call - * {@link #queueEvent(Runnable)}. For example: + * To handle an event you will typically subclass GLSurfaceView and override the appropriate method, just as you would with any + * other View. However, when handling the event, you may need to communicate with the Renderer object that's running in the + * rendering thread. You can do this using any standard Java cross-thread communication mechanism. In addition, one relatively + * easy way to communicate with your renderer is to call {@link #queueEvent(Runnable)}. For example: + * *

  * class MyGLSurfaceView extends GLSurfaceView {
- *
- *     private MyRenderer mMyRenderer;
- *
- *     public void start() {
+ * 
+ * 	private MyRenderer mMyRenderer;
+ * 
+ * 	public void start() {
  *         mMyRenderer = ...;
  *         setRenderer(mMyRenderer);
  *     }
- *
- *     public boolean onKeyDown(int keyCode, KeyEvent event) {
- *         if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
- *             queueEvent(new Runnable() {
- *                 // This method will be called on the rendering
- *                 // thread:
- *                 public void run() {
- *                     mMyRenderer.handleDpadCenter();
- *                 }});
- *             return true;
- *         }
- *         return super.onKeyDown(keyCode, event);
- *     }
+ * 
+ * 	public boolean onKeyDown (int keyCode, KeyEvent event) {
+ * 		if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
+ * 			queueEvent(new Runnable() {
+ * 				// This method will be called on the rendering
+ * 				// thread:
+ * 				public void run () {
+ * 					mMyRenderer.handleDpadCenter();
+ * 				}
+ * 			});
+ * 			return true;
+ * 		}
+ * 		return super.onKeyDown(keyCode, event);
+ * 	}
  * }
+ * 
  * 
- * + * */ public class GLSurfaceViewCupcake extends SurfaceView implements SurfaceHolder.Callback { - /** - * The renderer only renders - * when the surface is created, or when {@link #requestRender} is called. - * - * @see #getRenderMode() - * @see #setRenderMode(int) - */ - public final static int RENDERMODE_WHEN_DIRTY = 0; - /** - * The renderer is called - * continuously to re-render the scene. - * - * @see #getRenderMode() - * @see #setRenderMode(int) - * @see #requestRender() - */ - public final static int RENDERMODE_CONTINUOUSLY = 1; - - /** - * Check glError() after every GL call and throw an exception if glError indicates - * that an error has occurred. This can be used to help track down which OpenGL ES call - * is causing an error. - * - * @see #getDebugFlags - * @see #setDebugFlags - */ - public final static int DEBUG_CHECK_GL_ERROR = 1; - - /** - * Log GL calls to the system log at "verbose" level with tag "GLSurfaceView". - * - * @see #getDebugFlags - * @see #setDebugFlags - */ - public final static int DEBUG_LOG_GL_CALLS = 2; - - /** - * Standard View constructor. In order to render something, you - * must call {@link #setRenderer} to register a renderer. - */ - public GLSurfaceViewCupcake(Context context) { - super(context); - init(); - } - - /** - * Standard View constructor. In order to render something, you - * must call {@link #setRenderer} to register a renderer. - */ - public GLSurfaceViewCupcake(Context context, AttributeSet attrs) { - super(context, attrs); - init(); - } - - private void init() { - // Install a SurfaceHolder.Callback so we get notified when the - // underlying surface is created and destroyed - SurfaceHolder holder = getHolder(); - holder.addCallback(this); - holder.setType(SurfaceHolder.SURFACE_TYPE_GPU); - mRenderMode = RENDERMODE_CONTINUOUSLY; - } - - /** - * Set the glWrapper. If the glWrapper is not null, its - * {@link GLWrapper#wrap(GL)} method is called - * whenever a surface is created. A GLWrapper can be used to wrap - * the GL object that's passed to the renderer. Wrapping a GL - * object enables examining and modifying the behavior of the - * GL calls made by the renderer. - *

- * Wrapping is typically used for debugging purposes. - *

- * The default value is null. - * @param glWrapper the new GLWrapper - */ - public void setGLWrapper(GLWrapper glWrapper) { - mGLWrapper = glWrapper; - } - - /** - * Set the debug flags to a new value. The value is - * constructed by OR-together zero or more - * of the DEBUG_CHECK_* constants. The debug flags take effect - * whenever a surface is created. The default value is zero. - * @param debugFlags the new debug flags - * @see #DEBUG_CHECK_GL_ERROR - * @see #DEBUG_LOG_GL_CALLS - */ - public void setDebugFlags(int debugFlags) { - mDebugFlags = debugFlags; - } - - /** - * Get the current value of the debug flags. - * @return the current value of the debug flags. - */ - public int getDebugFlags() { - return mDebugFlags; - } - - /** - * Set the renderer associated with this view. Also starts the thread that - * will call the renderer, which in turn causes the rendering to start. - *

This method should be called once and only once in the life-cycle of - * a GLSurfaceView. - *

The following GLSurfaceView methods can only be called before - * setRenderer is called: - *

    - *
  • {@link #setEGLConfigChooser(boolean)} - *
  • {@link #setEGLConfigChooser(EGLConfigChooser)} - *
  • {@link #setEGLConfigChooser(int, int, int, int, int, int)} - *
- *

- * The following GLSurfaceView methods can only be called after - * setRenderer is called: - *

    - *
  • {@link #getRenderMode()} - *
  • {@link #onPause()} - *
  • {@link #onResume()} - *
  • {@link #queueEvent(Runnable)} - *
  • {@link #requestRender()} - *
  • {@link #setRenderMode(int)} - *
- * - * @param renderer the renderer to use to perform OpenGL drawing. - */ - public void setRenderer(Renderer renderer) { - if (mRenderer != null) { - throw new IllegalStateException( - "setRenderer has already been called for this instance."); - } - - mRenderer = renderer; - } - - /** - * Install a custom EGLConfigChooser. - *

If this method is - * called, it must be called before {@link #setRenderer(Renderer)} - * is called. - *

- * If no setEGLConfigChooser method is called, then by default the - * view will choose a config as close to 16-bit RGB as possible, with - * a depth buffer as close to 16 bits as possible. - * @param configChooser - */ - public void setEGLConfigChooser(EGLConfigChooser configChooser) { - if (mRenderer != null) { - throw new IllegalStateException( - "setRenderer has already been called for this instance."); - } - mEGLConfigChooser = configChooser; - } - - /** - * Install a config chooser which will choose a config - * as close to 16-bit RGB as possible, with or without an optional depth - * buffer as close to 16-bits as possible. - *

If this method is - * called, it must be called before {@link #setRenderer(Renderer)} - * is called. - *

- * If no setEGLConfigChooser method is called, then by default the - * view will choose a config as close to 16-bit RGB as possible, with - * a depth buffer as close to 16 bits as possible. - * - * @param needDepth - */ - public void setEGLConfigChooser(boolean needDepth) { - setEGLConfigChooser(new SimpleEGLConfigChooser(needDepth)); - } - - /** - * Install a config chooser which will choose a config - * with at least the specified component sizes, and as close - * to the specified component sizes as possible. - *

If this method is - * called, it must be called before {@link #setRenderer(Renderer)} - * is called. - *

- * If no setEGLConfigChooser method is called, then by default the - * view will choose a config as close to 16-bit RGB as possible, with - * a depth buffer as close to 16 bits as possible. - * - */ - public void setEGLConfigChooser(int redSize, int greenSize, int blueSize, - int alphaSize, int depthSize, int stencilSize) { - setEGLConfigChooser(new ComponentSizeChooser(redSize, greenSize, - blueSize, alphaSize, depthSize, stencilSize)); - } - /** - * Set the rendering mode. When renderMode is - * RENDERMODE_CONTINUOUSLY, the renderer is called - * repeatedly to re-render the scene. When renderMode - * is RENDERMODE_WHEN_DIRTY, the renderer only rendered when the surface - * is created, or when {@link #requestRender} is called. Defaults to RENDERMODE_CONTINUOUSLY. - *

- * Using RENDERMODE_WHEN_DIRTY can improve battery life and overall system performance - * by allowing the GPU and CPU to idle when the view does not need to be updated. - *

- * This method can only be called after {@link #setRenderer(Renderer)} - * - * @param renderMode one of the RENDERMODE_X constants - * @see #RENDERMODE_CONTINUOUSLY - * @see #RENDERMODE_WHEN_DIRTY - */ - public void setRenderMode(int renderMode) { - mRenderMode = renderMode; - if (mGLThread != null) { - mGLThread.setRenderMode(renderMode); - } - } - - /** - * Get the current rendering mode. May be called - * from any thread. Must not be called before a renderer has been set. - * @return the current rendering mode. - * @see #RENDERMODE_CONTINUOUSLY - * @see #RENDERMODE_WHEN_DIRTY - */ - public int getRenderMode() { - return mRenderMode; - } - - /** - * Request that the renderer render a frame. - * This method is typically used when the render mode has been set to - * {@link #RENDERMODE_WHEN_DIRTY}, so that frames are only rendered on demand. - * May be called - * from any thread. Must be called after onResume() and before onPause(). - */ - public void requestRender() { - mGLThread.requestRender(); - } - - /** - * This method is part of the SurfaceHolder.Callback interface, and is - * not normally called or subclassed by clients of GLSurfaceView. - */ - public void surfaceCreated(SurfaceHolder holder) { - if (mGLThread != null) { - mGLThread.surfaceCreated(); - } - mHasSurface = true; - } - - /** - * This method is part of the SurfaceHolder.Callback interface, and is - * not normally called or subclassed by clients of GLSurfaceView. - */ - public void surfaceDestroyed(SurfaceHolder holder) { - // Surface will be destroyed when we return - if (mGLThread != null) { - mGLThread.surfaceDestroyed(); - } - mHasSurface = false; - } - - /** - * This method is part of the SurfaceHolder.Callback interface, and is - * not normally called or subclassed by clients of GLSurfaceView. - */ - public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { - if (mGLThread != null) { - mGLThread.onWindowResize(w, h); - } - mSurfaceWidth = w; - mSurfaceHeight = h; - } - - /** - * Inform the view that the activity is paused. The owner of this view must - * call this method when the activity is paused. Calling this method will - * pause the rendering thread. - * Must not be called before a renderer has been set. - */ - public void onPause() { - mGLThread.onPause(); - mGLThread.requestExitAndWait(); - mGLThread = null; - } - - /** - * Inform the view that the activity is resumed. The owner of this view must - * call this method when the activity is resumed. Calling this method will - * recreate the OpenGL display and resume the rendering - * thread. - * Must not be called before a renderer has been set. - */ - public void onResume() { - if (mEGLConfigChooser == null) { - mEGLConfigChooser = new SimpleEGLConfigChooser(true); - } - mGLThread = new GLThread(mRenderer); - mGLThread.start(); - mGLThread.setRenderMode(mRenderMode); - if (mHasSurface) { - mGLThread.surfaceCreated(); - } - if (mSurfaceWidth > 0 && mSurfaceHeight > 0) { - mGLThread.onWindowResize(mSurfaceWidth, mSurfaceHeight); - } - mGLThread.onResume(); - } - - /** - * Queue a runnable to be run on the GL rendering thread. This can be used - * to communicate with the Renderer on the rendering thread. - * Must be called after onResume() and before onPause(). - * @param r the runnable to be run on the GL rendering thread. - */ - public void queueEvent(Runnable r) { - if (mGLThread != null) { - mGLThread.queueEvent(r); - } - } - - // ---------------------------------------------------------------------- - - /** - * An interface used to wrap a GL interface. - *

Typically - * used for implementing debugging and tracing on top of the default - * GL interface. You would typically use this by creating your own class - * that implemented all the GL methods by delegating to another GL instance. - * Then you could add your own behavior before or after calling the - * delegate. All the GLWrapper would do was instantiate and return the - * wrapper GL instance: - *

-     * class MyGLWrapper implements GLWrapper {
-     *     GL wrap(GL gl) {
-     *         return new MyGLImplementation(gl);
-     *     }
-     *     static class MyGLImplementation implements GL,GL10,GL11,... {
-     *         ...
-     *     }
-     * }
-     * 
- * @see #setGLWrapper(GLWrapper) - */ - public interface GLWrapper { - /** - * Wraps a gl interface in another gl interface. - * @param gl a GL interface that is to be wrapped. - * @return either the input argument or another GL object that wraps the input argument. - */ - GL wrap(GL gl); - } - - - - /** - * An interface for choosing an EGLConfig configuration from a list of - * potential configurations. - *

- * This interface must be implemented by clients wishing to call - * {@link GLSurfaceViewCupcake#setEGLConfigChooser(EGLConfigChooser)} - */ - public interface EGLConfigChooser { - /** - * Choose a configuration from the list. Implementors typically - * implement this method by calling - * {@link EGL10#eglChooseConfig} and iterating through the results. Please consult the - * EGL specification available from The Khronos Group to learn how to call eglChooseConfig. - * @param egl the EGL10 for the current display. - * @param display the current display. - * @return the chosen configuration. - */ - EGLConfig chooseConfig(EGL10 egl, EGLDisplay display); - } - - private static abstract class BaseConfigChooser - implements EGLConfigChooser { - public BaseConfigChooser(int[] configSpec) { - mConfigSpec = configSpec; - } - public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) { - int[] num_config = new int[1]; - egl.eglChooseConfig(display, mConfigSpec, null, 0, num_config); - - int numConfigs = num_config[0]; - - if (numConfigs <= 0) { - throw new IllegalArgumentException( - "No configs match configSpec"); - } - - EGLConfig[] configs = new EGLConfig[numConfigs]; - egl.eglChooseConfig(display, mConfigSpec, configs, numConfigs, - num_config); - EGLConfig config = chooseConfig(egl, display, configs); - if (config == null) { - throw new IllegalArgumentException("No config chosen"); - } - return config; - } - - abstract EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, - EGLConfig[] configs); - - protected int[] mConfigSpec; - } - - private static class ComponentSizeChooser extends BaseConfigChooser { - public ComponentSizeChooser(int redSize, int greenSize, int blueSize, - int alphaSize, int depthSize, int stencilSize) { - super(new int[] { - EGL10.EGL_RED_SIZE, redSize, - EGL10.EGL_GREEN_SIZE, greenSize, - EGL10.EGL_BLUE_SIZE, blueSize, - EGL10.EGL_ALPHA_SIZE, alphaSize, - EGL10.EGL_DEPTH_SIZE, depthSize, - EGL10.EGL_STENCIL_SIZE, stencilSize, - EGL10.EGL_NONE}); - mValue = new int[1]; - mRedSize = redSize; - mGreenSize = greenSize; - mBlueSize = blueSize; - mAlphaSize = alphaSize; - mDepthSize = depthSize; - mStencilSize = stencilSize; - } - - @Override - public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, - EGLConfig[] configs) { - EGLConfig closestConfig = null; - int closestDistance = 1000; - for(EGLConfig config : configs) { - int r = findConfigAttrib(egl, display, config, - EGL10.EGL_RED_SIZE, 0); - int g = findConfigAttrib(egl, display, config, - EGL10.EGL_GREEN_SIZE, 0); - int b = findConfigAttrib(egl, display, config, - EGL10.EGL_BLUE_SIZE, 0); - int a = findConfigAttrib(egl, display, config, - EGL10.EGL_ALPHA_SIZE, 0); - int d = findConfigAttrib(egl, display, config, - EGL10.EGL_DEPTH_SIZE, 0); - int s = findConfigAttrib(egl, display, config, - EGL10.EGL_STENCIL_SIZE, 0); - int distance = Math.abs(r - mRedSize) - + Math.abs(g - mGreenSize) - + Math.abs(b - mBlueSize) + Math.abs(a - mAlphaSize) - + Math.abs(d - mDepthSize) + Math.abs(s - mStencilSize); - if (distance < closestDistance) { - closestDistance = distance; - closestConfig = config; - } - } - return closestConfig; - } - - private int findConfigAttrib(EGL10 egl, EGLDisplay display, - EGLConfig config, int attribute, int defaultValue) { - - if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) { - return mValue[0]; - } - return defaultValue; - } - - private int[] mValue; - // Subclasses can adjust these values: - protected int mRedSize; - protected int mGreenSize; - protected int mBlueSize; - protected int mAlphaSize; - protected int mDepthSize; - protected int mStencilSize; - } - - /** - * This class will choose a supported surface as close to - * RGB565 as possible, with or without a depth buffer. - * - */ - private static class SimpleEGLConfigChooser extends ComponentSizeChooser { - public SimpleEGLConfigChooser(boolean withDepthBuffer) { - super(4, 4, 4, 0, withDepthBuffer ? 16 : 0, 0); - // Adjust target values. This way we'll accept a 4444 or - // 555 buffer if there's no 565 buffer available. - mRedSize = 5; - mGreenSize = 6; - mBlueSize = 5; - } - } - - /** - * An EGL helper class. - */ - - private class EglHelper { - public EglHelper() { - - } - - /** - * Initialize EGL for a given configuration spec. - * @param configSpec - */ - public void start(){ - /* - * Get an EGL instance - */ - mEgl = (EGL10) EGLContext.getEGL(); - - /* - * Get to the default display. - */ - mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); - - /* - * We can now initialize EGL for that display - */ - int[] version = new int[2]; - mEgl.eglInitialize(mEglDisplay, version); - mEglConfig = mEGLConfigChooser.chooseConfig(mEgl, mEglDisplay); - - /* - * Create an OpenGL ES context. This must be done only once, an - * OpenGL context is a somewhat heavy object. - */ - mEglContext = mEgl.eglCreateContext(mEglDisplay, mEglConfig, - EGL10.EGL_NO_CONTEXT, null); - - mEglSurface = null; - } - - /* - * React to the creation of a new surface by creating and returning an - * OpenGL interface that renders to that surface. - */ - public GL createSurface(SurfaceHolder holder) { - /* - * The window size has changed, so we need to create a new - * surface. - */ - if (mEglSurface != null) { - - /* - * Unbind and destroy the old EGL surface, if - * there is one. - */ - mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, - EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); - mEgl.eglDestroySurface(mEglDisplay, mEglSurface); - } - - /* - * Create an EGL surface we can render into. - */ - mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay, - mEglConfig, holder, null); - - /* - * Before we can issue GL commands, we need to make sure - * the context is current and bound to a surface. - */ - mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, - mEglContext); - - - GL gl = mEglContext.getGL(); - if (mGLWrapper != null) { - gl = mGLWrapper.wrap(gl); - } - - /* Debugging disabled */ - /* - if ((mDebugFlags & (DEBUG_CHECK_GL_ERROR | DEBUG_LOG_GL_CALLS))!= 0) { - int configFlags = 0; - Writer log = null; - if ((mDebugFlags & DEBUG_CHECK_GL_ERROR) != 0) { - configFlags |= GLDebugHelper.CONFIG_CHECK_GL_ERROR; - } - if ((mDebugFlags & DEBUG_LOG_GL_CALLS) != 0) { - log = new LogWriter(); - } - gl = GLDebugHelper.wrap(gl, configFlags, log); - } - */ - return gl; - } - - /** - * Display the current render surface. - * @return false if the context has been lost. - */ - public boolean swap() { - mEgl.eglSwapBuffers(mEglDisplay, mEglSurface); - - /* - * Always check for EGL_CONTEXT_LOST, which means the context - * and all associated data were lost (For instance because - * the device went to sleep). We need to sleep until we - * get a new surface. - */ - return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST; - } - - public void finish() { - if (mEglSurface != null) { - mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, - EGL10.EGL_NO_SURFACE, - EGL10.EGL_NO_CONTEXT); - mEgl.eglDestroySurface(mEglDisplay, mEglSurface); - mEglSurface = null; - } - if (mEglContext != null) { - mEgl.eglDestroyContext(mEglDisplay, mEglContext); - mEglContext = null; - } - if (mEglDisplay != null) { - mEgl.eglTerminate(mEglDisplay); - mEglDisplay = null; - } - } - - EGL10 mEgl; - EGLDisplay mEglDisplay; - EGLSurface mEglSurface; - EGLConfig mEglConfig; - EGLContext mEglContext; - } - - /** - * A generic GL Thread. Takes care of initializing EGL and GL. Delegates - * to a Renderer instance to do the actual drawing. Can be configured to - * render continuously or on request. - * - */ - class GLThread extends Thread { - GLThread(Renderer renderer) { - super(); - mDone = false; - mWidth = 0; - mHeight = 0; - mRequestRender = true; - mRenderMode = RENDERMODE_CONTINUOUSLY; - mRenderer = renderer; - mSizeChanged = true; - setName("GLThread"); - } - - @Override - public void run() { - /* - * When the android framework launches a second instance of - * an activity, the new instance's onCreate() method may be - * called before the first instance returns from onDestroy(). - * - * This semaphore ensures that only one instance at a time - * accesses EGL. - */ - try { - try { - sEglSemaphore.acquire(); - } catch (InterruptedException e) { - return; - } - guardedRun(); - } catch (InterruptedException e) { - // fall thru and exit normally - } finally { - sEglSemaphore.release(); - } - } - - private void guardedRun() throws InterruptedException { - mEglHelper = new EglHelper(); - mEglHelper.start(); - - GL10 gl = null; - boolean tellRendererSurfaceCreated = true; - boolean tellRendererSurfaceChanged = true; - - /* - * This is our main activity thread's loop, we go until - * asked to quit. - */ - while (!mDone) { - - /* - * Update the asynchronous state (window size) - */ - int w, h; - boolean changed; - boolean needStart = false; - synchronized (this) { - Runnable r; - while ((r = getEvent()) != null) { - r.run(); - } - if (mPaused) { - mEglHelper.finish(); - needStart = true; - } - while (needToWait()) { - wait(); - } - if (mDone) { - break; - } - changed = mSizeChanged; - w = mWidth; - h = mHeight; - mSizeChanged = false; - mRequestRender = false; - } - if (needStart) { - mEglHelper.start(); - tellRendererSurfaceCreated = true; - changed = true; - } - if (changed) { - gl = (GL10) mEglHelper.createSurface(getHolder()); - tellRendererSurfaceChanged = true; - } - if (tellRendererSurfaceCreated) { - mRenderer.onSurfaceCreated(gl, mEglHelper.mEglConfig); - tellRendererSurfaceCreated = false; - } - if (tellRendererSurfaceChanged) { - mRenderer.onSurfaceChanged(gl, w, h); - tellRendererSurfaceChanged = false; - } - if ((w > 0) && (h > 0)) { - /* draw a frame here */ - mRenderer.onDrawFrame(gl); - - /* - * Once we're done with GL, we need to call swapBuffers() - * to instruct the system to display the rendered frame - */ - mEglHelper.swap(); - } - } - - /* - * clean-up everything... - */ - mEglHelper.finish(); - } - - private boolean needToWait() { - if (mDone) { - return false; - } - - if (mPaused || (! mHasSurface)) { - return true; - } - - if ((mWidth > 0) && (mHeight > 0) && (mRequestRender || (mRenderMode == RENDERMODE_CONTINUOUSLY))) { - return false; - } - - return true; - } - - public void setRenderMode(int renderMode) { - if ( !((RENDERMODE_WHEN_DIRTY <= renderMode) && (renderMode <= RENDERMODE_CONTINUOUSLY)) ) { - throw new IllegalArgumentException("renderMode"); - } - synchronized(this) { - mRenderMode = renderMode; - if (renderMode == RENDERMODE_CONTINUOUSLY) { - notify(); - } - } - } - - public int getRenderMode() { - synchronized(this) { - return mRenderMode; - } - } - - public void requestRender() { - synchronized(this) { - mRequestRender = true; - notify(); - } - } - - public void surfaceCreated() { - synchronized(this) { - mHasSurface = true; - notify(); - } - } - - public void surfaceDestroyed() { - synchronized(this) { - mHasSurface = false; - notify(); - } - } - - public void onPause() { - synchronized (this) { - mPaused = true; - } - } - - public void onResume() { - synchronized (this) { - mPaused = false; - notify(); - } - } - - public void onWindowResize(int w, int h) { - synchronized (this) { - mWidth = w; - mHeight = h; - mSizeChanged = true; - notify(); - } - } - - public void requestExitAndWait() { - // don't call this from GLThread thread or it is a guaranteed - // deadlock! - synchronized(this) { - mDone = true; - notify(); - } - try { - join(); - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - } - } - - /** - * Queue an "event" to be run on the GL rendering thread. - * @param r the runnable to be run on the GL rendering thread. - */ - public void queueEvent(Runnable r) { - synchronized(this) { - mEventQueue.add(r); - } - } - - private Runnable getEvent() { - synchronized(this) { - if (mEventQueue.size() > 0) { - return mEventQueue.remove(0); - } - - } - return null; - } - - private boolean mDone; - private boolean mPaused; - private boolean mHasSurface; - private int mWidth; - private int mHeight; - private int mRenderMode; - private boolean mRequestRender; - private Renderer mRenderer; - private ArrayList mEventQueue = new ArrayList(); - private EglHelper mEglHelper; - private boolean mSizeChanged; - } - - static class LogWriter extends Writer { - - @Override public void close() { - flushBuilder(); - } - - @Override public void flush() { - flushBuilder(); - } - - @Override public void write(char[] buf, int offset, int count) { - for(int i = 0; i < count; i++) { - char c = buf[offset + i]; - if ( c == '\n') { - flushBuilder(); - } - else { - mBuilder.append(c); - } - } - } - - private void flushBuilder() { - if (mBuilder.length() > 0) { - Log.v("GLSurfaceView", mBuilder.toString()); - mBuilder.delete(0, mBuilder.length()); - } - } - - private StringBuilder mBuilder = new StringBuilder(); - } - - private static final Semaphore sEglSemaphore = new Semaphore(1); - - private GLThread mGLThread; - private EGLConfigChooser mEGLConfigChooser; - private GLWrapper mGLWrapper; - private int mDebugFlags; - private int mRenderMode; - private Renderer mRenderer; - private int mSurfaceWidth; - private int mSurfaceHeight; - private boolean mHasSurface; + /** + * The renderer only renders when the surface is created, or when {@link #requestRender} is called. + * + * @see #getRenderMode() + * @see #setRenderMode(int) + */ + public final static int RENDERMODE_WHEN_DIRTY = 0; + /** + * The renderer is called continuously to re-render the scene. + * + * @see #getRenderMode() + * @see #setRenderMode(int) + * @see #requestRender() + */ + public final static int RENDERMODE_CONTINUOUSLY = 1; + + /** + * Check glError() after every GL call and throw an exception if glError indicates that an error has occurred. This can be used + * to help track down which OpenGL ES call is causing an error. + * + * @see #getDebugFlags + * @see #setDebugFlags + */ + public final static int DEBUG_CHECK_GL_ERROR = 1; + + /** + * Log GL calls to the system log at "verbose" level with tag "GLSurfaceView". + * + * @see #getDebugFlags + * @see #setDebugFlags + */ + public final static int DEBUG_LOG_GL_CALLS = 2; + + /** + * Standard View constructor. In order to render something, you must call {@link #setRenderer} to register a renderer. + */ + public GLSurfaceViewCupcake (Context context) { + super(context); + init(); + } + + /** + * Standard View constructor. In order to render something, you must call {@link #setRenderer} to register a renderer. + */ + public GLSurfaceViewCupcake (Context context, AttributeSet attrs) { + super(context, attrs); + init(); + } + + private void init () { + // Install a SurfaceHolder.Callback so we get notified when the + // underlying surface is created and destroyed + SurfaceHolder holder = getHolder(); + holder.addCallback(this); + holder.setType(SurfaceHolder.SURFACE_TYPE_GPU); + mRenderMode = RENDERMODE_CONTINUOUSLY; + } + + /** + * Set the glWrapper. If the glWrapper is not null, its {@link GLWrapper#wrap(GL)} method is called whenever a surface is + * created. A GLWrapper can be used to wrap the GL object that's passed to the renderer. Wrapping a GL object enables examining + * and modifying the behavior of the GL calls made by the renderer. + *

+ * Wrapping is typically used for debugging purposes. + *

+ * The default value is null. + * @param glWrapper the new GLWrapper + */ + public void setGLWrapper (GLWrapper glWrapper) { + mGLWrapper = glWrapper; + } + + /** + * Set the debug flags to a new value. The value is constructed by OR-together zero or more of the DEBUG_CHECK_* constants. The + * debug flags take effect whenever a surface is created. The default value is zero. + * @param debugFlags the new debug flags + * @see #DEBUG_CHECK_GL_ERROR + * @see #DEBUG_LOG_GL_CALLS + */ + public void setDebugFlags (int debugFlags) { + mDebugFlags = debugFlags; + } + + /** + * Get the current value of the debug flags. + * @return the current value of the debug flags. + */ + public int getDebugFlags () { + return mDebugFlags; + } + + /** + * Set the renderer associated with this view. Also starts the thread that will call the renderer, which in turn causes the + * rendering to start. + *

+ * This method should be called once and only once in the life-cycle of a GLSurfaceView. + *

+ * The following GLSurfaceView methods can only be called before setRenderer is called: + *

    + *
  • {@link #setEGLConfigChooser(boolean)} + *
  • {@link #setEGLConfigChooser(EGLConfigChooser)} + *
  • {@link #setEGLConfigChooser(int, int, int, int, int, int)} + *
+ *

+ * The following GLSurfaceView methods can only be called after setRenderer is called: + *

    + *
  • {@link #getRenderMode()} + *
  • {@link #onPause()} + *
  • {@link #onResume()} + *
  • {@link #queueEvent(Runnable)} + *
  • {@link #requestRender()} + *
  • {@link #setRenderMode(int)} + *
+ * + * @param renderer the renderer to use to perform OpenGL drawing. + */ + public void setRenderer (Renderer renderer) { + if (mRenderer != null) { + throw new IllegalStateException("setRenderer has already been called for this instance."); + } + + mRenderer = renderer; + } + + /** + * Install a custom EGLConfigChooser. + *

+ * If this method is called, it must be called before {@link #setRenderer(Renderer)} is called. + *

+ * If no setEGLConfigChooser method is called, then by default the view will choose a config as close to 16-bit RGB as + * possible, with a depth buffer as close to 16 bits as possible. + * @param configChooser + */ + public void setEGLConfigChooser (EGLConfigChooser configChooser) { + if (mRenderer != null) { + throw new IllegalStateException("setRenderer has already been called for this instance."); + } + mEGLConfigChooser = configChooser; + } + + /** + * Install a config chooser which will choose a config as close to 16-bit RGB as possible, with or without an optional depth + * buffer as close to 16-bits as possible. + *

+ * If this method is called, it must be called before {@link #setRenderer(Renderer)} is called. + *

+ * If no setEGLConfigChooser method is called, then by default the view will choose a config as close to 16-bit RGB as + * possible, with a depth buffer as close to 16 bits as possible. + * + * @param needDepth + */ + public void setEGLConfigChooser (boolean needDepth) { + setEGLConfigChooser(new SimpleEGLConfigChooser(needDepth)); + } + + /** + * Install a config chooser which will choose a config with at least the specified component sizes, and as close to the + * specified component sizes as possible. + *

+ * If this method is called, it must be called before {@link #setRenderer(Renderer)} is called. + *

+ * If no setEGLConfigChooser method is called, then by default the view will choose a config as close to 16-bit RGB as + * possible, with a depth buffer as close to 16 bits as possible. + * + */ + public void setEGLConfigChooser (int redSize, int greenSize, int blueSize, int alphaSize, int depthSize, int stencilSize) { + setEGLConfigChooser(new ComponentSizeChooser(redSize, greenSize, blueSize, alphaSize, depthSize, stencilSize)); + } + + /** + * Set the rendering mode. When renderMode is RENDERMODE_CONTINUOUSLY, the renderer is called repeatedly to re-render the + * scene. When renderMode is RENDERMODE_WHEN_DIRTY, the renderer only rendered when the surface is created, or when + * {@link #requestRender} is called. Defaults to RENDERMODE_CONTINUOUSLY. + *

+ * Using RENDERMODE_WHEN_DIRTY can improve battery life and overall system performance by allowing the GPU and CPU to idle when + * the view does not need to be updated. + *

+ * This method can only be called after {@link #setRenderer(Renderer)} + * + * @param renderMode one of the RENDERMODE_X constants + * @see #RENDERMODE_CONTINUOUSLY + * @see #RENDERMODE_WHEN_DIRTY + */ + public void setRenderMode (int renderMode) { + mRenderMode = renderMode; + if (mGLThread != null) { + mGLThread.setRenderMode(renderMode); + } + } + + /** + * Get the current rendering mode. May be called from any thread. Must not be called before a renderer has been set. + * @return the current rendering mode. + * @see #RENDERMODE_CONTINUOUSLY + * @see #RENDERMODE_WHEN_DIRTY + */ + public int getRenderMode () { + return mRenderMode; + } + + /** + * Request that the renderer render a frame. This method is typically used when the render mode has been set to + * {@link #RENDERMODE_WHEN_DIRTY}, so that frames are only rendered on demand. May be called from any thread. Must be called + * after onResume() and before onPause(). + */ + public void requestRender () { + mGLThread.requestRender(); + } + + /** + * This method is part of the SurfaceHolder.Callback interface, and is not normally called or subclassed by clients of + * GLSurfaceView. + */ + public void surfaceCreated (SurfaceHolder holder) { + if (mGLThread != null) { + mGLThread.surfaceCreated(); + } + mHasSurface = true; + } + + /** + * This method is part of the SurfaceHolder.Callback interface, and is not normally called or subclassed by clients of + * GLSurfaceView. + */ + public void surfaceDestroyed (SurfaceHolder holder) { + // Surface will be destroyed when we return + if (mGLThread != null) { + mGLThread.surfaceDestroyed(); + } + mHasSurface = false; + } + + /** + * This method is part of the SurfaceHolder.Callback interface, and is not normally called or subclassed by clients of + * GLSurfaceView. + */ + public void surfaceChanged (SurfaceHolder holder, int format, int w, int h) { + if (mGLThread != null) { + mGLThread.onWindowResize(w, h); + } + mSurfaceWidth = w; + mSurfaceHeight = h; + } + + /** + * Inform the view that the activity is paused. The owner of this view must call this method when the activity is paused. + * Calling this method will pause the rendering thread. Must not be called before a renderer has been set. + */ + public void onPause () { + mGLThread.onPause(); + mGLThread.requestExitAndWait(); + mGLThread = null; + } + + /** + * Inform the view that the activity is resumed. The owner of this view must call this method when the activity is resumed. + * Calling this method will recreate the OpenGL display and resume the rendering thread. Must not be called before a renderer + * has been set. + */ + public void onResume () { + if (mEGLConfigChooser == null) { + mEGLConfigChooser = new SimpleEGLConfigChooser(true); + } + mGLThread = new GLThread(mRenderer); + mGLThread.start(); + mGLThread.setRenderMode(mRenderMode); + if (mHasSurface) { + mGLThread.surfaceCreated(); + } + if (mSurfaceWidth > 0 && mSurfaceHeight > 0) { + mGLThread.onWindowResize(mSurfaceWidth, mSurfaceHeight); + } + mGLThread.onResume(); + } + + /** + * Queue a runnable to be run on the GL rendering thread. This can be used to communicate with the Renderer on the rendering + * thread. Must be called after onResume() and before onPause(). + * @param r the runnable to be run on the GL rendering thread. + */ + public void queueEvent (Runnable r) { + if (mGLThread != null) { + mGLThread.queueEvent(r); + } + } + + // ---------------------------------------------------------------------- + + /** + * An interface used to wrap a GL interface. + *

+ * Typically used for implementing debugging and tracing on top of the default GL interface. You would typically use this by + * creating your own class that implemented all the GL methods by delegating to another GL instance. Then you could add your + * own behavior before or after calling the delegate. All the GLWrapper would do was instantiate and return the wrapper GL + * instance: + * + *

+	 * class MyGLWrapper implements GLWrapper {
+	 *     GL wrap(GL gl) {
+	 *         return new MyGLImplementation(gl);
+	 *     }
+	 *     static class MyGLImplementation implements GL,GL10,GL11,... {
+	 *         ...
+	 *     }
+	 * }
+	 * 
+ * @see #setGLWrapper(GLWrapper) + */ + public interface GLWrapper { + /** + * Wraps a gl interface in another gl interface. + * @param gl a GL interface that is to be wrapped. + * @return either the input argument or another GL object that wraps the input argument. + */ + GL wrap (GL gl); + } + + /** + * An interface for choosing an EGLConfig configuration from a list of potential configurations. + *

+ * This interface must be implemented by clients wishing to call + * {@link GLSurfaceViewCupcake#setEGLConfigChooser(EGLConfigChooser)} + */ + public interface EGLConfigChooser { + /** + * Choose a configuration from the list. Implementors typically implement this method by calling + * {@link EGL10#eglChooseConfig} and iterating through the results. Please consult the EGL specification available from The + * Khronos Group to learn how to call eglChooseConfig. + * @param egl the EGL10 for the current display. + * @param display the current display. + * @return the chosen configuration. + */ + EGLConfig chooseConfig (EGL10 egl, EGLDisplay display); + } + + private static abstract class BaseConfigChooser implements EGLConfigChooser { + public BaseConfigChooser (int[] configSpec) { + mConfigSpec = configSpec; + } + + public EGLConfig chooseConfig (EGL10 egl, EGLDisplay display) { + int[] num_config = new int[1]; + egl.eglChooseConfig(display, mConfigSpec, null, 0, num_config); + + int numConfigs = num_config[0]; + + if (numConfigs <= 0) { + throw new IllegalArgumentException("No configs match configSpec"); + } + + EGLConfig[] configs = new EGLConfig[numConfigs]; + egl.eglChooseConfig(display, mConfigSpec, configs, numConfigs, num_config); + EGLConfig config = chooseConfig(egl, display, configs); + if (config == null) { + throw new IllegalArgumentException("No config chosen"); + } + return config; + } + + abstract EGLConfig chooseConfig (EGL10 egl, EGLDisplay display, EGLConfig[] configs); + + protected int[] mConfigSpec; + } + + private static class ComponentSizeChooser extends BaseConfigChooser { + public ComponentSizeChooser (int redSize, int greenSize, int blueSize, int alphaSize, int depthSize, int stencilSize) { + super( + new int[] {EGL10.EGL_RED_SIZE, redSize, EGL10.EGL_GREEN_SIZE, greenSize, EGL10.EGL_BLUE_SIZE, blueSize, + EGL10.EGL_ALPHA_SIZE, alphaSize, EGL10.EGL_DEPTH_SIZE, depthSize, EGL10.EGL_STENCIL_SIZE, stencilSize, + EGL10.EGL_NONE}); + mValue = new int[1]; + mRedSize = redSize; + mGreenSize = greenSize; + mBlueSize = blueSize; + mAlphaSize = alphaSize; + mDepthSize = depthSize; + mStencilSize = stencilSize; + } + + @Override public EGLConfig chooseConfig (EGL10 egl, EGLDisplay display, EGLConfig[] configs) { + EGLConfig closestConfig = null; + int closestDistance = 1000; + for (EGLConfig config : configs) { + int r = findConfigAttrib(egl, display, config, EGL10.EGL_RED_SIZE, 0); + int g = findConfigAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0); + int b = findConfigAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0); + int a = findConfigAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0); + int d = findConfigAttrib(egl, display, config, EGL10.EGL_DEPTH_SIZE, 0); + int s = findConfigAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0); + int distance = Math.abs(r - mRedSize) + Math.abs(g - mGreenSize) + Math.abs(b - mBlueSize) + Math.abs(a - mAlphaSize) + + Math.abs(d - mDepthSize) + Math.abs(s - mStencilSize); + if (distance < closestDistance) { + closestDistance = distance; + closestConfig = config; + } + } + return closestConfig; + } + + private int findConfigAttrib (EGL10 egl, EGLDisplay display, EGLConfig config, int attribute, int defaultValue) { + + if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) { + return mValue[0]; + } + return defaultValue; + } + + private int[] mValue; + // Subclasses can adjust these values: + protected int mRedSize; + protected int mGreenSize; + protected int mBlueSize; + protected int mAlphaSize; + protected int mDepthSize; + protected int mStencilSize; + } + + /** + * This class will choose a supported surface as close to RGB565 as possible, with or without a depth buffer. + * + */ + private static class SimpleEGLConfigChooser extends ComponentSizeChooser { + public SimpleEGLConfigChooser (boolean withDepthBuffer) { + super(4, 4, 4, 0, withDepthBuffer ? 16 : 0, 0); + // Adjust target values. This way we'll accept a 4444 or + // 555 buffer if there's no 565 buffer available. + mRedSize = 5; + mGreenSize = 6; + mBlueSize = 5; + } + } + + /** + * An EGL helper class. + */ + + private class EglHelper { + public EglHelper () { + + } + + /** + * Initialize EGL for a given configuration spec. + * @param configSpec + */ + public void start () { + /* + * Get an EGL instance + */ + mEgl = (EGL10)EGLContext.getEGL(); + + /* + * Get to the default display. + */ + mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); + + /* + * We can now initialize EGL for that display + */ + int[] version = new int[2]; + mEgl.eglInitialize(mEglDisplay, version); + mEglConfig = mEGLConfigChooser.chooseConfig(mEgl, mEglDisplay); + + /* + * Create an OpenGL ES context. This must be done only once, an OpenGL context is a somewhat heavy object. + */ + mEglContext = mEgl.eglCreateContext(mEglDisplay, mEglConfig, EGL10.EGL_NO_CONTEXT, null); + + mEglSurface = null; + } + + /* + * React to the creation of a new surface by creating and returning an OpenGL interface that renders to that surface. + */ + public GL createSurface (SurfaceHolder holder) { + /* + * The window size has changed, so we need to create a new surface. + */ + if (mEglSurface != null) { + + /* + * Unbind and destroy the old EGL surface, if there is one. + */ + mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); + mEgl.eglDestroySurface(mEglDisplay, mEglSurface); + } + + /* + * Create an EGL surface we can render into. + */ + mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay, mEglConfig, holder, null); + + /* + * Before we can issue GL commands, we need to make sure the context is current and bound to a surface. + */ + mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext); + + GL gl = mEglContext.getGL(); + if (mGLWrapper != null) { + gl = mGLWrapper.wrap(gl); + } + + /* Debugging disabled */ + /* + * if ((mDebugFlags & (DEBUG_CHECK_GL_ERROR | DEBUG_LOG_GL_CALLS))!= 0) { int configFlags = 0; Writer log = null; if + * ((mDebugFlags & DEBUG_CHECK_GL_ERROR) != 0) { configFlags |= GLDebugHelper.CONFIG_CHECK_GL_ERROR; } if ((mDebugFlags & + * DEBUG_LOG_GL_CALLS) != 0) { log = new LogWriter(); } gl = GLDebugHelper.wrap(gl, configFlags, log); } + */ + return gl; + } + + /** + * Display the current render surface. + * @return false if the context has been lost. + */ + public boolean swap () { + mEgl.eglSwapBuffers(mEglDisplay, mEglSurface); + + /* + * Always check for EGL_CONTEXT_LOST, which means the context and all associated data were lost (For instance because the + * device went to sleep). We need to sleep until we get a new surface. + */ + return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST; + } + + public void finish () { + if (mEglSurface != null) { + mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); + mEgl.eglDestroySurface(mEglDisplay, mEglSurface); + mEglSurface = null; + } + if (mEglContext != null) { + mEgl.eglDestroyContext(mEglDisplay, mEglContext); + mEglContext = null; + } + if (mEglDisplay != null) { + mEgl.eglTerminate(mEglDisplay); + mEglDisplay = null; + } + } + + EGL10 mEgl; + EGLDisplay mEglDisplay; + EGLSurface mEglSurface; + EGLConfig mEglConfig; + EGLContext mEglContext; + } + + /** + * A generic GL Thread. Takes care of initializing EGL and GL. Delegates to a Renderer instance to do the actual drawing. Can + * be configured to render continuously or on request. + * + */ + class GLThread extends Thread { + GLThread (Renderer renderer) { + super(); + mDone = false; + mWidth = 0; + mHeight = 0; + mRequestRender = true; + mRenderMode = RENDERMODE_CONTINUOUSLY; + mRenderer = renderer; + mSizeChanged = true; + setName("GLThread"); + } + + @Override public void run () { + /* + * When the android framework launches a second instance of an activity, the new instance's onCreate() method may be + * called before the first instance returns from onDestroy(). + * + * This semaphore ensures that only one instance at a time accesses EGL. + */ + try { + try { + sEglSemaphore.acquire(); + } catch (InterruptedException e) { + return; + } + guardedRun(); + } catch (InterruptedException e) { + // fall thru and exit normally + } finally { + sEglSemaphore.release(); + } + } + + private void guardedRun () throws InterruptedException { + mEglHelper = new EglHelper(); + mEglHelper.start(); + + GL10 gl = null; + boolean tellRendererSurfaceCreated = true; + boolean tellRendererSurfaceChanged = true; + + /* + * This is our main activity thread's loop, we go until asked to quit. + */ + while (!mDone) { + + /* + * Update the asynchronous state (window size) + */ + int w, h; + boolean changed; + boolean needStart = false; + synchronized (this) { + Runnable r; + while ((r = getEvent()) != null) { + r.run(); + } + if (mPaused) { + mEglHelper.finish(); + needStart = true; + } + while (needToWait()) { + wait(); + } + if (mDone) { + break; + } + changed = mSizeChanged; + w = mWidth; + h = mHeight; + mSizeChanged = false; + mRequestRender = false; + } + if (needStart) { + mEglHelper.start(); + tellRendererSurfaceCreated = true; + changed = true; + } + if (changed) { + gl = (GL10)mEglHelper.createSurface(getHolder()); + tellRendererSurfaceChanged = true; + } + if (tellRendererSurfaceCreated) { + mRenderer.onSurfaceCreated(gl, mEglHelper.mEglConfig); + tellRendererSurfaceCreated = false; + } + if (tellRendererSurfaceChanged) { + mRenderer.onSurfaceChanged(gl, w, h); + tellRendererSurfaceChanged = false; + } + if ((w > 0) && (h > 0)) { + /* draw a frame here */ + mRenderer.onDrawFrame(gl); + + /* + * Once we're done with GL, we need to call swapBuffers() to instruct the system to display the rendered frame + */ + mEglHelper.swap(); + } + } + + /* + * clean-up everything... + */ + mEglHelper.finish(); + } + + private boolean needToWait () { + if (mDone) { + return false; + } + + if (mPaused || (!mHasSurface)) { + return true; + } + + if ((mWidth > 0) && (mHeight > 0) && (mRequestRender || (mRenderMode == RENDERMODE_CONTINUOUSLY))) { + return false; + } + + return true; + } + + public void setRenderMode (int renderMode) { + if (!((RENDERMODE_WHEN_DIRTY <= renderMode) && (renderMode <= RENDERMODE_CONTINUOUSLY))) { + throw new IllegalArgumentException("renderMode"); + } + synchronized (this) { + mRenderMode = renderMode; + if (renderMode == RENDERMODE_CONTINUOUSLY) { + notify(); + } + } + } + + public int getRenderMode () { + synchronized (this) { + return mRenderMode; + } + } + + public void requestRender () { + synchronized (this) { + mRequestRender = true; + notify(); + } + } + + public void surfaceCreated () { + synchronized (this) { + mHasSurface = true; + notify(); + } + } + + public void surfaceDestroyed () { + synchronized (this) { + mHasSurface = false; + notify(); + } + } + + public void onPause () { + synchronized (this) { + mPaused = true; + } + } + + public void onResume () { + synchronized (this) { + mPaused = false; + notify(); + } + } + + public void onWindowResize (int w, int h) { + synchronized (this) { + mWidth = w; + mHeight = h; + mSizeChanged = true; + notify(); + } + } + + public void requestExitAndWait () { + // don't call this from GLThread thread or it is a guaranteed + // deadlock! + synchronized (this) { + mDone = true; + notify(); + } + try { + join(); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + } + + /** + * Queue an "event" to be run on the GL rendering thread. + * @param r the runnable to be run on the GL rendering thread. + */ + public void queueEvent (Runnable r) { + synchronized (this) { + mEventQueue.add(r); + } + } + + private Runnable getEvent () { + synchronized (this) { + if (mEventQueue.size() > 0) { + return mEventQueue.remove(0); + } + + } + return null; + } + + private boolean mDone; + private boolean mPaused; + private boolean mHasSurface; + private int mWidth; + private int mHeight; + private int mRenderMode; + private boolean mRequestRender; + private Renderer mRenderer; + private ArrayList mEventQueue = new ArrayList(); + private EglHelper mEglHelper; + private boolean mSizeChanged; + } + + static class LogWriter extends Writer { + + @Override public void close () { + flushBuilder(); + } + + @Override public void flush () { + flushBuilder(); + } + + @Override public void write (char[] buf, int offset, int count) { + for (int i = 0; i < count; i++) { + char c = buf[offset + i]; + if (c == '\n') { + flushBuilder(); + } else { + mBuilder.append(c); + } + } + } + + private void flushBuilder () { + if (mBuilder.length() > 0) { + Log.v("GLSurfaceView", mBuilder.toString()); + mBuilder.delete(0, mBuilder.length()); + } + } + + private StringBuilder mBuilder = new StringBuilder(); + } + + private static final Semaphore sEglSemaphore = new Semaphore(1); + + private GLThread mGLThread; + private EGLConfigChooser mEGLConfigChooser; + private GLWrapper mGLWrapper; + private int mDebugFlags; + private int mRenderMode; + private Renderer mRenderer; + private int mSurfaceWidth; + private int mSurfaceHeight; + private boolean mHasSurface; } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLWrapperBase.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLWrapperBase.java index 3c2be4f79..49c8a07a1 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLWrapperBase.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GLWrapperBase.java @@ -1,17 +1,14 @@ /* * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. */ package com.badlogic.gdx.backends.android.surfaceview; @@ -19,6 +16,7 @@ package com.badlogic.gdx.backends.android.surfaceview; import java.nio.Buffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; + import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL10Ext; @@ -27,469 +25,467 @@ import javax.microedition.khronos.opengles.GL11Ext; import javax.microedition.khronos.opengles.GL11ExtensionPack; /** - * The abstract base class for a GL wrapper. Provides - * some convenient instance variables and default implementations. + * The abstract base class for a GL wrapper. Provides some convenient instance variables and default implementations. */ -abstract class GLWrapperBase - implements GL, GL10, GL10Ext, GL11, GL11Ext { - public GLWrapperBase(GL gl) { - mgl = (GL10) gl; +abstract class GLWrapperBase implements GL, GL10, GL10Ext, GL11, GL11Ext { + public GLWrapperBase (GL gl) { + mgl = (GL10)gl; if (gl instanceof GL10Ext) { - mgl10Ext = (GL10Ext) gl; + mgl10Ext = (GL10Ext)gl; } if (gl instanceof GL11) { - mgl11 = (GL11) gl; + mgl11 = (GL11)gl; } if (gl instanceof GL11Ext) { - mgl11Ext = (GL11Ext) gl; + mgl11Ext = (GL11Ext)gl; } if (gl instanceof GL11ExtensionPack) { - mgl11ExtensionPack = (GL11ExtensionPack) gl; + mgl11ExtensionPack = (GL11ExtensionPack)gl; } } - + protected GL10 mgl; protected GL10Ext mgl10Ext; protected GL11 mgl11; protected GL11Ext mgl11Ext; protected GL11ExtensionPack mgl11ExtensionPack; - // Unsupported GL11 methods + // Unsupported GL11 methods - public void glGetPointerv(int pname, java.nio.Buffer[] params) { - throw new UnsupportedOperationException(); - } + public void glGetPointerv (int pname, java.nio.Buffer[] params) { + throw new UnsupportedOperationException(); + } - // VBO versions of *Pointer and *Elements methods - public void glColorPointer(int size, int type, int stride, int offset) { - throw new UnsupportedOperationException(); - } + // VBO versions of *Pointer and *Elements methods + public void glColorPointer (int size, int type, int stride, int offset) { + throw new UnsupportedOperationException(); + } - public void glNormalPointer(int type, int stride, int offset) { - throw new UnsupportedOperationException(); - } + public void glNormalPointer (int type, int stride, int offset) { + throw new UnsupportedOperationException(); + } - public void glTexCoordPointer(int size, int type, int stride, int offset) { - throw new UnsupportedOperationException(); - } + public void glTexCoordPointer (int size, int type, int stride, int offset) { + throw new UnsupportedOperationException(); + } - public void glVertexPointer(int size, int type, int stride, int offset) { - throw new UnsupportedOperationException(); - } + public void glVertexPointer (int size, int type, int stride, int offset) { + throw new UnsupportedOperationException(); + } - public void glDrawElements(int mode, int count, int type, int offset) { - throw new UnsupportedOperationException(); - } + public void glDrawElements (int mode, int count, int type, int offset) { + throw new UnsupportedOperationException(); + } - public void glBindBuffer(int target, int buffer) { - throw new UnsupportedOperationException(); - } + public void glBindBuffer (int target, int buffer) { + throw new UnsupportedOperationException(); + } - public void glBufferData(int target, int size, Buffer data, int usage) { - throw new UnsupportedOperationException(); - } + public void glBufferData (int target, int size, Buffer data, int usage) { + throw new UnsupportedOperationException(); + } - public void glBufferSubData(int target, int offset, int size, Buffer data) { - throw new UnsupportedOperationException(); - } + public void glBufferSubData (int target, int offset, int size, Buffer data) { + throw new UnsupportedOperationException(); + } - public void glColor4ub(byte red, byte green, byte blue, byte alpha) { - throw new UnsupportedOperationException(); - } + public void glColor4ub (byte red, byte green, byte blue, byte alpha) { + throw new UnsupportedOperationException(); + } - public void glDeleteBuffers(int n, int[] buffers, int offset) { - throw new UnsupportedOperationException(); - } + public void glDeleteBuffers (int n, int[] buffers, int offset) { + throw new UnsupportedOperationException(); + } - public void glDeleteBuffers(int n, IntBuffer buffers) { - throw new UnsupportedOperationException(); - } + public void glDeleteBuffers (int n, IntBuffer buffers) { + throw new UnsupportedOperationException(); + } - public void glGenBuffers(int n, int[] buffers, int offset) { - throw new UnsupportedOperationException(); - } + public void glGenBuffers (int n, int[] buffers, int offset) { + throw new UnsupportedOperationException(); + } - public void glGenBuffers(int n, IntBuffer buffers) { - throw new UnsupportedOperationException(); - } + public void glGenBuffers (int n, IntBuffer buffers) { + throw new UnsupportedOperationException(); + } - public void glGetBooleanv(int pname, boolean[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glGetBooleanv (int pname, boolean[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetBooleanv(int pname, IntBuffer params) { - throw new UnsupportedOperationException(); - } + public void glGetBooleanv (int pname, IntBuffer params) { + throw new UnsupportedOperationException(); + } - public void glGetBufferParameteriv(int target, int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glGetBufferParameteriv (int target, int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetBufferParameteriv(int target, int pname, IntBuffer params) { - throw new UnsupportedOperationException(); - } + public void glGetBufferParameteriv (int target, int pname, IntBuffer params) { + throw new UnsupportedOperationException(); + } - public void glGetClipPlanef(int pname, float[] eqn, int offset) { - throw new UnsupportedOperationException(); - } + public void glGetClipPlanef (int pname, float[] eqn, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetClipPlanef(int pname, FloatBuffer eqn) { - throw new UnsupportedOperationException(); - } + public void glGetClipPlanef (int pname, FloatBuffer eqn) { + throw new UnsupportedOperationException(); + } - public void glGetClipPlanex(int pname, int[] eqn, int offset) { - throw new UnsupportedOperationException(); - } + public void glGetClipPlanex (int pname, int[] eqn, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetClipPlanex(int pname, IntBuffer eqn) { - throw new UnsupportedOperationException(); - } + public void glGetClipPlanex (int pname, IntBuffer eqn) { + throw new UnsupportedOperationException(); + } - public void glGetFixedv(int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glGetFixedv (int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetFixedv(int pname, IntBuffer params) { - throw new UnsupportedOperationException(); - } + public void glGetFixedv (int pname, IntBuffer params) { + throw new UnsupportedOperationException(); + } - public void glGetFloatv(int pname, float[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glGetFloatv (int pname, float[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetFloatv(int pname, FloatBuffer params) { - throw new UnsupportedOperationException(); - } + public void glGetFloatv (int pname, FloatBuffer params) { + throw new UnsupportedOperationException(); + } - public void glGetLightfv(int light, int pname, float[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glGetLightfv (int light, int pname, float[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetLightfv(int light, int pname, FloatBuffer params) { - throw new UnsupportedOperationException(); - } + public void glGetLightfv (int light, int pname, FloatBuffer params) { + throw new UnsupportedOperationException(); + } - public void glGetLightxv(int light, int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glGetLightxv (int light, int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetLightxv(int light, int pname, IntBuffer params) { - throw new UnsupportedOperationException(); - } + public void glGetLightxv (int light, int pname, IntBuffer params) { + throw new UnsupportedOperationException(); + } - public void glGetMaterialfv(int face, int pname, float[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glGetMaterialfv (int face, int pname, float[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetMaterialfv(int face, int pname, FloatBuffer params) { - throw new UnsupportedOperationException(); - } + public void glGetMaterialfv (int face, int pname, FloatBuffer params) { + throw new UnsupportedOperationException(); + } - public void glGetMaterialxv(int face, int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glGetMaterialxv (int face, int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetMaterialxv(int face, int pname, IntBuffer params) { - throw new UnsupportedOperationException(); - } + public void glGetMaterialxv (int face, int pname, IntBuffer params) { + throw new UnsupportedOperationException(); + } - public void glGetTexEnviv(int env, int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glGetTexEnviv (int env, int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetTexEnviv(int env, int pname, IntBuffer params) { - throw new UnsupportedOperationException(); - } + public void glGetTexEnviv (int env, int pname, IntBuffer params) { + throw new UnsupportedOperationException(); + } - public void glGetTexEnvxv(int env, int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glGetTexEnvxv (int env, int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetTexEnvxv(int env, int pname, IntBuffer params) { - throw new UnsupportedOperationException(); - } + public void glGetTexEnvxv (int env, int pname, IntBuffer params) { + throw new UnsupportedOperationException(); + } - public void glGetTexParameterfv(int target, int pname, float[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glGetTexParameterfv (int target, int pname, float[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetTexParameterfv(int target, int pname, FloatBuffer params) { - throw new UnsupportedOperationException(); - } + public void glGetTexParameterfv (int target, int pname, FloatBuffer params) { + throw new UnsupportedOperationException(); + } - public void glGetTexParameteriv(int target, int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glGetTexParameteriv (int target, int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetTexParameteriv(int target, int pname, IntBuffer params) { - throw new UnsupportedOperationException(); - } + public void glGetTexParameteriv (int target, int pname, IntBuffer params) { + throw new UnsupportedOperationException(); + } - public void glGetTexParameterxv(int target, int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glGetTexParameterxv (int target, int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetTexParameterxv(int target, int pname, IntBuffer params) { - throw new UnsupportedOperationException(); - } + public void glGetTexParameterxv (int target, int pname, IntBuffer params) { + throw new UnsupportedOperationException(); + } - public boolean glIsBuffer(int buffer) { - throw new UnsupportedOperationException(); - } + public boolean glIsBuffer (int buffer) { + throw new UnsupportedOperationException(); + } - public boolean glIsEnabled(int cap) { - throw new UnsupportedOperationException(); - } + public boolean glIsEnabled (int cap) { + throw new UnsupportedOperationException(); + } - public boolean glIsTexture(int texture) { - throw new UnsupportedOperationException(); - } + public boolean glIsTexture (int texture) { + throw new UnsupportedOperationException(); + } - public void glPointParameterf(int pname, float param) { - throw new UnsupportedOperationException(); - } + public void glPointParameterf (int pname, float param) { + throw new UnsupportedOperationException(); + } - public void glPointParameterfv(int pname, float[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glPointParameterfv (int pname, float[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glPointParameterfv(int pname, FloatBuffer params) { - throw new UnsupportedOperationException(); - } + public void glPointParameterfv (int pname, FloatBuffer params) { + throw new UnsupportedOperationException(); + } - public void glPointParameterx(int pname, int param) { - throw new UnsupportedOperationException(); - } + public void glPointParameterx (int pname, int param) { + throw new UnsupportedOperationException(); + } - public void glPointParameterxv(int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glPointParameterxv (int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glPointParameterxv(int pname, IntBuffer params) { - throw new UnsupportedOperationException(); - } + public void glPointParameterxv (int pname, IntBuffer params) { + throw new UnsupportedOperationException(); + } - public void glPointSizePointerOES(int type, int stride, Buffer pointer) { - throw new UnsupportedOperationException(); - } + public void glPointSizePointerOES (int type, int stride, Buffer pointer) { + throw new UnsupportedOperationException(); + } - public void glTexEnvi(int target, int pname, int param) { - throw new UnsupportedOperationException(); - } + public void glTexEnvi (int target, int pname, int param) { + throw new UnsupportedOperationException(); + } - public void glTexEnviv(int target, int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glTexEnviv (int target, int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glTexEnviv(int target, int pname, IntBuffer params) { - throw new UnsupportedOperationException(); - } + public void glTexEnviv (int target, int pname, IntBuffer params) { + throw new UnsupportedOperationException(); + } - public void glTexParameterfv(int target, int pname, float[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glTexParameterfv (int target, int pname, float[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glTexParameterfv(int target, int pname, FloatBuffer params) { - throw new UnsupportedOperationException(); - } + public void glTexParameterfv (int target, int pname, FloatBuffer params) { + throw new UnsupportedOperationException(); + } - public void glTexParameteri(int target, int pname, int param) { - throw new UnsupportedOperationException(); - } + public void glTexParameteri (int target, int pname, int param) { + throw new UnsupportedOperationException(); + } - public void glTexParameterxv(int target, int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glTexParameterxv (int target, int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glTexParameterxv(int target, int pname, IntBuffer params) { - throw new UnsupportedOperationException(); - } + public void glTexParameterxv (int target, int pname, IntBuffer params) { + throw new UnsupportedOperationException(); + } - // Unsupported GL11Ext methods + // Unsupported GL11Ext methods - public void glCurrentPaletteMatrixOES(int matrixpaletteindex) { - throw new UnsupportedOperationException(); - } + public void glCurrentPaletteMatrixOES (int matrixpaletteindex) { + throw new UnsupportedOperationException(); + } - public void glLoadPaletteFromModelViewMatrixOES() { - throw new UnsupportedOperationException(); - } + public void glLoadPaletteFromModelViewMatrixOES () { + throw new UnsupportedOperationException(); + } - public void glMatrixIndexPointerOES(int size, int type, int stride, Buffer pointer) { - throw new UnsupportedOperationException(); - } + public void glMatrixIndexPointerOES (int size, int type, int stride, Buffer pointer) { + throw new UnsupportedOperationException(); + } - public void glMatrixIndexPointerOES(int size, int type, int stride, int offset) { - throw new UnsupportedOperationException(); - } + public void glMatrixIndexPointerOES (int size, int type, int stride, int offset) { + throw new UnsupportedOperationException(); + } - public void glWeightPointerOES(int size, int type, int stride, Buffer pointer) { - throw new UnsupportedOperationException(); - } + public void glWeightPointerOES (int size, int type, int stride, Buffer pointer) { + throw new UnsupportedOperationException(); + } - public void glWeightPointerOES(int size, int type, int stride, int offset) { - throw new UnsupportedOperationException(); - } + public void glWeightPointerOES (int size, int type, int stride, int offset) { + throw new UnsupportedOperationException(); + } - // Unsupported GL11ExtensionPack methods + // Unsupported GL11ExtensionPack methods - public void glBindFramebufferOES(int target, int framebuffer) { - throw new UnsupportedOperationException(); - } + public void glBindFramebufferOES (int target, int framebuffer) { + throw new UnsupportedOperationException(); + } - public void glBindRenderbufferOES(int target, int renderbuffer) { - throw new UnsupportedOperationException(); - } + public void glBindRenderbufferOES (int target, int renderbuffer) { + throw new UnsupportedOperationException(); + } - public void glBlendEquation(int mode) { - throw new UnsupportedOperationException(); - } + public void glBlendEquation (int mode) { + throw new UnsupportedOperationException(); + } - public void glBlendEquationSeparate(int modeRGB, int modeAlpha) { - throw new UnsupportedOperationException(); - } + public void glBlendEquationSeparate (int modeRGB, int modeAlpha) { + throw new UnsupportedOperationException(); + } - public void glBlendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) { - throw new UnsupportedOperationException(); - } + public void glBlendFuncSeparate (int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) { + throw new UnsupportedOperationException(); + } - int glCheckFramebufferStatusOES(int target) { - throw new UnsupportedOperationException(); - } + int glCheckFramebufferStatusOES (int target) { + throw new UnsupportedOperationException(); + } - public void glCompressedTexImage2D(int target, int level, int internalformat, int width, int height, int border, int imageSize) { - throw new UnsupportedOperationException(); - } + public void glCompressedTexImage2D (int target, int level, int internalformat, int width, int height, int border, int imageSize) { + throw new UnsupportedOperationException(); + } - public void glDeleteFramebuffersOES(int n, int[] framebuffers, int offset) { - throw new UnsupportedOperationException(); - } + public void glDeleteFramebuffersOES (int n, int[] framebuffers, int offset) { + throw new UnsupportedOperationException(); + } - public void glDeleteFramebuffersOES(int n, java.nio.IntBuffer framebuffers) { - throw new UnsupportedOperationException(); - } + public void glDeleteFramebuffersOES (int n, java.nio.IntBuffer framebuffers) { + throw new UnsupportedOperationException(); + } - public void glDeleteRenderbuffersOES(int n, int[] renderbuffers, int offset) { - throw new UnsupportedOperationException(); - } + public void glDeleteRenderbuffersOES (int n, int[] renderbuffers, int offset) { + throw new UnsupportedOperationException(); + } - public void glDeleteRenderbuffersOES(int n, java.nio.IntBuffer renderbuffers) { - throw new UnsupportedOperationException(); - } + public void glDeleteRenderbuffersOES (int n, java.nio.IntBuffer renderbuffers) { + throw new UnsupportedOperationException(); + } - public void glFramebufferRenderbufferOES(int target, int attachment, int renderbuffertarget, int renderbuffer) { - throw new UnsupportedOperationException(); - } + public void glFramebufferRenderbufferOES (int target, int attachment, int renderbuffertarget, int renderbuffer) { + throw new UnsupportedOperationException(); + } - public void glFramebufferTexture2DOES(int target, int attachment, int textarget, int texture, int level) { - throw new UnsupportedOperationException(); - } + public void glFramebufferTexture2DOES (int target, int attachment, int textarget, int texture, int level) { + throw new UnsupportedOperationException(); + } - public void glGenerateMipmapOES(int target) { - throw new UnsupportedOperationException(); - } + public void glGenerateMipmapOES (int target) { + throw new UnsupportedOperationException(); + } - public void glGenFramebuffersOES(int n, int[] framebuffers, int offset) { - throw new UnsupportedOperationException(); - } + public void glGenFramebuffersOES (int n, int[] framebuffers, int offset) { + throw new UnsupportedOperationException(); + } - public void glGenFramebuffersOES(int n, java.nio.IntBuffer framebuffers) { - throw new UnsupportedOperationException(); - } + public void glGenFramebuffersOES (int n, java.nio.IntBuffer framebuffers) { + throw new UnsupportedOperationException(); + } - public void glGenRenderbuffersOES(int n, int[] renderbuffers, int offset) { - throw new UnsupportedOperationException(); - } + public void glGenRenderbuffersOES (int n, int[] renderbuffers, int offset) { + throw new UnsupportedOperationException(); + } - public void glGenRenderbuffersOES(int n, java.nio.IntBuffer renderbuffers) { - throw new UnsupportedOperationException(); - } + public void glGenRenderbuffersOES (int n, java.nio.IntBuffer renderbuffers) { + throw new UnsupportedOperationException(); + } - public void glGetFramebufferAttachmentParameterivOES(int target, int attachment, int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glGetFramebufferAttachmentParameterivOES (int target, int attachment, int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetFramebufferAttachmentParameterivOES(int target, int attachment, int pname, java.nio.IntBuffer params) { - throw new UnsupportedOperationException(); - } + public void glGetFramebufferAttachmentParameterivOES (int target, int attachment, int pname, java.nio.IntBuffer params) { + throw new UnsupportedOperationException(); + } - public void glGetRenderbufferParameterivOES(int target, int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glGetRenderbufferParameterivOES (int target, int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetRenderbufferParameterivOES(int target, int pname, java.nio.IntBuffer params) { - throw new UnsupportedOperationException(); - } + public void glGetRenderbufferParameterivOES (int target, int pname, java.nio.IntBuffer params) { + throw new UnsupportedOperationException(); + } - public void glGetTexGenfv(int coord, int pname, float[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glGetTexGenfv (int coord, int pname, float[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetTexGenfv(int coord, int pname, java.nio.FloatBuffer params) { - throw new UnsupportedOperationException(); - } + public void glGetTexGenfv (int coord, int pname, java.nio.FloatBuffer params) { + throw new UnsupportedOperationException(); + } - public void glGetTexGeniv(int coord, int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glGetTexGeniv (int coord, int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetTexGeniv(int coord, int pname, java.nio.IntBuffer params) { - throw new UnsupportedOperationException(); - } + public void glGetTexGeniv (int coord, int pname, java.nio.IntBuffer params) { + throw new UnsupportedOperationException(); + } - public void glGetTexGenxv(int coord, int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glGetTexGenxv (int coord, int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glGetTexGenxv(int coord, int pname, java.nio.IntBuffer params) { - throw new UnsupportedOperationException(); - } + public void glGetTexGenxv (int coord, int pname, java.nio.IntBuffer params) { + throw new UnsupportedOperationException(); + } - public boolean glIsFramebufferOES(int framebuffer) { - throw new UnsupportedOperationException(); - } + public boolean glIsFramebufferOES (int framebuffer) { + throw new UnsupportedOperationException(); + } - public boolean glIsRenderbufferOES(int renderbuffer) { - throw new UnsupportedOperationException(); - } + public boolean glIsRenderbufferOES (int renderbuffer) { + throw new UnsupportedOperationException(); + } - public void glRenderbufferStorageOES(int target, int internalformat, int width, int height) { - throw new UnsupportedOperationException(); - } + public void glRenderbufferStorageOES (int target, int internalformat, int width, int height) { + throw new UnsupportedOperationException(); + } - public void glTexGenf(int coord, int pname, float param) { - throw new UnsupportedOperationException(); - } + public void glTexGenf (int coord, int pname, float param) { + throw new UnsupportedOperationException(); + } - public void glTexGenfv(int coord, int pname, float[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glTexGenfv (int coord, int pname, float[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glTexGenfv(int coord, int pname, java.nio.FloatBuffer params) { - throw new UnsupportedOperationException(); - } + public void glTexGenfv (int coord, int pname, java.nio.FloatBuffer params) { + throw new UnsupportedOperationException(); + } - public void glTexGeni(int coord, int pname, int param) { - throw new UnsupportedOperationException(); - } + public void glTexGeni (int coord, int pname, int param) { + throw new UnsupportedOperationException(); + } - public void glTexGeniv(int coord, int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glTexGeniv (int coord, int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glTexGeniv(int coord, int pname, java.nio.IntBuffer params) { - throw new UnsupportedOperationException(); - } + public void glTexGeniv (int coord, int pname, java.nio.IntBuffer params) { + throw new UnsupportedOperationException(); + } - public void glTexGenx(int coord, int pname, int param) { - throw new UnsupportedOperationException(); - } + public void glTexGenx (int coord, int pname, int param) { + throw new UnsupportedOperationException(); + } - public void glTexGenxv(int coord, int pname, int[] params, int offset) { - throw new UnsupportedOperationException(); - } + public void glTexGenxv (int coord, int pname, int[] params, int offset) { + throw new UnsupportedOperationException(); + } - public void glTexGenxv(int coord, int pname, java.nio.IntBuffer params) { - throw new UnsupportedOperationException(); - } -} \ No newline at end of file + public void glTexGenxv (int coord, int pname, java.nio.IntBuffer params) { + throw new UnsupportedOperationException(); + } +} diff --git a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletApplication.java b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletApplication.java index ba375a3b6..bf1ef5427 100644 --- a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletApplication.java +++ b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletApplication.java @@ -1,17 +1,14 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ package com.badlogic.gdx.backends.applet; @@ -31,115 +28,93 @@ import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.GL11; /** - * An implemenation of the {@link Application} interface based on Jogl for Windows, Linux and Mac. Instantiate - * this class with apropriate parameters and then register {@link ApplicationListener}, {@link RenderListener} or {@link InputListener} - * instances. + * An implemenation of the {@link Application} interface based on Jogl for Windows, Linux and Mac. Instantiate this class with + * apropriate parameters and then register {@link ApplicationListener}, {@link RenderListener} or {@link InputListener} instances. * * @author mzechner - * + * */ -public class AppletApplication implements Application -{ +public class AppletApplication implements Application { /** the graphics instance **/ private AppletGraphics graphics; - + /** the input instance **/ private AppletInput input; - + /** the audio instance **/ private AppletAudio audio; - + /** the DestroyListener **/ ApplicationListener listener; - + /** - * Initializes a new {@link AppletApplication}. If useGL20IfAvailable is set the - * AppletApplication will try to create an OpenGL 2.0 context - * which can then be used via {@link AppletApplication.getGraphics().getGL20()}. The - * {@link GL10} and {@link GL11} interfaces should not be used when - * OpenGL 2.0 is enabled. To query whether enabling OpenGL 2.0 was - * successful use the {@link AppletApplication.getGraphics().isGL20Available()} - * method. + * Initializes a new {@link AppletApplication}. If useGL20IfAvailable is set the AppletApplication will try to create an OpenGL + * 2.0 context which can then be used via {@link AppletApplication.getGraphics().getGL20()}. The {@link GL10} and {@link GL11} + * interfaces should not be used when OpenGL 2.0 is enabled. To query whether enabling OpenGL 2.0 was successful use the + * {@link AppletApplication.getGraphics().isGL20Available()} method. * * @param useGL20IfAvailable wheter to use OpenGL 2.0 if it is available or not * @param allowFixedPoint not allowing fixed point will reduce memory consumption considerably */ - public AppletApplication( Applet applet, boolean useGL20IfAvailable, boolean allowFixedPoint ) - { - graphics = new AppletGraphics( this, applet, useGL20IfAvailable, allowFixedPoint ); - input = new AppletInput( graphics.graphicPanel ); - audio = new AppletAudio( ); - + public AppletApplication (Applet applet, boolean useGL20IfAvailable, boolean allowFixedPoint) { + graphics = new AppletGraphics(this, applet, useGL20IfAvailable, allowFixedPoint); + input = new AppletInput(graphics.graphicPanel); + audio = new AppletAudio(); + Gdx.app = this; Gdx.graphics = this.getGraphics(); Gdx.input = this.getInput(); Gdx.audio = this.getAudio(); Gdx.files = this.getFiles(); } - + /** * {@inheritDoc} */ - @Override - public Audio getAudio() - { + @Override public Audio getAudio () { return audio; } /** * {@inheritDoc} */ - @Override - public Files getFiles() - { - return new AppletFiles( ); + @Override public Files getFiles () { + return new AppletFiles(); } /** * {@inheritDoc} */ - @Override - public Graphics getGraphics() - { + @Override public Graphics getGraphics () { return graphics; } /** * {@inheritDoc} */ - @Override - public Input getInput() - { + @Override public Input getInput () { return input; } /** * {@inheritDoc} */ - @Override - public void setApplicationListener(ApplicationListener listener) - { + @Override public void setApplicationListener (ApplicationListener listener) { this.listener = listener; } - @Override - public void log(String tag, String message) - { - System.out.println( tag + ": " + message ); + @Override public void log (String tag, String message) { + System.out.println(tag + ": " + message); } /** * {@inheritDoc} */ - @Override - public ApplicationType getType() - { + @Override public ApplicationType getType () { return ApplicationType.Applet; } - @Override - public int getVersion() - { + @Override public int getVersion () { return 0; } diff --git a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletAudio.java b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletAudio.java index 28658075b..eb808a8d0 100644 --- a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletAudio.java +++ b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletAudio.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.applet; import java.util.ArrayList; @@ -34,105 +32,91 @@ import com.badlogic.gdx.files.FileHandle; * An implementation of the {@link Audio} interface for the desktop. * * @author mzechner - * + * */ -final class AppletAudio implements Audio, Runnable -{ +final class AppletAudio implements Audio, Runnable { /** the audio line for sound effects **/ private SourceDataLine line; - - /** The current buffers to play **/ - private final List buffers = new ArrayList( ); - + + /** The current buffers to play **/ + private final List buffers = new ArrayList(); + /** The sound effects thread **/ private Thread thread; - + /** * Helper class for playing back sound effects concurrently. * * @author mzechner - * + * */ - class JoglSoundBuffer - { + class JoglSoundBuffer { private final float[] samples; private final AudioFormat format; private final float volume; private int writtenSamples = 0; - - public JoglSoundBuffer( AppletSound sound, float volume ) throws Exception - { - samples = sound.getAudioData( ); + + public JoglSoundBuffer (AppletSound sound, float volume) throws Exception { + samples = sound.getAudioData(); format = sound.getAudioFormat(); this.volume = volume; } - + /** - * Writes the next numFrames frames to the line for playback + * Writes the next numFrames frames to the line for playback * @return whether playback is done or not. */ - public boolean writeSamples( int numSamples, float[] buffer ) - { - if( format.getChannels() == 1 ) - { - int remainingSamples = Math.min( samples.length, writtenSamples + numSamples / 2 ); - for( int i = writtenSamples, j = 0; i < remainingSamples; i++, j+=2 ) - { + public boolean writeSamples (int numSamples, float[] buffer) { + if (format.getChannels() == 1) { + int remainingSamples = Math.min(samples.length, writtenSamples + numSamples / 2); + for (int i = writtenSamples, j = 0; i < remainingSamples; i++, j += 2) { buffer[j] += samples[i] * volume; - buffer[j+1] += samples[i] * volume; + buffer[j + 1] += samples[i] * volume; writtenSamples++; } - } - else - { - int remainingSamples = Math.min( samples.length, writtenSamples + numSamples ); - for( int i = writtenSamples, j = 0; i < remainingSamples; i+= 2, j+=2 ) - { + } else { + int remainingSamples = Math.min(samples.length, writtenSamples + numSamples); + for (int i = writtenSamples, j = 0; i < remainingSamples; i += 2, j += 2) { buffer[j] += samples[i] * volume; - buffer[j+1] += samples[i+1] * volume; - writtenSamples+=2; - } - } - - if( writtenSamples >= samples.length ) + buffer[j + 1] += samples[i + 1] * volume; + writtenSamples += 2; + } + } + + if (writtenSamples >= samples.length) return false; else return true; } } - - AppletAudio( ) - { + + AppletAudio () { try { - AudioFormat format = new AudioFormat( 44100.0f, 16, 2, true, false ); - line = AudioSystem.getSourceDataLine( format ); + AudioFormat format = new AudioFormat(44100.0f, 16, 2, true, false); + line = AudioSystem.getSourceDataLine(format); line.open(format, 4410); line.start(); - thread = new Thread( this ); - thread.setDaemon( true ); + thread = new Thread(this); + thread.setDaemon(true); thread.start(); } catch (Exception e) { e.printStackTrace(); - } + } } - + /** * {@inheritDoc} */ - @Override - public AudioDevice newAudioDevice(boolean isMono) - { - return new AppletAudioDevice( isMono ); + @Override public AudioDevice newAudioDevice (boolean isMono) { + return new AppletAudioDevice(isMono); } /** * {@inheritDoc} */ - @Override - public Music newMusic(FileHandle file) - { - try { - AppletMusic music = new AppletMusic( ((AppletFileHandle)file) ); + @Override public Music newMusic (FileHandle file) { + try { + AppletMusic music = new AppletMusic(((AppletFileHandle)file)); return music; } catch (Exception e) { e.printStackTrace(); @@ -143,10 +127,9 @@ final class AppletAudio implements Audio, Runnable /** * {@inheritDoc} */ - @Override - public Sound newSound(FileHandle file) { - try { - AppletSound sound = new AppletSound( this, ((AppletFileHandle)file) ); + @Override public Sound newSound (FileHandle file) { + try { + AppletSound sound = new AppletSound(this, ((AppletFileHandle)file)); return sound; } catch (Exception e) { e.printStackTrace(); @@ -154,41 +137,32 @@ final class AppletAudio implements Audio, Runnable } } - protected void enqueueSound( AppletSound sound, float volume ) - { - try - { - synchronized( this ) - { - buffers.add( new JoglSoundBuffer( sound, volume ) ); + protected void enqueueSound (AppletSound sound, float volume) { + try { + synchronized (this) { + buffers.add(new JoglSoundBuffer(sound, volume)); } - } - catch( Exception ex ) - { + } catch (Exception ex) { ex.printStackTrace(); } } - - @Override - public void run() - { - + + @Override public void run () { + int NUM_SAMPLES = 44100 * 2; float[] buffer = new float[NUM_SAMPLES]; - byte[] bytes = new byte[2 * NUM_SAMPLES]; - - while( true ) - { - int samplesToWrite = line.available() / 2; - - if( samplesToWrite > 0 ) - { - fillBuffer( buffer, bytes, samplesToWrite ); - int writtenBytes = line.write(bytes, 0, samplesToWrite * 2 ); - while( writtenBytes != samplesToWrite * 2 ) - writtenBytes += line.write( bytes, writtenBytes, samplesToWrite - writtenBytes ); + byte[] bytes = new byte[2 * NUM_SAMPLES]; + + while (true) { + int samplesToWrite = line.available() / 2; + + if (samplesToWrite > 0) { + fillBuffer(buffer, bytes, samplesToWrite); + int writtenBytes = line.write(bytes, 0, samplesToWrite * 2); + while (writtenBytes != samplesToWrite * 2) + writtenBytes += line.write(bytes, writtenBytes, samplesToWrite - writtenBytes); } - + try { Thread.sleep(5); } catch (InterruptedException e) { @@ -196,47 +170,38 @@ final class AppletAudio implements Audio, Runnable } } } - - private void fillBuffer( float[] buffer, byte[] bytes, int samplesToWrite ) - { - for( int i = 0; i < buffer.length; i++ ) + + private void fillBuffer (float[] buffer, byte[] bytes, int samplesToWrite) { + for (int i = 0; i < buffer.length; i++) buffer[i] = 0.0f; - for( int i = 0; i < bytes.length; i++ ) + for (int i = 0; i < bytes.length; i++) bytes[i] = 0; - + int numBuffers = buffers.size(); - synchronized( this ) - { + synchronized (this) { Iterator bufferIter = buffers.iterator(); - while( bufferIter.hasNext() ) - { + while (bufferIter.hasNext()) { JoglSoundBuffer soundBuffer = bufferIter.next(); - if( !soundBuffer.writeSamples(samplesToWrite, buffer) ) - bufferIter.remove(); + if (!soundBuffer.writeSamples(samplesToWrite, buffer)) bufferIter.remove(); } - } - - if( numBuffers > 0 ) - { - for( int i = 0, j = 0; i < samplesToWrite; i++, j+=2 ) - { - float fValue = buffer[i]; - if( fValue > 1 ) - fValue = 1; - if( fValue < -1 ) - fValue = -1; - short value = (short)( fValue * Short.MAX_VALUE); - bytes[j] = (byte)(value | 0xff); - bytes[j+1] = (byte)(value >> 8 ); - } - } + } + + if (numBuffers > 0) { + for (int i = 0, j = 0; i < samplesToWrite; i++, j += 2) { + float fValue = buffer[i]; + if (fValue > 1) fValue = 1; + if (fValue < -1) fValue = -1; + short value = (short)(fValue * Short.MAX_VALUE); + bytes[j] = (byte)(value | 0xff); + bytes[j + 1] = (byte)(value >> 8); + } + } } /** * {@inheritDoc} */ - @Override - public AudioRecorder newAudioRecoder(int samplingRate, boolean isMono) { + @Override public AudioRecorder newAudioRecoder (int samplingRate, boolean isMono) { return new AppletAudioRecorder(samplingRate, isMono); } } diff --git a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletAudioDevice.java b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletAudioDevice.java index 1f564992f..27d2ff87a 100644 --- a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletAudioDevice.java +++ b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletAudioDevice.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.applet; import javax.sound.sampled.AudioFormat; @@ -22,88 +20,71 @@ import javax.sound.sampled.SourceDataLine; import com.badlogic.gdx.audio.AudioDevice; /** - * Implementation of the {@link AudioDevice} interface for the - * desktop using Java Sound. + * Implementation of the {@link AudioDevice} interface for the desktop using Java Sound. * * @author mzechner - * + * */ -public final class AppletAudioDevice implements AudioDevice -{ +public final class AppletAudioDevice implements AudioDevice { /** the audio line **/ private SourceDataLine line; - + /** whether this device is mono **/ private final boolean isMono; - + /** byte buffer **/ - private byte[] bytes = new byte[44100*2*2]; - - public AppletAudioDevice( boolean isMono ) - { + private byte[] bytes = new byte[44100 * 2 * 2]; + + public AppletAudioDevice (boolean isMono) { this.isMono = isMono; - + try { - AudioFormat format = new AudioFormat( 44100.0f, 16, isMono?1:2, true, false ); - line = AudioSystem.getSourceDataLine( format ); + AudioFormat format = new AudioFormat(44100.0f, 16, isMono ? 1 : 2, true, false); + line = AudioSystem.getSourceDataLine(format); line.open(format, 4410); - line.start(); + line.start(); } catch (Exception e) { - e.printStackTrace(); - } + e.printStackTrace(); + } } - - @Override - public void dispose() - { + + @Override public void dispose () { line.drain(); line.close(); } - @Override - public boolean isMono() - { + @Override public boolean isMono () { return isMono; } - @Override - public void writeSamples(short[] samples, int offset, int numSamples ) - { - if( bytes.length < samples.length * 2 ) - bytes = new byte[samples.length*2]; - - for( int i = offset, j = 0; i < offset + numSamples; i++, j+=2 ) - { - short value = samples[i]; - bytes[j] = (byte)(value | 0xff); - bytes[j+1] = (byte)(value >> 8 ); - } - - int writtenBytes = line.write( bytes, 0, numSamples * 2 ); - while( writtenBytes != numSamples * 2 ) - writtenBytes += line.write( bytes, writtenBytes, numSamples * 2 - writtenBytes ); + @Override public void writeSamples (short[] samples, int offset, int numSamples) { + if (bytes.length < samples.length * 2) bytes = new byte[samples.length * 2]; + + for (int i = offset, j = 0; i < offset + numSamples; i++, j += 2) { + short value = samples[i]; + bytes[j] = (byte)(value | 0xff); + bytes[j + 1] = (byte)(value >> 8); + } + + int writtenBytes = line.write(bytes, 0, numSamples * 2); + while (writtenBytes != numSamples * 2) + writtenBytes += line.write(bytes, writtenBytes, numSamples * 2 - writtenBytes); } - @Override - public void writeSamples(float[] samples, int offset, int numSamples) - { - if( bytes.length < samples.length * 2 ) - bytes = new byte[samples.length*2]; - - for( int i = offset, j = 0; i < offset + numSamples; i++, j+=2 ) - { - float fValue = samples[i]; - if( fValue > 1 ) - fValue = 1; - if( fValue < -1 ) - fValue = -1; - short value = (short)( fValue * Short.MAX_VALUE); - bytes[j] = (byte)(value | 0xff); - bytes[j+1] = (byte)(value >> 8 ); - } - - int writtenBytes = line.write( bytes, 0, numSamples * 2 ); - while( writtenBytes != numSamples * 2 ) - writtenBytes += line.write( bytes, writtenBytes, numSamples * 2 - writtenBytes ); + @Override public void writeSamples (float[] samples, int offset, int numSamples) { + if (bytes.length < samples.length * 2) bytes = new byte[samples.length * 2]; + + for (int i = offset, j = 0; i < offset + numSamples; i++, j += 2) { + float fValue = samples[i]; + if (fValue > 1) fValue = 1; + if (fValue < -1) fValue = -1; + short value = (short)(fValue * Short.MAX_VALUE); + bytes[j] = (byte)(value | 0xff); + bytes[j + 1] = (byte)(value >> 8); + } + + int writtenBytes = line.write(bytes, 0, numSamples * 2); + while (writtenBytes != numSamples * 2) + writtenBytes += line.write(bytes, writtenBytes, numSamples * 2 - writtenBytes); } } diff --git a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletAudioRecorder.java b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletAudioRecorder.java index dedf599b1..648331454 100644 --- a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletAudioRecorder.java +++ b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletAudioRecorder.java @@ -1,78 +1,65 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.applet; import javax.sound.sampled.AudioFormat; +import javax.sound.sampled.AudioFormat.Encoding; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.TargetDataLine; -import javax.sound.sampled.AudioFormat.Encoding; import com.badlogic.gdx.audio.AudioRecorder; /** - * {@link AudioRecorder} implementation for the applets using - * the java sound API. + * {@link AudioRecorder} implementation for the applets using the java sound API. * * @author badlogicgames@gmail.com - * + * */ -public class AppletAudioRecorder implements AudioRecorder -{ +public class AppletAudioRecorder implements AudioRecorder { /** the line we read the audio from **/ private TargetDataLine line; - + /** the buffer to temporarily store the samples **/ - private byte[] buffer = new byte[1024*4]; - - public AppletAudioRecorder( int samplingRate, boolean isMono ) - { - try - { - AudioFormat format = new AudioFormat( Encoding.PCM_SIGNED, samplingRate, 16, isMono?1:2, isMono?2:4, samplingRate, false ); - line = AudioSystem.getTargetDataLine( format ); + private byte[] buffer = new byte[1024 * 4]; + + public AppletAudioRecorder (int samplingRate, boolean isMono) { + try { + AudioFormat format = new AudioFormat(Encoding.PCM_SIGNED, samplingRate, 16, isMono ? 1 : 2, isMono ? 2 : 4, + samplingRate, false); + line = AudioSystem.getTargetDataLine(format); line.open(format, buffer.length); - line.start(); - } - catch( Exception ex ) - { - throw new IllegalStateException( "Couldn't create AudioRecorder", ex ); + line.start(); + } catch (Exception ex) { + throw new IllegalStateException("Couldn't create AudioRecorder", ex); } } - - @Override - public void read(short[] samples, int offset, int numSamples) - { - if( buffer.length < numSamples * 2 ) - buffer = new byte[numSamples*2]; - + + @Override public void read (short[] samples, int offset, int numSamples) { + if (buffer.length < numSamples * 2) buffer = new byte[numSamples * 2]; + int toRead = numSamples * 2; int read = 0; - - while( read != toRead ) - read += line.read( buffer, read, toRead - read ); - - for( int i = 0, j = 0; i < numSamples * 2; i+=2, j++ ) - { - samples[offset + j] = (short)((buffer[i] << 8) | (buffer[i+1] & 0xff)); - } + + while (read != toRead) + read += line.read(buffer, read, toRead - read); + + for (int i = 0, j = 0; i < numSamples * 2; i += 2, j++) { + samples[offset + j] = (short)((buffer[i] << 8) | (buffer[i + 1] & 0xff)); + } } - - @Override - public void dispose() - { + + @Override public void dispose () { line.close(); } } diff --git a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletFileHandle.java b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletFileHandle.java index cc6f973cd..236df8087 100644 --- a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletFileHandle.java +++ b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletFileHandle.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.applet; import java.io.InputStream; @@ -20,26 +18,23 @@ import java.io.InputStream; import com.badlogic.gdx.files.FileHandle; /** - * A {@link FileHandle} implementation for the desktop. + * A {@link FileHandle} implementation for the desktop. * * @author mzechner - * + * */ -public class AppletFileHandle implements FileHandle -{ +public class AppletFileHandle implements FileHandle { /** the file **/ private final String uri; - - AppletFileHandle( String uri ) - { + + AppletFileHandle (String uri) { this.uri = uri; } - + /** * @return the underlying {@link InputStream}. Needs to be closed when the handle is no longer used. */ - public InputStream getInputStream( ) - { - return getClass().getResourceAsStream( "/" + uri ); + public InputStream getInputStream () { + return getClass().getResourceAsStream("/" + uri); } } diff --git a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletFiles.java b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletFiles.java index 618dbc77f..e6827c108 100644 --- a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletFiles.java +++ b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletFiles.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.applet; import java.io.InputStream; @@ -22,63 +20,51 @@ import com.badlogic.gdx.Files; import com.badlogic.gdx.files.FileHandle; /** - * Implementation for a desktop application of {@link Files}. Internal - * resources are relative to the application root directory, external files - * are relative to the user's home directory. - * + * Implementation for a desktop application of {@link Files}. Internal resources are relative to the application root directory, + * external files are relative to the user's home directory. + * * @author mzechner - * + * */ -final class AppletFiles implements Files -{ +final class AppletFiles implements Files { /** * {@inheritDoc} */ - @Override - public FileHandle getFileHandle(String filename, FileType type) - { - if( type == FileType.Absolut || type == FileType.External ) + @Override public FileHandle getFileHandle (String filename, FileType type) { + if (type == FileType.Absolut || type == FileType.External) return null; else - return new AppletFileHandle( filename ); + return new AppletFileHandle(filename); } /** * {@inheritDoc} */ - @Override - public String[] listDirectory(String directory, FileType type) - { + @Override public String[] listDirectory (String directory, FileType type) { return new String[0]; } /** * {@inheritDoc} */ - @Override - public boolean makeDirectory(String directory, FileType type) - { + @Override public boolean makeDirectory (String directory, FileType type) { return false; } /** * {@inheritDoc} */ - @Override - public InputStream readFile(String fileName, FileType type) - { - if( type == FileType.Absolut || type == FileType.External ) + @Override public InputStream readFile (String fileName, FileType type) { + if (type == FileType.Absolut || type == FileType.External) return null; else - return new AppletFileHandle( fileName ).getInputStream(); + return new AppletFileHandle(fileName).getInputStream(); } /** * {@inheritDoc} */ - @Override - public OutputStream writeFile(String filename, FileType type) - { + @Override public OutputStream writeFile (String filename, FileType type) { return null; } } diff --git a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletFont.java b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletFont.java index 7d594ed88..5c4017f0f 100644 --- a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletFont.java +++ b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletFont.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.applet; import java.awt.FontMetrics; @@ -27,122 +25,102 @@ import com.badlogic.gdx.graphics.Font; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.math.Rectangle; - /** * An implementation of {@link Font} based on the java graphics framework. * * @author badlogicgames@gmail.com - * + * */ -final class AppletFont extends Font -{ - private final BufferedImage tmpBitmap = new BufferedImage( 1, 1, BufferedImage.TYPE_4BYTE_ABGR ); - private java.awt.Font font; +final class AppletFont extends Font { + private final BufferedImage tmpBitmap = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR); + private java.awt.Font font; private FontMetrics metrics; - - AppletFont( com.badlogic.gdx.Graphics graphics, String fontName, int size, FontStyle style ) - { - super( ); - font = new java.awt.Font( fontName, getJavaFontStyle(style), size ); + + AppletFont (com.badlogic.gdx.Graphics graphics, String fontName, int size, FontStyle style) { + super(); + font = new java.awt.Font(fontName, getJavaFontStyle(style), size); Graphics g = tmpBitmap.getGraphics(); - g.setFont( font ); + g.setFont(font); metrics = g.getFontMetrics(); g.dispose(); } - - AppletFont( com.badlogic.gdx.Graphics graphics, InputStream in, int size, FontStyle style ) - { - super( ); - - try - { - java.awt.Font baseFont = java.awt.Font.createFont( java.awt.Font.PLAIN, in); - font = baseFont.deriveFont( getJavaFontStyle(style), size ); - } - catch( Exception ex ) - { - font = new java.awt.Font( "Arial", getJavaFontStyle(style), size ); + + AppletFont (com.badlogic.gdx.Graphics graphics, InputStream in, int size, FontStyle style) { + super(); + + try { + java.awt.Font baseFont = java.awt.Font.createFont(java.awt.Font.PLAIN, in); + font = baseFont.deriveFont(getJavaFontStyle(style), size); + } catch (Exception ex) { + font = new java.awt.Font("Arial", getJavaFontStyle(style), size); } Graphics g = tmpBitmap.getGraphics(); - g.setFont( font ); + g.setFont(font); metrics = g.getFontMetrics(); g.dispose(); } - - private int getJavaFontStyle( FontStyle style ) - { - if( style == FontStyle.Plain ) - return java.awt.Font.PLAIN; - if( style == FontStyle.Bold ) - return java.awt.Font.BOLD; - if( style == FontStyle.Italic ) - return java.awt.Font.ITALIC; - if( style == FontStyle.BoldItalic ) - return java.awt.Font.BOLD | java.awt.Font.ITALIC; - + + private int getJavaFontStyle (FontStyle style) { + if (style == FontStyle.Plain) return java.awt.Font.PLAIN; + if (style == FontStyle.Bold) return java.awt.Font.BOLD; + if (style == FontStyle.Italic) return java.awt.Font.ITALIC; + if (style == FontStyle.BoldItalic) return java.awt.Font.BOLD | java.awt.Font.ITALIC; + return java.awt.Font.PLAIN; } - + /** * {@inheritDoc} */ - @Override - public int getGlyphAdvance(char character) - { + @Override public int getGlyphAdvance (char character) { return metrics.charWidth(character); } /** * {@inheritDoc} */ - @Override - public Pixmap getGlyphBitmap(char character) { + @Override public Pixmap getGlyphBitmap (char character) { Graphics2D g = (Graphics2D)tmpBitmap.getGraphics(); - g.setFont( font ); - Rectangle2D bounds = metrics.getStringBounds( "" + character, g); - g.dispose( ); - - BufferedImage bitmap = new BufferedImage( (int)Math.ceil(bounds.getWidth()), getLineHeight(), BufferedImage.TYPE_4BYTE_ABGR ); + g.setFont(font); + Rectangle2D bounds = metrics.getStringBounds("" + character, g); + g.dispose(); + + BufferedImage bitmap = new BufferedImage((int)Math.ceil(bounds.getWidth()), getLineHeight(), BufferedImage.TYPE_4BYTE_ABGR); g = (Graphics2D)bitmap.getGraphics(); - - g.setFont(font); - g.addRenderingHints( new RenderingHints( RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON )); - g.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING, - RenderingHints.VALUE_TEXT_ANTIALIAS_ON ); - - g.setColor( new java.awt.Color( 0x0000000, true ) ); - g.fillRect( 0, 0, bitmap.getWidth(), bitmap.getHeight() ); - g.setColor( new java.awt.Color( 0xffffffff, true ) ); - g.drawString( "" + character, 0, metrics.getAscent()); + + g.setFont(font); + g.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)); + g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + + g.setColor(new java.awt.Color(0x0000000, true)); + g.fillRect(0, 0, bitmap.getWidth(), bitmap.getHeight()); + g.setColor(new java.awt.Color(0xffffffff, true)); + g.drawString("" + character, 0, metrics.getAscent()); g.dispose(); - - return new AppletPixmap( bitmap ); + + return new AppletPixmap(bitmap); } /** * {@inheritDoc} */ - @Override - public int getLineGap() { + @Override public int getLineGap () { return metrics.getLeading(); } /** * {@inheritDoc} */ - @Override - public int getLineHeight() { + @Override public int getLineHeight () { return metrics.getAscent() + metrics.getDescent(); } /** * {@inheritDoc} */ - @Override - public int getStringWidth(String text) { + @Override public int getStringWidth (String text) { Graphics g = tmpBitmap.getGraphics(); - g.setFont( font ); + g.setFont(font); int width = (int)Math.ceil(metrics.getStringBounds(text, g).getWidth()); g.dispose(); return width; @@ -151,14 +129,13 @@ final class AppletFont extends Font /** * {@inheritDoc} */ - @Override - public void getGlyphBounds(char character, Rectangle rect) { + @Override public void getGlyphBounds (char character, Rectangle rect) { Graphics g = tmpBitmap.getGraphics(); - g.setFont( font ); - Rectangle2D bounds = metrics.getStringBounds( "" + character, g); + g.setFont(font); + Rectangle2D bounds = metrics.getStringBounds("" + character, g); g.dispose(); - rect.setWidth( (int)Math.ceil(bounds.getWidth()) ); - rect.setHeight( getLineHeight() ); + rect.setWidth((int)Math.ceil(bounds.getWidth())); + rect.setHeight(getLineHeight()); } } diff --git a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletGL10.java b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletGL10.java index 05fde6672..21e8f1a08 100644 --- a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletGL10.java +++ b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletGL10.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.applet; import java.nio.Buffer; @@ -24,16 +22,14 @@ import java.nio.IntBuffer; import com.badlogic.gdx.graphics.GL10; /** - * An implementation of the {@link GL10} interface based on Jogl. Fixed point vertex - * arrays are emulated. + * An implementation of the {@link GL10} interface based on Jogl. Fixed point vertex arrays are emulated. * * @author mzechner - * + * */ -class AppletGL10 implements GL10 -{ +class AppletGL10 implements GL10 { protected final javax.media.opengl.GL gl; - protected final float FIXED_TO_FLOAT = 1 / 65536.0f; + protected final float FIXED_TO_FLOAT = 1 / 65536.0f; private final FloatBuffer colorBuffer; private final FloatBuffer normalBuffer; private final FloatBuffer vertexBuffer; @@ -41,917 +37,626 @@ class AppletGL10 implements GL10 private int activeTexture = 0; private boolean allowFixedPoint = true; private float[] tmp = new float[1000]; - - - public AppletGL10( javax.media.opengl.GL gl, boolean allowFixedPoint ) - { + + public AppletGL10 (javax.media.opengl.GL gl, boolean allowFixedPoint) { this.gl = gl; this.allowFixedPoint = allowFixedPoint; - if( allowFixedPoint ) - { - ByteBuffer buffer = ByteBuffer.allocateDirect( 200000 * 4 * 4 ); + if (allowFixedPoint) { + ByteBuffer buffer = ByteBuffer.allocateDirect(200000 * 4 * 4); buffer.order(ByteOrder.nativeOrder()); colorBuffer = buffer.asFloatBuffer(); - - buffer = ByteBuffer.allocateDirect( 200000 * 4 * 3 ); + + buffer = ByteBuffer.allocateDirect(200000 * 4 * 3); buffer.order(ByteOrder.nativeOrder()); normalBuffer = buffer.asFloatBuffer(); - - buffer = ByteBuffer.allocateDirect( 200000 * 4 * 4 ); + + buffer = ByteBuffer.allocateDirect(200000 * 4 * 4); buffer.order(ByteOrder.nativeOrder()); vertexBuffer = buffer.asFloatBuffer(); - - for( int i = 0; i < texCoordBuffer.length; i++ ) - { - buffer = ByteBuffer.allocateDirect( 200000 * 4 * 4 ); - buffer.order(ByteOrder.nativeOrder()); + + for (int i = 0; i < texCoordBuffer.length; i++) { + buffer = ByteBuffer.allocateDirect(200000 * 4 * 4); + buffer.order(ByteOrder.nativeOrder()); texCoordBuffer[i] = buffer.asFloatBuffer(); } - } - else - { + } else { colorBuffer = null; normalBuffer = null; vertexBuffer = null; - for( int i = 0; i < texCoordBuffer.length; i++ ) - { + for (int i = 0; i < texCoordBuffer.length; i++) { texCoordBuffer[i] = null; } } - } - - protected final void convertFixedToFloatbuffer( Buffer source, FloatBuffer target, int stride ) - { - if( !allowFixedPoint ) - throw new IllegalStateException( "fixed point meshes were disabled when constructing the Applet!" ); - - if( source instanceof IntBuffer || source instanceof ByteBuffer ) - { - IntBuffer buffer = source instanceof ByteBuffer?((ByteBuffer)source).asIntBuffer():(IntBuffer)source; - if( stride % 4 != 0 ) - throw new IllegalArgumentException( "Can't cope with strides % 4 != 0 for IntBuffers" ); + } + + protected final void convertFixedToFloatbuffer (Buffer source, FloatBuffer target, int stride) { + if (!allowFixedPoint) throw new IllegalStateException("fixed point meshes were disabled when constructing the Applet!"); + + if (source instanceof IntBuffer || source instanceof ByteBuffer) { + IntBuffer buffer = source instanceof ByteBuffer ? ((ByteBuffer)source).asIntBuffer() : (IntBuffer)source; + if (stride % 4 != 0) throw new IllegalArgumentException("Can't cope with strides % 4 != 0 for IntBuffers"); target.clear(); - for( int i = buffer.position(); i < buffer.limit(); i++ ) - { + for (int i = buffer.position(); i < buffer.limit(); i++) { float value = FIXED_TO_FLOAT * buffer.get(i); - target.put( value ); + target.put(value); } target.flip(); - } - else - { - throw new IllegalArgumentException( "Can't cope with buffer of type " + source.getClass().getName() + ", only ByteBuffers and IntBuffers supported" ); + } else { + throw new IllegalArgumentException("Can't cope with buffer of type " + source.getClass().getName() + + ", only ByteBuffers and IntBuffers supported"); } } - - - @Override - public final void glActiveTexture(int texture) - { - gl.glActiveTexture( texture ); + + @Override public final void glActiveTexture (int texture) { + gl.glActiveTexture(texture); } - @Override - public final void glAlphaFunc(int func, float ref) - { - gl.glAlphaFunc( func, ref ); + @Override public final void glAlphaFunc (int func, float ref) { + gl.glAlphaFunc(func, ref); } - @Override - public final void glAlphaFuncx(int func, int ref) { - gl.glAlphaFunc( func, FIXED_TO_FLOAT * ref ); + @Override public final void glAlphaFuncx (int func, int ref) { + gl.glAlphaFunc(func, FIXED_TO_FLOAT * ref); } - @Override - public final void glBindTexture(int target, int texture) - { - gl.glBindTexture( target, texture ); + @Override public final void glBindTexture (int target, int texture) { + gl.glBindTexture(target, texture); } - @Override - public final void glBlendFunc(int sfactor, int dfactor) - { - gl.glBlendFunc( sfactor, dfactor ); + @Override public final void glBlendFunc (int sfactor, int dfactor) { + gl.glBlendFunc(sfactor, dfactor); } - @Override - public final void glClear(int mask) - { - gl.glClear( mask ); + @Override public final void glClear (int mask) { + gl.glClear(mask); } - @Override - public final void glClearColor(float red, float green, float blue, float alpha) - { - gl.glClearColor( red, green, blue, alpha ); + @Override public final void glClearColor (float red, float green, float blue, float alpha) { + gl.glClearColor(red, green, blue, alpha); } - @Override - public final void glClearColorx(int red, int green, int blue, int alpha) - { - gl.glClearColor( FIXED_TO_FLOAT * red, FIXED_TO_FLOAT * green, FIXED_TO_FLOAT * blue, FIXED_TO_FLOAT * alpha ); + @Override public final void glClearColorx (int red, int green, int blue, int alpha) { + gl.glClearColor(FIXED_TO_FLOAT * red, FIXED_TO_FLOAT * green, FIXED_TO_FLOAT * blue, FIXED_TO_FLOAT * alpha); } - @Override - public final void glClearDepthf(float depth) - { - gl.glClearDepth( depth ); + @Override public final void glClearDepthf (float depth) { + gl.glClearDepth(depth); } - @Override - public final void glClearDepthx(int depth) - { - gl.glClearDepth( FIXED_TO_FLOAT * depth ); + @Override public final void glClearDepthx (int depth) { + gl.glClearDepth(FIXED_TO_FLOAT * depth); } - @Override - public final void glClearStencil(int s) - { - gl.glClearStencil( s ); + @Override public final void glClearStencil (int s) { + gl.glClearStencil(s); } - @Override - public final void glClientActiveTexture(int texture) - { + @Override public final void glClientActiveTexture (int texture) { activeTexture = texture - GL10.GL_TEXTURE0; - gl.glClientActiveTexture( texture ); + gl.glClientActiveTexture(texture); } - @Override - public final void glColor4f(float red, float green, float blue, float alpha) - { - gl.glColor4f( red, green, blue, alpha ); + @Override public final void glColor4f (float red, float green, float blue, float alpha) { + gl.glColor4f(red, green, blue, alpha); } - @Override - public final void glColor4x(int red, int green, int blue, int alpha) - { - gl.glColor4f( FIXED_TO_FLOAT * red, FIXED_TO_FLOAT * green, FIXED_TO_FLOAT * blue, FIXED_TO_FLOAT * alpha ); + @Override public final void glColor4x (int red, int green, int blue, int alpha) { + gl.glColor4f(FIXED_TO_FLOAT * red, FIXED_TO_FLOAT * green, FIXED_TO_FLOAT * blue, FIXED_TO_FLOAT * alpha); } - @Override - public final void glColorMask(boolean red, boolean green, boolean blue, boolean alpha) - { - gl.glColorMask( red, green, blue, alpha ); + @Override public final void glColorMask (boolean red, boolean green, boolean blue, boolean alpha) { + gl.glColorMask(red, green, blue, alpha); } - @Override - public final void glColorPointer(int size, int type, int stride, Buffer pointer) - { - if( type == GL10.GL_FIXED ) - { - convertFixedToFloatbuffer(pointer,colorBuffer, stride); - gl.glColorPointer( size, GL10.GL_FLOAT, stride, colorBuffer ); - } - else - { - gl.glColorPointer( size, type, stride, pointer ); + @Override public final void glColorPointer (int size, int type, int stride, Buffer pointer) { + if (type == GL10.GL_FIXED) { + convertFixedToFloatbuffer(pointer, colorBuffer, stride); + gl.glColorPointer(size, GL10.GL_FLOAT, stride, colorBuffer); + } else { + gl.glColorPointer(size, type, stride, pointer); } } - @Override - public final void glCompressedTexImage2D(int target, int level, - int internalformat, int width, int height, int border, - int imageSize, Buffer data) - { - gl.glCompressedTexImage2D( target, level, internalformat, width, height, border, imageSize, data ); + @Override public final void glCompressedTexImage2D (int target, int level, int internalformat, int width, int height, + int border, int imageSize, Buffer data) { + gl.glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); } - @Override - public final void glCompressedTexSubImage2D(int target, int level, int xoffset, - int yoffset, int width, int height, int format, int imageSize, - Buffer data) - { - gl.glCompressedTexSubImage2D( target, level, xoffset, yoffset, width, height, format, imageSize, data ); + @Override public final void glCompressedTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, + int format, int imageSize, Buffer data) { + gl.glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); } - @Override - public final void glCopyTexImage2D(int target, int level, int internalformat, - int x, int y, int width, int height, int border) - { - gl.glCopyTexImage2D( target, level, internalformat, x, y, width, height, border ); + @Override public final void glCopyTexImage2D (int target, int level, int internalformat, int x, int y, int width, int height, + int border) { + gl.glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); } - @Override - public final void glCopyTexSubImage2D(int target, int level, int xoffset, - int yoffset, int x, int y, int width, int height) - { - gl.glCopyTexSubImage2D( target, level, xoffset, yoffset, x, y, width, height ); + @Override public final void glCopyTexSubImage2D (int target, int level, int xoffset, int yoffset, int x, int y, int width, + int height) { + gl.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); } - @Override - public final void glCullFace(int mode) - { - gl.glCullFace( mode ); + @Override public final void glCullFace (int mode) { + gl.glCullFace(mode); } - @Override - public final void glDeleteTextures(int n, IntBuffer textures) - { - gl.glDeleteTextures( n, textures ); + @Override public final void glDeleteTextures (int n, IntBuffer textures) { + gl.glDeleteTextures(n, textures); } - @Override - public final void glDepthFunc(int func) - { - gl.glDepthFunc( func ); + @Override public final void glDepthFunc (int func) { + gl.glDepthFunc(func); } - @Override - public final void glDepthMask(boolean flag) - { - gl.glDepthMask( flag ); + @Override public final void glDepthMask (boolean flag) { + gl.glDepthMask(flag); } - @Override - public final void glDepthRangef(float zNear, float zFar) - { - gl.glDepthRange( zNear, zFar ); + @Override public final void glDepthRangef (float zNear, float zFar) { + gl.glDepthRange(zNear, zFar); } - @Override - public final void glDepthRangex(int zNear, int zFar) - { - gl.glDepthRange( FIXED_TO_FLOAT * zNear, FIXED_TO_FLOAT * zFar ); + @Override public final void glDepthRangex (int zNear, int zFar) { + gl.glDepthRange(FIXED_TO_FLOAT * zNear, FIXED_TO_FLOAT * zFar); } - @Override - public final void glDisable(int cap) - { - gl.glDisable( cap ); + @Override public final void glDisable (int cap) { + gl.glDisable(cap); } - @Override - public final void glDisableClientState(int array) - { - gl.glDisableClientState( array ); + @Override public final void glDisableClientState (int array) { + gl.glDisableClientState(array); } - @Override - public final void glDrawArrays(int mode, int first, int count) - { - gl.glDrawArrays( mode, first, count ); + @Override public final void glDrawArrays (int mode, int first, int count) { + gl.glDrawArrays(mode, first, count); } - @Override - public final void glDrawElements(int mode, int count, int type, Buffer indices) - { - // nothing to do here per documentation - gl.glDrawElements( mode, count, type, indices ); + @Override public final void glDrawElements (int mode, int count, int type, Buffer indices) { + // nothing to do here per documentation + gl.glDrawElements(mode, count, type, indices); } - @Override - public final void glEnable(int cap) - { - gl.glEnable( cap ); + @Override public final void glEnable (int cap) { + gl.glEnable(cap); } - @Override - public final void glEnableClientState(int array) - { - gl.glEnableClientState( array ); + @Override public final void glEnableClientState (int array) { + gl.glEnableClientState(array); } - @Override - public final void glFinish() - { + @Override public final void glFinish () { gl.glFinish(); } - @Override - public final void glFlush() - { + @Override public final void glFlush () { gl.glFlush(); } - @Override - public final void glFogf(int pname, float param) - { - gl.glFogf( pname, param ); + @Override public final void glFogf (int pname, float param) { + gl.glFogf(pname, param); } - @Override - public final void glFogfv(int pname, FloatBuffer params) - { - gl.glFogfv( pname, params ); + @Override public final void glFogfv (int pname, FloatBuffer params) { + gl.glFogfv(pname, params); } - @Override - public final void glFogx(int pname, int param) - { - gl.glFogf( pname, FIXED_TO_FLOAT * param ); + @Override public final void glFogx (int pname, int param) { + gl.glFogf(pname, FIXED_TO_FLOAT * param); } - - @Override - public final void glFogxv(int pname, IntBuffer params) - { - if( tmp.length < params.capacity() ) - tmp = new float[params.capacity()]; + + @Override public final void glFogxv (int pname, IntBuffer params) { + if (tmp.length < params.capacity()) tmp = new float[params.capacity()]; int i = 0; - while( params.hasRemaining() ) + while (params.hasRemaining()) tmp[i++] = FIXED_TO_FLOAT * params.get(); - gl.glFogfv(pname, tmp, 0 ); + gl.glFogfv(pname, tmp, 0); } - @Override - public final void glFrontFace(int mode) - { - gl.glFrontFace( mode ); + @Override public final void glFrontFace (int mode) { + gl.glFrontFace(mode); } - @Override - public final void glFrustumf(float left, float right, float bottom, float top, - float zNear, float zFar) - { - gl.glFrustum( left, right, bottom, top, zNear, zFar ); + @Override public final void glFrustumf (float left, float right, float bottom, float top, float zNear, float zFar) { + gl.glFrustum(left, right, bottom, top, zNear, zFar); } - @Override - public final void glFrustumx(int left, int right, int bottom, int top, int zNear, - int zFar) - { - gl.glFrustum( FIXED_TO_FLOAT * left, FIXED_TO_FLOAT * right, FIXED_TO_FLOAT * bottom, FIXED_TO_FLOAT * top, FIXED_TO_FLOAT * zNear, FIXED_TO_FLOAT * zFar ); + @Override public final void glFrustumx (int left, int right, int bottom, int top, int zNear, int zFar) { + gl.glFrustum(FIXED_TO_FLOAT * left, FIXED_TO_FLOAT * right, FIXED_TO_FLOAT * bottom, FIXED_TO_FLOAT * top, FIXED_TO_FLOAT + * zNear, FIXED_TO_FLOAT * zFar); } - @Override - public final void glGenTextures(int n, IntBuffer textures) - { - gl.glGenTextures( n, textures ); + @Override public final void glGenTextures (int n, IntBuffer textures) { + gl.glGenTextures(n, textures); } - @Override - public final int glGetError() - { + @Override public final int glGetError () { return gl.glGetError(); } - @Override - public final void glGetIntegerv(int pname, IntBuffer params) - { - gl.glGetIntegerv( pname, params ); + @Override public final void glGetIntegerv (int pname, IntBuffer params) { + gl.glGetIntegerv(pname, params); } - @Override - public final String glGetString(int name) - { - return gl.glGetString( name ); + @Override public final String glGetString (int name) { + return gl.glGetString(name); } - @Override - public final void glHint(int target, int mode) - { - gl.glHint( target, mode ); + @Override public final void glHint (int target, int mode) { + gl.glHint(target, mode); } - @Override - public final void glLightModelf(int pname, float param) - { - gl.glLightModelf( pname, param ); + @Override public final void glLightModelf (int pname, float param) { + gl.glLightModelf(pname, param); } - @Override - public final void glLightModelfv(int pname, FloatBuffer params) - { - gl.glLightModelfv( pname, params ); + @Override public final void glLightModelfv (int pname, FloatBuffer params) { + gl.glLightModelfv(pname, params); } - @Override - public final void glLightModelx(int pname, int param) - { - gl.glLightModelf( pname, FIXED_TO_FLOAT * param ); + @Override public final void glLightModelx (int pname, int param) { + gl.glLightModelf(pname, FIXED_TO_FLOAT * param); } - @Override - public final void glLightModelxv(int pname, IntBuffer params) - { + @Override public final void glLightModelxv (int pname, IntBuffer params) { int i = 0; - while( params.hasRemaining() ) + while (params.hasRemaining()) tmp[i++] = FIXED_TO_FLOAT * params.get(); - gl.glLightModelfv( pname, tmp, 0 ); + gl.glLightModelfv(pname, tmp, 0); } - @Override - public final void glLightf(int light, int pname, float param) - { - gl.glLightf( light, pname, param ); + @Override public final void glLightf (int light, int pname, float param) { + gl.glLightf(light, pname, param); } - @Override - public final void glLightfv(int light, int pname, FloatBuffer params) - { - gl.glLightfv( light, pname, params ); + @Override public final void glLightfv (int light, int pname, FloatBuffer params) { + gl.glLightfv(light, pname, params); } - @Override - public final void glLightx(int light, int pname, int param) - { - gl.glLightf( light, pname, FIXED_TO_FLOAT * param ); + @Override public final void glLightx (int light, int pname, int param) { + gl.glLightf(light, pname, FIXED_TO_FLOAT * param); } - @Override - public final void glLightxv(int light, int pname, IntBuffer params) - { - if( tmp.length < params.capacity() ) - tmp = new float[params.capacity()]; + @Override public final void glLightxv (int light, int pname, IntBuffer params) { + if (tmp.length < params.capacity()) tmp = new float[params.capacity()]; int i = 0; - while( params.hasRemaining() ) + while (params.hasRemaining()) tmp[i++] = FIXED_TO_FLOAT * params.get(); - gl.glLightfv( light, pname, tmp, 0 ); + gl.glLightfv(light, pname, tmp, 0); } - @Override - public final void glLineWidth(float width) - { - gl.glLineWidth( width ); + @Override public final void glLineWidth (float width) { + gl.glLineWidth(width); } - @Override - public final void glLineWidthx(int width) - { - gl.glLineWidth( FIXED_TO_FLOAT * width ); + @Override public final void glLineWidthx (int width) { + gl.glLineWidth(FIXED_TO_FLOAT * width); } - @Override - public final void glLoadIdentity() - { + @Override public final void glLoadIdentity () { gl.glLoadIdentity(); } - @Override - public final void glLoadMatrixf(FloatBuffer m) - { - gl.glLoadMatrixf( m ); + @Override public final void glLoadMatrixf (FloatBuffer m) { + gl.glLoadMatrixf(m); } - @Override - public final void glLoadMatrixx(IntBuffer m) - { - if( tmp.length < m.capacity() ) - tmp = new float[m.capacity()]; + @Override public final void glLoadMatrixx (IntBuffer m) { + if (tmp.length < m.capacity()) tmp = new float[m.capacity()]; int i = 0; - while( m.hasRemaining() ) + while (m.hasRemaining()) tmp[i++] = FIXED_TO_FLOAT * m.get(); - - gl.glLoadMatrixf( tmp, 0 ); + + gl.glLoadMatrixf(tmp, 0); } - @Override - public final void glLogicOp(int opcode) - { - gl.glLogicOp( opcode ); + @Override public final void glLogicOp (int opcode) { + gl.glLogicOp(opcode); } - @Override - public final void glMaterialf(int face, int pname, float param) - { - gl.glMaterialf( face, pname, param ); + @Override public final void glMaterialf (int face, int pname, float param) { + gl.glMaterialf(face, pname, param); } - @Override - public final void glMaterialfv(int face, int pname, FloatBuffer params) - { - gl.glMaterialfv( face, pname, params ); + @Override public final void glMaterialfv (int face, int pname, FloatBuffer params) { + gl.glMaterialfv(face, pname, params); } - @Override - public final void glMaterialx(int face, int pname, int param) - { - gl.glMaterialf( face, pname, FIXED_TO_FLOAT * param ); + @Override public final void glMaterialx (int face, int pname, int param) { + gl.glMaterialf(face, pname, FIXED_TO_FLOAT * param); } - @Override - public final void glMaterialxv(int face, int pname, IntBuffer params) - { - if( tmp.length < params.capacity() ) - tmp = new float[params.capacity()]; + @Override public final void glMaterialxv (int face, int pname, IntBuffer params) { + if (tmp.length < params.capacity()) tmp = new float[params.capacity()]; int i = 0; - while( params.hasRemaining() ) + while (params.hasRemaining()) tmp[i++] = FIXED_TO_FLOAT * params.get(); - gl.glMaterialfv( face, pname, tmp, 0 ); + gl.glMaterialfv(face, pname, tmp, 0); } - @Override - public final void glMatrixMode(int mode) - { - gl.glMatrixMode( mode ); + @Override public final void glMatrixMode (int mode) { + gl.glMatrixMode(mode); } - @Override - public final void glMultMatrixf(FloatBuffer m) - { - gl.glMultMatrixf( m ); + @Override public final void glMultMatrixf (FloatBuffer m) { + gl.glMultMatrixf(m); } - @Override - public final void glMultMatrixx(IntBuffer m) - { - if( tmp.length < m.capacity() ) - tmp = new float[m.capacity()]; + @Override public final void glMultMatrixx (IntBuffer m) { + if (tmp.length < m.capacity()) tmp = new float[m.capacity()]; int i = 0; - while( m.hasRemaining() ) + while (m.hasRemaining()) tmp[i++] = FIXED_TO_FLOAT * m.get(); - gl.glMultMatrixf( tmp, 0 ); + gl.glMultMatrixf(tmp, 0); } - @Override - public final void glMultiTexCoord4f(int target, float s, float t, float r, float q) - { - gl.glMultiTexCoord4f( target, s, t, r, q ); + @Override public final void glMultiTexCoord4f (int target, float s, float t, float r, float q) { + gl.glMultiTexCoord4f(target, s, t, r, q); } - @Override - public final void glMultiTexCoord4x(int target, int s, int t, int r, int q) - { - gl.glMultiTexCoord4f( target, FIXED_TO_FLOAT * s, FIXED_TO_FLOAT * t, FIXED_TO_FLOAT * r, FIXED_TO_FLOAT * q ); + @Override public final void glMultiTexCoord4x (int target, int s, int t, int r, int q) { + gl.glMultiTexCoord4f(target, FIXED_TO_FLOAT * s, FIXED_TO_FLOAT * t, FIXED_TO_FLOAT * r, FIXED_TO_FLOAT * q); } - @Override - public final void glNormal3f(float nx, float ny, float nz) - { - gl.glNormal3f( nx, ny, nz ); + @Override public final void glNormal3f (float nx, float ny, float nz) { + gl.glNormal3f(nx, ny, nz); } - @Override - public final void glNormal3x(int nx, int ny, int nz) - { - gl.glNormal3f( FIXED_TO_FLOAT * nx, FIXED_TO_FLOAT * ny, FIXED_TO_FLOAT * nz ); + @Override public final void glNormal3x (int nx, int ny, int nz) { + gl.glNormal3f(FIXED_TO_FLOAT * nx, FIXED_TO_FLOAT * ny, FIXED_TO_FLOAT * nz); } - @Override - public final void glNormalPointer(int type, int stride, Buffer pointer) - { - if( type == GL10.GL_FIXED ) - { - convertFixedToFloatbuffer(pointer,normalBuffer, stride); - gl.glNormalPointer( GL10.GL_FLOAT, stride, normalBuffer ); - } - else - { - gl.glNormalPointer( type, stride, pointer ); + @Override public final void glNormalPointer (int type, int stride, Buffer pointer) { + if (type == GL10.GL_FIXED) { + convertFixedToFloatbuffer(pointer, normalBuffer, stride); + gl.glNormalPointer(GL10.GL_FLOAT, stride, normalBuffer); + } else { + gl.glNormalPointer(type, stride, pointer); } } - @Override - public final void glOrthof(float left, float right, float bottom, float top, - float zNear, float zFar) - { - gl.glOrtho( left, right, bottom, top, zNear, zFar ); + @Override public final void glOrthof (float left, float right, float bottom, float top, float zNear, float zFar) { + gl.glOrtho(left, right, bottom, top, zNear, zFar); } - @Override - public final void glOrthox(int left, int right, int bottom, int top, int zNear, - int zFar) - { - gl.glOrtho( FIXED_TO_FLOAT * left, FIXED_TO_FLOAT * right, FIXED_TO_FLOAT * bottom, FIXED_TO_FLOAT * top, FIXED_TO_FLOAT * zNear, FIXED_TO_FLOAT * zFar ); + @Override public final void glOrthox (int left, int right, int bottom, int top, int zNear, int zFar) { + gl.glOrtho(FIXED_TO_FLOAT * left, FIXED_TO_FLOAT * right, FIXED_TO_FLOAT * bottom, FIXED_TO_FLOAT * top, FIXED_TO_FLOAT + * zNear, FIXED_TO_FLOAT * zFar); } - @Override - public final void glPixelStorei(int pname, int param) - { - gl.glPixelStorei( pname, param ); + @Override public final void glPixelStorei (int pname, int param) { + gl.glPixelStorei(pname, param); } - @Override - public final void glPointSize(float size) - { - gl.glPointSize( size ); + @Override public final void glPointSize (float size) { + gl.glPointSize(size); } - @Override - public final void glPointSizex(int size) - { - gl.glPointSize( FIXED_TO_FLOAT * size ); + @Override public final void glPointSizex (int size) { + gl.glPointSize(FIXED_TO_FLOAT * size); } - @Override - public final void glPolygonOffset(float factor, float units) - { - gl.glPolygonOffset( factor, units ); + @Override public final void glPolygonOffset (float factor, float units) { + gl.glPolygonOffset(factor, units); } - @Override - public final void glPolygonOffsetx(int factor, int units) - { - gl.glPolygonOffset( FIXED_TO_FLOAT * factor, FIXED_TO_FLOAT * units ); + @Override public final void glPolygonOffsetx (int factor, int units) { + gl.glPolygonOffset(FIXED_TO_FLOAT * factor, FIXED_TO_FLOAT * units); } - @Override - public final void glPopMatrix() - { + @Override public final void glPopMatrix () { gl.glPopMatrix(); } - @Override - public final void glPushMatrix() - { + @Override public final void glPushMatrix () { gl.glPushMatrix(); } - @Override - public final void glReadPixels(int x, int y, int width, int height, int format, - int type, Buffer pixels) - { - gl.glReadPixels( x, y, width, height, format, type, pixels ); + @Override public final void glReadPixels (int x, int y, int width, int height, int format, int type, Buffer pixels) { + gl.glReadPixels(x, y, width, height, format, type, pixels); } - @Override - public final void glRotatef(float angle, float x, float y, float z) - { - gl.glRotatef( angle, x, y, z ); + @Override public final void glRotatef (float angle, float x, float y, float z) { + gl.glRotatef(angle, x, y, z); } - @Override - public final void glRotatex(int angle, int x, int y, int z) - { - gl.glRotatef( FIXED_TO_FLOAT * angle, FIXED_TO_FLOAT * x, FIXED_TO_FLOAT * y, FIXED_TO_FLOAT * z ); + @Override public final void glRotatex (int angle, int x, int y, int z) { + gl.glRotatef(FIXED_TO_FLOAT * angle, FIXED_TO_FLOAT * x, FIXED_TO_FLOAT * y, FIXED_TO_FLOAT * z); } - @Override - public final void glSampleCoverage(float value, boolean invert) - { - gl.glSampleCoverage( value, invert ); + @Override public final void glSampleCoverage (float value, boolean invert) { + gl.glSampleCoverage(value, invert); } - @Override - public final void glSampleCoveragex(int value, boolean invert) - { - gl.glSampleCoverage( FIXED_TO_FLOAT * value, invert ); + @Override public final void glSampleCoveragex (int value, boolean invert) { + gl.glSampleCoverage(FIXED_TO_FLOAT * value, invert); } - @Override - public final void glScalef(float x, float y, float z) - { - gl.glScalef( x, y, z ); + @Override public final void glScalef (float x, float y, float z) { + gl.glScalef(x, y, z); } - @Override - public final void glScalex(int x, int y, int z) - { - gl.glScalef( FIXED_TO_FLOAT * x, FIXED_TO_FLOAT * y, FIXED_TO_FLOAT * z ); + @Override public final void glScalex (int x, int y, int z) { + gl.glScalef(FIXED_TO_FLOAT * x, FIXED_TO_FLOAT * y, FIXED_TO_FLOAT * z); } - @Override - public final void glScissor(int x, int y, int width, int height) - { - gl.glScissor( x, y, width, height ); + @Override public final void glScissor (int x, int y, int width, int height) { + gl.glScissor(x, y, width, height); } - @Override - public final void glShadeModel(int mode) - { + @Override public final void glShadeModel (int mode) { gl.glShadeModel(mode); } - @Override - public final void glStencilFunc(int func, int ref, int mask) - { - gl.glStencilFunc( func, ref, mask ); + @Override public final void glStencilFunc (int func, int ref, int mask) { + gl.glStencilFunc(func, ref, mask); } - @Override - public final void glStencilMask(int mask) - { - gl.glStencilMask( mask ); + @Override public final void glStencilMask (int mask) { + gl.glStencilMask(mask); } - @Override - public final void glStencilOp(int fail, int zfail, int zpass) - { - gl.glStencilOp( fail, zfail, zpass ); + @Override public final void glStencilOp (int fail, int zfail, int zpass) { + gl.glStencilOp(fail, zfail, zpass); } - @Override - public final void glTexCoordPointer(int size, int type, int stride, Buffer pointer) - { - if( type == GL10.GL_FIXED ) - { - convertFixedToFloatbuffer(pointer,texCoordBuffer[activeTexture], stride); - gl.glTexCoordPointer( size, GL10.GL_FLOAT, stride, texCoordBuffer[activeTexture] ); - } - else - gl.glTexCoordPointer( size, type, stride, pointer ); + @Override public final void glTexCoordPointer (int size, int type, int stride, Buffer pointer) { + if (type == GL10.GL_FIXED) { + convertFixedToFloatbuffer(pointer, texCoordBuffer[activeTexture], stride); + gl.glTexCoordPointer(size, GL10.GL_FLOAT, stride, texCoordBuffer[activeTexture]); + } else + gl.glTexCoordPointer(size, type, stride, pointer); } - @Override - public final void glTexEnvf(int target, int pname, float param) - { - gl.glTexEnvf( target, pname, param ); + @Override public final void glTexEnvf (int target, int pname, float param) { + gl.glTexEnvf(target, pname, param); } - @Override - public final void glTexEnvfv(int target, int pname, FloatBuffer params) - { - gl.glTexEnvfv( target, pname, params ); + @Override public final void glTexEnvfv (int target, int pname, FloatBuffer params) { + gl.glTexEnvfv(target, pname, params); } - @Override - public final void glTexEnvx(int target, int pname, int param) - { - gl.glTexEnvf( target, pname, FIXED_TO_FLOAT * param ); + @Override public final void glTexEnvx (int target, int pname, int param) { + gl.glTexEnvf(target, pname, FIXED_TO_FLOAT * param); } - @Override - public final void glTexEnvxv(int target, int pname, IntBuffer params) - { - if( tmp.length < params.capacity() ) - tmp = new float[params.capacity()]; + @Override public final void glTexEnvxv (int target, int pname, IntBuffer params) { + if (tmp.length < params.capacity()) tmp = new float[params.capacity()]; int i = 0; - while( params.hasRemaining() ) + while (params.hasRemaining()) tmp[i++] = FIXED_TO_FLOAT * params.get(); - gl.glTexEnvfv( target, pname, tmp, 0 ); + gl.glTexEnvfv(target, pname, tmp, 0); } - @Override - public final void glTexImage2D(int target, int level, int internalformat, - int width, int height, int border, int format, int type, - Buffer pixels) - { - gl.glTexImage2D( target, level, internalformat, width, height, border, format, type, pixels ); + @Override public final void glTexImage2D (int target, int level, int internalformat, int width, int height, int border, + int format, int type, Buffer pixels) { + gl.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); } - @Override - public final void glTexParameterf(int target, int pname, float param) - { - gl.glTexParameterf( target, pname, param ); + @Override public final void glTexParameterf (int target, int pname, float param) { + gl.glTexParameterf(target, pname, param); } - @Override - public final void glTexParameterx(int target, int pname, int param) - { - gl.glTexParameterf( target, pname, FIXED_TO_FLOAT * param ); + @Override public final void glTexParameterx (int target, int pname, int param) { + gl.glTexParameterf(target, pname, FIXED_TO_FLOAT * param); } - @Override - public final void glTexSubImage2D(int target, int level, int xoffset, - int yoffset, int width, int height, int format, int type, - Buffer pixels) - { - gl.glTexSubImage2D( target, level, xoffset, yoffset, width, height, format, type, pixels ); + @Override public final void glTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, + int format, int type, Buffer pixels) { + gl.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); } - @Override - public final void glTranslatef(float x, float y, float z) - { - gl.glTranslatef( x, y, z ); + @Override public final void glTranslatef (float x, float y, float z) { + gl.glTranslatef(x, y, z); } - @Override - public final void glTranslatex(int x, int y, int z) - { - gl.glTranslatef( FIXED_TO_FLOAT * x, FIXED_TO_FLOAT * y, FIXED_TO_FLOAT * z ); + @Override public final void glTranslatex (int x, int y, int z) { + gl.glTranslatef(FIXED_TO_FLOAT * x, FIXED_TO_FLOAT * y, FIXED_TO_FLOAT * z); } - @Override - public final void glVertexPointer(int size, int type, int stride, Buffer pointer) - { - if( type == GL10.GL_FIXED ) - { - convertFixedToFloatbuffer(pointer,vertexBuffer, stride); - gl.glVertexPointer( size, GL10.GL_FLOAT, stride, vertexBuffer ); - } - else - gl.glVertexPointer( size, GL10.GL_FLOAT, stride, pointer ); + @Override public final void glVertexPointer (int size, int type, int stride, Buffer pointer) { + if (type == GL10.GL_FIXED) { + convertFixedToFloatbuffer(pointer, vertexBuffer, stride); + gl.glVertexPointer(size, GL10.GL_FLOAT, stride, vertexBuffer); + } else + gl.glVertexPointer(size, GL10.GL_FLOAT, stride, pointer); } - @Override - public final void glViewport(int x, int y, int width, int height) - { - gl.glViewport( x, y, width, height ); + @Override public final void glViewport (int x, int y, int width, int height) { + gl.glViewport(x, y, width, height); } - @Override - public final void glDeleteTextures(int n, int[] textures, int offset) - { - gl.glDeleteTextures( n, textures, offset ); + @Override public final void glDeleteTextures (int n, int[] textures, int offset) { + gl.glDeleteTextures(n, textures, offset); } - @Override - public final void glFogfv(int pname, float[] params, int offset) - { - gl.glFogfv( pname, params, offset ); + @Override public final void glFogfv (int pname, float[] params, int offset) { + gl.glFogfv(pname, params, offset); } - @Override - public final void glFogxv(int pname, int[] params, int offset) - { - if( params.length > tmp.length ) - tmp = new float[params.length]; - for( int i = 0; i + offset< params.length; i++ ) + @Override public final void glFogxv (int pname, int[] params, int offset) { + if (params.length > tmp.length) tmp = new float[params.length]; + for (int i = 0; i + offset < params.length; i++) tmp[i] = FIXED_TO_FLOAT * params[i + offset]; - gl.glFogfv( pname, tmp, 0 ); + gl.glFogfv(pname, tmp, 0); } - @Override - public final void glGenTextures(int n, int[] textures, int offset) - { - gl.glGenTextures( n, textures, offset ); + @Override public final void glGenTextures (int n, int[] textures, int offset) { + gl.glGenTextures(n, textures, offset); } - @Override - public final void glGetIntegerv(int pname, int[] params, int offset) - { - gl.glGetIntegerv( pname, params, offset ); + @Override public final void glGetIntegerv (int pname, int[] params, int offset) { + gl.glGetIntegerv(pname, params, offset); } - @Override - public final void glLightModelfv(int pname, float[] params, int offset) - { - gl.glLightModelfv( pname, params, offset ); + @Override public final void glLightModelfv (int pname, float[] params, int offset) { + gl.glLightModelfv(pname, params, offset); } - @Override - public final void glLightModelxv(int pname, int[] params, int offset) - { - if( params.length > tmp.length ) - tmp = new float[params.length]; - for( int i = 0; i + offset< params.length; i++ ) + @Override public final void glLightModelxv (int pname, int[] params, int offset) { + if (params.length > tmp.length) tmp = new float[params.length]; + for (int i = 0; i + offset < params.length; i++) tmp[i] = FIXED_TO_FLOAT * params[i + offset]; - gl.glLightModelfv( pname, tmp, 0 ); + gl.glLightModelfv(pname, tmp, 0); } - @Override - public final void glLightfv(int light, int pname, float[] params, int offset) - { - gl.glLightfv( light, pname, params, offset ); + @Override public final void glLightfv (int light, int pname, float[] params, int offset) { + gl.glLightfv(light, pname, params, offset); } - @Override - public final void glLightxv(int light, int pname, int[] params, int offset) - { - if( params.length > tmp.length ) - tmp = new float[params.length]; - for( int i = 0; i + offset < params.length; i++ ) + @Override public final void glLightxv (int light, int pname, int[] params, int offset) { + if (params.length > tmp.length) tmp = new float[params.length]; + for (int i = 0; i + offset < params.length; i++) tmp[i] = FIXED_TO_FLOAT * params[i + offset]; - gl.glLightfv( light, pname, tmp, 0 ); + gl.glLightfv(light, pname, tmp, 0); } - @Override - public final void glLoadMatrixf(float[] m, int offset) - { - gl.glLoadMatrixf( m, offset ); + @Override public final void glLoadMatrixf (float[] m, int offset) { + gl.glLoadMatrixf(m, offset); } - @Override - public final void glLoadMatrixx(int[] m, int offset) - { - if( m.length > tmp.length ) - tmp = new float[m.length]; - for( int i = 0; i + offset< m.length; i++ ) + @Override public final void glLoadMatrixx (int[] m, int offset) { + if (m.length > tmp.length) tmp = new float[m.length]; + for (int i = 0; i + offset < m.length; i++) tmp[i] = FIXED_TO_FLOAT * m[i + offset]; - gl.glLoadMatrixf( tmp, 0 ); + gl.glLoadMatrixf(tmp, 0); } - @Override - public final void glMaterialfv(int face, int pname, float[] params, int offset) - { - gl.glMaterialfv( face, pname, params, offset ); + @Override public final void glMaterialfv (int face, int pname, float[] params, int offset) { + gl.glMaterialfv(face, pname, params, offset); } - @Override - public final void glMaterialxv(int face, int pname, int[] params, int offset) - { - if( params.length > tmp.length ) - tmp = new float[params.length]; - for( int i = 0; i + offset < params.length; i++ ) + @Override public final void glMaterialxv (int face, int pname, int[] params, int offset) { + if (params.length > tmp.length) tmp = new float[params.length]; + for (int i = 0; i + offset < params.length; i++) tmp[i] = FIXED_TO_FLOAT * params[i + offset]; - gl.glMaterialfv( face, pname, tmp, 0 ); + gl.glMaterialfv(face, pname, tmp, 0); } - @Override - public final void glMultMatrixf(float[] m, int offset) - { - gl.glMultMatrixf( m, offset ); + @Override public final void glMultMatrixf (float[] m, int offset) { + gl.glMultMatrixf(m, offset); } - @Override - public final void glMultMatrixx(int[] m, int offset) - { - if( m.length > tmp.length ) - tmp = new float[m.length]; - for( int i = 0; i + offset< m.length; i++ ) + @Override public final void glMultMatrixx (int[] m, int offset) { + if (m.length > tmp.length) tmp = new float[m.length]; + for (int i = 0; i + offset < m.length; i++) tmp[i] = FIXED_TO_FLOAT * m[i + offset]; - gl.glMultMatrixf( tmp, 0 ); + gl.glMultMatrixf(tmp, 0); } - @Override - public final void glTexEnvfv(int target, int pname, float[] params, int offset) - { - gl.glTexEnvfv( target, pname, params, offset ); + @Override public final void glTexEnvfv (int target, int pname, float[] params, int offset) { + gl.glTexEnvfv(target, pname, params, offset); } - @Override - public final void glTexEnvxv(int target, int pname, int[] params, int offset) - { - if( params.length > tmp.length ) - tmp = new float[params.length]; - for( int i = 0; i + offset< params.length; i++ ) + @Override public final void glTexEnvxv (int target, int pname, int[] params, int offset) { + if (params.length > tmp.length) tmp = new float[params.length]; + for (int i = 0; i + offset < params.length; i++) tmp[i] = FIXED_TO_FLOAT * params[i + offset]; - gl.glTexEnvfv( target, pname, tmp, 0 ); - } - - @Override - public void glPolygonMode(int face, int mode) - { - gl.glPolygonMode( face, mode ); - } + gl.glTexEnvfv(target, pname, tmp, 0); + } + + @Override public void glPolygonMode (int face, int mode) { + gl.glPolygonMode(face, mode); + } } diff --git a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletGL11.java b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletGL11.java index bee4d803b..03d8c10ca 100644 --- a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletGL11.java +++ b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletGL11.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.applet; import java.nio.Buffer; @@ -25,453 +23,307 @@ import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.GL11; /** - * An implementation of the {@link GL11} interface based on Jogl. Fixed point - * vertex arrays are emulated. Some glGetXXX methods are not implemented. + * An implementation of the {@link GL11} interface based on Jogl. Fixed point vertex arrays are emulated. Some glGetXXX methods + * are not implemented. * * @author mzechner - * + * */ -public final class AppletGL11 extends AppletGL10 implements GL11 -{ +public final class AppletGL11 extends AppletGL10 implements GL11 { double tmpDouble[] = new double[1000]; float tmpFloat[] = new float[1000]; - - public AppletGL11(GL gl, boolean allowFixedPoint) - { + + public AppletGL11 (GL gl, boolean allowFixedPoint) { super(gl, allowFixedPoint); } - @Override - public void glBindBuffer(int target, int buffer) - { - gl.glBindBuffer( target, buffer ); + @Override public void glBindBuffer (int target, int buffer) { + gl.glBindBuffer(target, buffer); } - @Override - public void glBufferData(int target, int size, Buffer data, int usage) - { - gl.glBufferData( target, size, data, usage ); + @Override public void glBufferData (int target, int size, Buffer data, int usage) { + gl.glBufferData(target, size, data, usage); } - @Override - public void glBufferSubData(int target, int offset, int size, Buffer data) - { - gl.glBufferSubData( target, offset, size, data ); + @Override public void glBufferSubData (int target, int offset, int size, Buffer data) { + gl.glBufferSubData(target, offset, size, data); } - @Override - public void glClipPlanef(int plane, float[] equation, int offset) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glClipPlanef (int plane, float[] equation, int offset) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glClipPlanef(int plane, FloatBuffer equation) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glClipPlanef (int plane, FloatBuffer equation) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glClipPlanex(int plane, int[] equation, int offset) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glClipPlanex (int plane, int[] equation, int offset) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glClipPlanex(int plane, IntBuffer equation) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glClipPlanex (int plane, IntBuffer equation) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glColor4ub(byte red, byte green, byte blue, byte alpha) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glColor4ub (byte red, byte green, byte blue, byte alpha) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glDeleteBuffers(int n, int[] buffers, int offset) - { - gl.glDeleteBuffers( n, buffers, offset ); + @Override public void glDeleteBuffers (int n, int[] buffers, int offset) { + gl.glDeleteBuffers(n, buffers, offset); } - @Override - public void glDeleteBuffers(int n, IntBuffer buffers) - { - gl.glDeleteBuffers( n, buffers ); + @Override public void glDeleteBuffers (int n, IntBuffer buffers) { + gl.glDeleteBuffers(n, buffers); } - @Override - public void glGenBuffers(int n, int[] buffers, int offset) - { - gl.glGenBuffers( n, buffers, offset ); + @Override public void glGenBuffers (int n, int[] buffers, int offset) { + gl.glGenBuffers(n, buffers, offset); } - @Override - public void glGenBuffers(int n, IntBuffer buffers) - { - gl.glGenBuffers( n, buffers ); + @Override public void glGenBuffers (int n, IntBuffer buffers) { + gl.glGenBuffers(n, buffers); } - @Override - public void glGetBooleanv(int pname, boolean[] params, int offset) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetBooleanv (int pname, boolean[] params, int offset) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetBooleanv(int pname, IntBuffer params) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetBooleanv (int pname, IntBuffer params) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetBufferParameteriv(int target, int pname, int[] params, int offset) - { - gl.glGetBufferParameteriv( target, pname, params, offset ); + @Override public void glGetBufferParameteriv (int target, int pname, int[] params, int offset) { + gl.glGetBufferParameteriv(target, pname, params, offset); } - @Override - public void glGetBufferParameteriv(int target, int pname, IntBuffer params) - { - gl.glGetBufferParameteriv(target, pname, params ); + @Override public void glGetBufferParameteriv (int target, int pname, IntBuffer params) { + gl.glGetBufferParameteriv(target, pname, params); } - @Override - public void glGetClipPlanef(int pname, float[] eqn, int offset) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetClipPlanef (int pname, float[] eqn, int offset) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetClipPlanef(int pname, FloatBuffer eqn) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetClipPlanef (int pname, FloatBuffer eqn) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetClipPlanex(int pname, int[] eqn, int offset) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetClipPlanex (int pname, int[] eqn, int offset) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetClipPlanex(int pname, IntBuffer eqn) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetClipPlanex (int pname, IntBuffer eqn) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetFixedv(int pname, int[] params, int offset) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetFixedv (int pname, int[] params, int offset) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetFixedv(int pname, IntBuffer params) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetFixedv (int pname, IntBuffer params) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetFloatv(int pname, float[] params, int offset) - { - gl.glGetFloatv( pname, params, offset ); + @Override public void glGetFloatv (int pname, float[] params, int offset) { + gl.glGetFloatv(pname, params, offset); } - @Override - public void glGetFloatv(int pname, FloatBuffer params) - { - gl.glGetFloatv( pname, params ); + @Override public void glGetFloatv (int pname, FloatBuffer params) { + gl.glGetFloatv(pname, params); } - @Override - public void glGetLightfv(int light, int pname, float[] params, int offset) - { - gl.glGetLightfv( light, pname, params, offset ); + @Override public void glGetLightfv (int light, int pname, float[] params, int offset) { + gl.glGetLightfv(light, pname, params, offset); } - @Override - public void glGetLightfv(int light, int pname, FloatBuffer params) - { - gl.glGetLightfv( light, pname, params ); + @Override public void glGetLightfv (int light, int pname, FloatBuffer params) { + gl.glGetLightfv(light, pname, params); } - @Override - public void glGetLightxv(int light, int pname, int[] params, int offset) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetLightxv (int light, int pname, int[] params, int offset) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetLightxv(int light, int pname, IntBuffer params) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetLightxv (int light, int pname, IntBuffer params) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetMaterialfv(int face, int pname, float[] params, int offset) - { - gl.glGetMaterialfv( face, pname, params, offset ); + @Override public void glGetMaterialfv (int face, int pname, float[] params, int offset) { + gl.glGetMaterialfv(face, pname, params, offset); } - @Override - public void glGetMaterialfv(int face, int pname, FloatBuffer params) - { - gl.glGetMaterialfv( face, pname, params ); + @Override public void glGetMaterialfv (int face, int pname, FloatBuffer params) { + gl.glGetMaterialfv(face, pname, params); } - @Override - public void glGetMaterialxv(int face, int pname, int[] params, int offset) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetMaterialxv (int face, int pname, int[] params, int offset) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetMaterialxv(int face, int pname, IntBuffer params) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetMaterialxv (int face, int pname, IntBuffer params) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetPointerv(int pname, Buffer[] params) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetPointerv (int pname, Buffer[] params) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetTexEnviv(int env, int pname, int[] params, int offset) - { - gl.glGetTexEnviv( env, pname, params, offset ); + @Override public void glGetTexEnviv (int env, int pname, int[] params, int offset) { + gl.glGetTexEnviv(env, pname, params, offset); } - @Override - public void glGetTexEnviv(int env, int pname, IntBuffer params) - { - gl.glGetTexEnviv( env, pname, params ); + @Override public void glGetTexEnviv (int env, int pname, IntBuffer params) { + gl.glGetTexEnviv(env, pname, params); } - @Override - public void glGetTexEnvxv(int env, int pname, int[] params, int offset) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetTexEnvxv (int env, int pname, int[] params, int offset) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetTexEnvxv(int env, int pname, IntBuffer params) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetTexEnvxv (int env, int pname, IntBuffer params) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetTexParameterfv(int target, int pname, float[] params, int offset) - { - gl.glGetTexParameterfv( target, pname, params, offset ); + @Override public void glGetTexParameterfv (int target, int pname, float[] params, int offset) { + gl.glGetTexParameterfv(target, pname, params, offset); } - @Override - public void glGetTexParameterfv(int target, int pname, FloatBuffer params) - { - gl.glGetTexParameterfv( target, pname, params ); + @Override public void glGetTexParameterfv (int target, int pname, FloatBuffer params) { + gl.glGetTexParameterfv(target, pname, params); } - @Override - public void glGetTexParameteriv(int target, int pname, int[] params, int offset) - { - gl.glGetTexParameteriv( target, pname, params, offset ); + @Override public void glGetTexParameteriv (int target, int pname, int[] params, int offset) { + gl.glGetTexParameteriv(target, pname, params, offset); } - @Override - public void glGetTexParameteriv(int target, int pname, IntBuffer params) - { - gl.glGetTexParameteriv( target, pname, params ); + @Override public void glGetTexParameteriv (int target, int pname, IntBuffer params) { + gl.glGetTexParameteriv(target, pname, params); } - @Override - public void glGetTexParameterxv(int target, int pname, int[] params, int offset) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetTexParameterxv (int target, int pname, int[] params, int offset) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetTexParameterxv(int target, int pname, IntBuffer params) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetTexParameterxv (int target, int pname, IntBuffer params) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public boolean glIsBuffer(int buffer) - { - return gl.glIsBuffer( buffer ); + @Override public boolean glIsBuffer (int buffer) { + return gl.glIsBuffer(buffer); } - @Override - public boolean glIsEnabled(int cap) - { - return gl.glIsEnabled( cap ); + @Override public boolean glIsEnabled (int cap) { + return gl.glIsEnabled(cap); } - @Override - public boolean glIsTexture(int texture) - { - return gl.glIsTexture( texture ); + @Override public boolean glIsTexture (int texture) { + return gl.glIsTexture(texture); } - @Override - public void glPointParameterf(int pname, float param) - { - gl.glPointParameterf( pname, param ); + @Override public void glPointParameterf (int pname, float param) { + gl.glPointParameterf(pname, param); } - @Override - public void glPointParameterfv(int pname, float[] params, int offset) - { - gl.glPointParameterfv( pname, params, offset ); + @Override public void glPointParameterfv (int pname, float[] params, int offset) { + gl.glPointParameterfv(pname, params, offset); } - @Override - public void glPointParameterfv(int pname, FloatBuffer params) - { - gl.glPointParameterfv( pname, params ); + @Override public void glPointParameterfv (int pname, FloatBuffer params) { + gl.glPointParameterfv(pname, params); } - @Override - public void glPointParameterx(int pname, int param) - { - gl.glPointParameterf(pname, FIXED_TO_FLOAT * param ); + @Override public void glPointParameterx (int pname, int param) { + gl.glPointParameterf(pname, FIXED_TO_FLOAT * param); } - @Override - public void glPointParameterxv(int pname, int[] params, int offset) - { - if( tmpFloat.length < params.length ) - tmpFloat = new float[params.length]; - for( int i = 0; i < params.length; i++ ) + @Override public void glPointParameterxv (int pname, int[] params, int offset) { + if (tmpFloat.length < params.length) tmpFloat = new float[params.length]; + for (int i = 0; i < params.length; i++) tmpFloat[i] = FIXED_TO_FLOAT * params[i]; - gl.glPointParameterfv( pname, tmpFloat, offset ); + gl.glPointParameterfv(pname, tmpFloat, offset); } - @Override - public void glPointParameterxv(int pname, IntBuffer params) - { - if( tmpFloat.length < params.capacity() ) - tmpFloat = new float[params.capacity()]; + @Override public void glPointParameterxv (int pname, IntBuffer params) { + if (tmpFloat.length < params.capacity()) tmpFloat = new float[params.capacity()]; int i = 0; - while( params.hasRemaining() ) + while (params.hasRemaining()) tmpFloat[i] = FIXED_TO_FLOAT * params.get(); - gl.glPointParameterfv( pname, tmpFloat, 0 ); + gl.glPointParameterfv(pname, tmpFloat, 0); } - @Override - public void glPointSizePointerOES(int type, int stride, Buffer pointer) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glPointSizePointerOES (int type, int stride, Buffer pointer) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glTexEnvi(int target, int pname, int param) - { - gl.glTexEnvi( target, pname, param ); + @Override public void glTexEnvi (int target, int pname, int param) { + gl.glTexEnvi(target, pname, param); } - @Override - public void glTexEnviv(int target, int pname, int[] params, int offset) - { - gl.glTexEnviv( target, pname, params, offset ); + @Override public void glTexEnviv (int target, int pname, int[] params, int offset) { + gl.glTexEnviv(target, pname, params, offset); } - @Override - public void glTexEnviv(int target, int pname, IntBuffer params) - { - gl.glTexEnviv( target, pname, params ); + @Override public void glTexEnviv (int target, int pname, IntBuffer params) { + gl.glTexEnviv(target, pname, params); } - @Override - public void glTexParameterfv(int target, int pname, float[] params, int offset) - { - gl.glTexParameterfv( target, pname, params, offset ); + @Override public void glTexParameterfv (int target, int pname, float[] params, int offset) { + gl.glTexParameterfv(target, pname, params, offset); } - @Override - public void glTexParameterfv(int target, int pname, FloatBuffer params) - { - gl.glTexParameterfv( target, pname, params ); + @Override public void glTexParameterfv (int target, int pname, FloatBuffer params) { + gl.glTexParameterfv(target, pname, params); } - @Override - public void glTexParameteri(int target, int pname, int param) - { - gl.glTexParameteri( target, pname, param ); + @Override public void glTexParameteri (int target, int pname, int param) { + gl.glTexParameteri(target, pname, param); } - @Override - public void glTexParameteriv(int target, int pname, int[] params, int offset) - { - gl.glTexParameteriv( target, pname, params, offset ); + @Override public void glTexParameteriv (int target, int pname, int[] params, int offset) { + gl.glTexParameteriv(target, pname, params, offset); } - @Override - public void glTexParameteriv(int target, int pname, IntBuffer params) - { - gl.glTexParameteriv( target, pname, params ); + @Override public void glTexParameteriv (int target, int pname, IntBuffer params) { + gl.glTexParameteriv(target, pname, params); } - @Override - public void glTexParameterxv(int target, int pname, int[] params, int offset) - { - if( tmpFloat.length < params.length ) - tmpFloat = new float[params.length]; - for( int i = 0; i < params.length; i++ ) + @Override public void glTexParameterxv (int target, int pname, int[] params, int offset) { + if (tmpFloat.length < params.length) tmpFloat = new float[params.length]; + for (int i = 0; i < params.length; i++) tmpFloat[i] = params[i]; - gl.glTexParameterfv( target, pname, tmpFloat, offset ); + gl.glTexParameterfv(target, pname, tmpFloat, offset); } - @Override - public void glTexParameterxv(int target, int pname, IntBuffer params) - { - if( tmpFloat.length < params.capacity() ) - tmpFloat = new float[params.capacity()]; + @Override public void glTexParameterxv (int target, int pname, IntBuffer params) { + if (tmpFloat.length < params.capacity()) tmpFloat = new float[params.capacity()]; int i = 0; - while( params.hasRemaining() ) + while (params.hasRemaining()) tmpFloat[i] = FIXED_TO_FLOAT * params.get(); - gl.glTexParameterfv( target, pname, tmpFloat, 0 ); + gl.glTexParameterfv(target, pname, tmpFloat, 0); } - @Override - public void glColorPointer(int size, int type, int stride, int pointer) - { - if( type == GL10.GL_FIXED ) - type = GL10.GL_FLOAT; - gl.glColorPointer( size, type, stride, pointer ); + @Override public void glColorPointer (int size, int type, int stride, int pointer) { + if (type == GL10.GL_FIXED) type = GL10.GL_FLOAT; + gl.glColorPointer(size, type, stride, pointer); } - @Override - public void glNormalPointer( int type, int stride, int pointer) - { - if( type == GL10.GL_FIXED ) - type = GL10.GL_FLOAT; - gl.glNormalPointer( type, stride, pointer ); + @Override public void glNormalPointer (int type, int stride, int pointer) { + if (type == GL10.GL_FIXED) type = GL10.GL_FLOAT; + gl.glNormalPointer(type, stride, pointer); } - @Override - public void glTexCoordPointer(int size, int type, int stride, int pointer) - { - if( type == GL10.GL_FIXED ) - type = GL10.GL_FLOAT; - gl.glTexCoordPointer( size, type, stride, pointer ); + @Override public void glTexCoordPointer (int size, int type, int stride, int pointer) { + if (type == GL10.GL_FIXED) type = GL10.GL_FLOAT; + gl.glTexCoordPointer(size, type, stride, pointer); } - @Override - public void glVertexPointer(int size, int type, int stride, int pointer) - { - if( type == GL10.GL_FIXED ) - type = GL10.GL_FLOAT; - gl.glVertexPointer( size, type, stride, pointer ); + @Override public void glVertexPointer (int size, int type, int stride, int pointer) { + if (type == GL10.GL_FIXED) type = GL10.GL_FLOAT; + gl.glVertexPointer(size, type, stride, pointer); } - - @Override - public void glDrawElements( int mode, int count, int type, int indices ) - { - gl.glDrawElements( mode, count, type, indices ); + + @Override public void glDrawElements (int mode, int count, int type, int indices) { + gl.glDrawElements(mode, count, type, indices); } } diff --git a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletGL20.java b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletGL20.java index 1bdee0fba..305416013 100644 --- a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletGL20.java +++ b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletGL20.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.applet; import java.nio.Buffer; @@ -26,927 +24,619 @@ import javax.media.opengl.GL; import com.badlogic.gdx.graphics.GL20; /** - * An implementation of the {@link GL20} interface based on Jogl. Note that - * Jogl shaders and OpenGL ES shaders will not be 100% compatible. Some glGetXXX - * methods are not implemented. + * An implementation of the {@link GL20} interface based on Jogl. Note that Jogl shaders and OpenGL ES shaders will not be 100% + * compatible. Some glGetXXX methods are not implemented. * * @author mzechner - * + * */ -final class AppletGL20 implements GL20 -{ +final class AppletGL20 implements GL20 { private final GL gl; - public AppletGL20( GL gl ) - { + public AppletGL20 (GL gl) { this.gl = gl; } - - @Override - public void glActiveTexture(int texture) - { - gl.glActiveTexture( texture ); + + @Override public void glActiveTexture (int texture) { + gl.glActiveTexture(texture); } - @Override - public void glAttachShader(int program, int shader) - { - gl.glAttachShader( program, shader ); + @Override public void glAttachShader (int program, int shader) { + gl.glAttachShader(program, shader); } - @Override - public void glBindAttribLocation(int program, int index, String name) - { - gl.glBindAttribLocation( program, index, name ); + @Override public void glBindAttribLocation (int program, int index, String name) { + gl.glBindAttribLocation(program, index, name); } - @Override - public void glBindBuffer(int target, int buffer) - { - gl.glBindBuffer( target, buffer ); + @Override public void glBindBuffer (int target, int buffer) { + gl.glBindBuffer(target, buffer); } - @Override - public void glBindFramebuffer(int target, int framebuffer) - { - gl.glBindFramebufferEXT( target, framebuffer ); + @Override public void glBindFramebuffer (int target, int framebuffer) { + gl.glBindFramebufferEXT(target, framebuffer); } - @Override - public void glBindRenderbuffer(int target, int renderbuffer) - { - gl.glBindRenderbufferEXT( target, renderbuffer ); + @Override public void glBindRenderbuffer (int target, int renderbuffer) { + gl.glBindRenderbufferEXT(target, renderbuffer); } - @Override - public void glBindTexture(int target, int texture) - { - gl.glBindTexture( target, texture ); + @Override public void glBindTexture (int target, int texture) { + gl.glBindTexture(target, texture); } - @Override - public void glBlendColor(float red, float green, float blue, float alpha) - { - gl.glBlendColor( red, green, blue, alpha ); + @Override public void glBlendColor (float red, float green, float blue, float alpha) { + gl.glBlendColor(red, green, blue, alpha); } - @Override - public void glBlendEquation(int mode) - { - gl.glBlendEquation( mode ); + @Override public void glBlendEquation (int mode) { + gl.glBlendEquation(mode); } - @Override - public void glBlendEquationSeparate(int modeRGB, int modeAlpha) - { - gl.glBlendEquationSeparate( modeRGB, modeAlpha ); + @Override public void glBlendEquationSeparate (int modeRGB, int modeAlpha) { + gl.glBlendEquationSeparate(modeRGB, modeAlpha); } - @Override - public void glBlendFunc(int sfactor, int dfactor) - { - gl.glBlendFunc( sfactor, dfactor ); + @Override public void glBlendFunc (int sfactor, int dfactor) { + gl.glBlendFunc(sfactor, dfactor); } - @Override - public void glBlendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) - { - gl.glBlendFuncSeparate( srcRGB, dstRGB, srcAlpha, dstAlpha ); + @Override public void glBlendFuncSeparate (int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) { + gl.glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha); } - @Override - public void glBufferData(int target, int size, Buffer data, int usage) - { - gl.glBufferData( target, size, data, usage ); + @Override public void glBufferData (int target, int size, Buffer data, int usage) { + gl.glBufferData(target, size, data, usage); } - @Override - public void glBufferSubData(int target, int offset, int size, Buffer data) - { - gl.glBufferSubData( target, offset, size, data ); + @Override public void glBufferSubData (int target, int offset, int size, Buffer data) { + gl.glBufferSubData(target, offset, size, data); } - @Override - public int glCheckFramebufferStatus(int target) - { - return gl.glCheckFramebufferStatusEXT( target ); + @Override public int glCheckFramebufferStatus (int target) { + return gl.glCheckFramebufferStatusEXT(target); } - @Override - public void glClear(int mask) - { - gl.glClear( mask ); + @Override public void glClear (int mask) { + gl.glClear(mask); } - @Override - public void glClearColor(float red, float green, float blue, float alpha) - { - gl.glClearColor( red, green, blue, alpha ); + @Override public void glClearColor (float red, float green, float blue, float alpha) { + gl.glClearColor(red, green, blue, alpha); } - @Override - public void glClearDepthf(float depth) - { - gl.glClearDepth( depth ); + @Override public void glClearDepthf (float depth) { + gl.glClearDepth(depth); } - @Override - public void glClearStencil(int s) - { - gl.glClearStencil( s ); + @Override public void glClearStencil (int s) { + gl.glClearStencil(s); } - @Override - public void glColorMask(boolean red, boolean green, boolean blue, boolean alpha) - { - gl.glColorMask( red, green, blue, alpha ); + @Override public void glColorMask (boolean red, boolean green, boolean blue, boolean alpha) { + gl.glColorMask(red, green, blue, alpha); } - @Override - public void glCompileShader(int shader) - { - gl.glCompileShader( shader ); + @Override public void glCompileShader (int shader) { + gl.glCompileShader(shader); } - @Override - public void glCompressedTexImage2D(int target, int level, - int internalformat, int width, int height, int border, - int imageSize, Buffer data) - { - gl.glCompressedTexImage2D( target, level, internalformat, width, height, border, imageSize, data ); + @Override public void glCompressedTexImage2D (int target, int level, int internalformat, int width, int height, int border, + int imageSize, Buffer data) { + gl.glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); } - @Override - public void glCompressedTexSubImage2D(int target, int level, int xoffset, - int yoffset, int width, int height, int format, int imageSize, - Buffer data) - { - gl.glCompressedTexSubImage2D( target, level, xoffset, yoffset, width, height, format, imageSize, data ); + @Override public void glCompressedTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, + int format, int imageSize, Buffer data) { + gl.glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); } - @Override - public void glCopyTexImage2D(int target, int level, int internalformat, - int x, int y, int width, int height, int border) - { - gl.glCopyTexImage2D( target, level, internalformat, x, y, width, height, border ); + @Override public void glCopyTexImage2D (int target, int level, int internalformat, int x, int y, int width, int height, + int border) { + gl.glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); } - @Override - public void glCopyTexSubImage2D(int target, int level, int xoffset, - int yoffset, int x, int y, int width, int height) - { - gl.glCopyTexSubImage2D( target, level, xoffset, yoffset, x, y, width, height ); + @Override public void glCopyTexSubImage2D (int target, int level, int xoffset, int yoffset, int x, int y, int width, int height) { + gl.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); } - @Override - public int glCreateProgram() - { + @Override public int glCreateProgram () { return gl.glCreateProgram(); } - @Override - public int glCreateShader(int type) - { - return gl.glCreateShader( type ); + @Override public int glCreateShader (int type) { + return gl.glCreateShader(type); } - @Override - public void glCullFace(int mode) - { - gl.glCullFace( mode ); + @Override public void glCullFace (int mode) { + gl.glCullFace(mode); } - @Override - public void glDeleteBuffers(int n, IntBuffer buffers) - { - gl.glDeleteBuffers( n, buffers ); + @Override public void glDeleteBuffers (int n, IntBuffer buffers) { + gl.glDeleteBuffers(n, buffers); } - @Override - public void glDeleteFramebuffers(int n, IntBuffer framebuffers) - { - gl.glDeleteFramebuffersEXT( n, framebuffers ); + @Override public void glDeleteFramebuffers (int n, IntBuffer framebuffers) { + gl.glDeleteFramebuffersEXT(n, framebuffers); } - @Override - public void glDeleteProgram(int program) - { - gl.glDeleteProgram( program ); - } + @Override public void glDeleteProgram (int program) { + gl.glDeleteProgram(program); + } - @Override - public void glDeleteRenderbuffers(int n, IntBuffer renderbuffers) - { - gl.glDeleteRenderbuffersEXT( n, renderbuffers ); + @Override public void glDeleteRenderbuffers (int n, IntBuffer renderbuffers) { + gl.glDeleteRenderbuffersEXT(n, renderbuffers); } - @Override - public void glDeleteShader(int shader) - { - gl.glDeleteShader( shader ); + @Override public void glDeleteShader (int shader) { + gl.glDeleteShader(shader); } - @Override - public void glDeleteTextures(int n, IntBuffer textures) - { - gl.glDeleteTextures( n, textures ); + @Override public void glDeleteTextures (int n, IntBuffer textures) { + gl.glDeleteTextures(n, textures); } - @Override - public void glDepthFunc(int func) - { - gl.glDepthFunc( func ); + @Override public void glDepthFunc (int func) { + gl.glDepthFunc(func); } - @Override - public void glDepthMask(boolean flag) - { - gl.glDepthMask( flag ); + @Override public void glDepthMask (boolean flag) { + gl.glDepthMask(flag); } - @Override - public void glDepthRangef(float zNear, float zFar) - { - gl.glDepthRange( zNear, zFar ); + @Override public void glDepthRangef (float zNear, float zFar) { + gl.glDepthRange(zNear, zFar); } - @Override - public void glDetachShader(int program, int shader) - { - gl.glDetachShader( program, shader ); + @Override public void glDetachShader (int program, int shader) { + gl.glDetachShader(program, shader); } - @Override - public void glDisable(int cap) - { - gl.glDisable( cap ); + @Override public void glDisable (int cap) { + gl.glDisable(cap); } - @Override - public void glDisableVertexAttribArray(int index) - { - gl.glDisableVertexAttribArray( index ); + @Override public void glDisableVertexAttribArray (int index) { + gl.glDisableVertexAttribArray(index); } - @Override - public void glDrawArrays(int mode, int first, int count) - { - gl.glDrawArrays( mode, first, count ); + @Override public void glDrawArrays (int mode, int first, int count) { + gl.glDrawArrays(mode, first, count); } - @Override - public void glDrawElements(int mode, int count, int type, Buffer indices) - { - gl.glDrawElements( mode, count, type, indices ); + @Override public void glDrawElements (int mode, int count, int type, Buffer indices) { + gl.glDrawElements(mode, count, type, indices); } - @Override - public void glEnable(int cap) - { - gl.glEnable( cap ); + @Override public void glEnable (int cap) { + gl.glEnable(cap); } - @Override - public void glEnableVertexAttribArray(int index) - { - gl.glEnableVertexAttribArray( index ); + @Override public void glEnableVertexAttribArray (int index) { + gl.glEnableVertexAttribArray(index); } - @Override - public void glFinish() - { - gl.glFinish( ); + @Override public void glFinish () { + gl.glFinish(); } - @Override - public void glFlush() - { - gl.glFlush( ); + @Override public void glFlush () { + gl.glFlush(); } - @Override - public void glFramebufferRenderbuffer(int target, int attachment, - int renderbuffertarget, int renderbuffer) - { - gl.glFramebufferRenderbufferEXT( target, attachment, renderbuffertarget, renderbuffer ); + @Override public void glFramebufferRenderbuffer (int target, int attachment, int renderbuffertarget, int renderbuffer) { + gl.glFramebufferRenderbufferEXT(target, attachment, renderbuffertarget, renderbuffer); } - @Override - public void glFramebufferTexture2D(int target, int attachment, - int textarget, int texture, int level) - { - gl.glFramebufferTexture2DEXT( target, attachment, textarget, texture, level ); + @Override public void glFramebufferTexture2D (int target, int attachment, int textarget, int texture, int level) { + gl.glFramebufferTexture2DEXT(target, attachment, textarget, texture, level); } - @Override - public void glFrontFace(int mode) - { - gl.glFrontFace( mode ); + @Override public void glFrontFace (int mode) { + gl.glFrontFace(mode); } - @Override - public void glGenBuffers(int n, IntBuffer buffers) - { - gl.glGenBuffers( n, buffers ); + @Override public void glGenBuffers (int n, IntBuffer buffers) { + gl.glGenBuffers(n, buffers); } - @Override - public void glGenFramebuffers(int n, IntBuffer framebuffers) - { - gl.glGenFramebuffersEXT( n, framebuffers ); + @Override public void glGenFramebuffers (int n, IntBuffer framebuffers) { + gl.glGenFramebuffersEXT(n, framebuffers); } - @Override - public void glGenRenderbuffers(int n, IntBuffer renderbuffers) - { - gl.glGenRenderbuffersEXT( n, renderbuffers ); + @Override public void glGenRenderbuffers (int n, IntBuffer renderbuffers) { + gl.glGenRenderbuffersEXT(n, renderbuffers); } - @Override - public void glGenTextures(int n, IntBuffer textures) - { - gl.glGenTextures( n, textures ); + @Override public void glGenTextures (int n, IntBuffer textures) { + gl.glGenTextures(n, textures); } - @Override - public void glGenerateMipmap(int target) - { - gl.glGenerateMipmapEXT( target ); + @Override public void glGenerateMipmap (int target) { + gl.glGenerateMipmapEXT(target); } - @Override - public String glGetActiveAttrib(int program, int index, IntBuffer size, - Buffer type) - { - throw new UnsupportedOperationException( "not implemented" ); // FIXME + @Override public String glGetActiveAttrib (int program, int index, IntBuffer size, Buffer type) { + throw new UnsupportedOperationException("not implemented"); // FIXME } - @Override - public String glGetActiveUniform(int program, int index, IntBuffer size, - Buffer type) { - throw new UnsupportedOperationException( "not implemented" ); // FIXME + @Override public String glGetActiveUniform (int program, int index, IntBuffer size, Buffer type) { + throw new UnsupportedOperationException("not implemented"); // FIXME } - @Override - public void glGetAttachedShaders(int program, int maxcount, Buffer count, - IntBuffer shaders) - { - gl.glGetAttachedShaders( program, maxcount, (IntBuffer)count, shaders ); + @Override public void glGetAttachedShaders (int program, int maxcount, Buffer count, IntBuffer shaders) { + gl.glGetAttachedShaders(program, maxcount, (IntBuffer)count, shaders); } - @Override - public int glGetAttribLocation(int program, String name) - { - return gl.glGetAttribLocation( program, name ); + @Override public int glGetAttribLocation (int program, String name) { + return gl.glGetAttribLocation(program, name); } - @Override - public void glGetBooleanv(int pname, Buffer params) - { - throw new UnsupportedOperationException( "not implemented" ); // FIXME + @Override public void glGetBooleanv (int pname, Buffer params) { + throw new UnsupportedOperationException("not implemented"); // FIXME } - @Override - public void glGetBufferParameteriv(int target, int pname, IntBuffer params) - { - gl.glGetBufferParameteriv( target, pname, params ); + @Override public void glGetBufferParameteriv (int target, int pname, IntBuffer params) { + gl.glGetBufferParameteriv(target, pname, params); } - @Override - public int glGetError() - { + @Override public int glGetError () { return gl.glGetError(); } - @Override - public void glGetFloatv(int pname, FloatBuffer params) - { - gl.glGetFloatv( pname, params ); + @Override public void glGetFloatv (int pname, FloatBuffer params) { + gl.glGetFloatv(pname, params); } - @Override - public void glGetFramebufferAttachmentParameteriv(int target, - int attachment, int pname, IntBuffer params) - { - gl.glGetFramebufferAttachmentParameterivEXT( target, attachment, pname, params ); + @Override public void glGetFramebufferAttachmentParameteriv (int target, int attachment, int pname, IntBuffer params) { + gl.glGetFramebufferAttachmentParameterivEXT(target, attachment, pname, params); } - @Override - public void glGetIntegerv(int pname, IntBuffer params) - { - gl.glGetIntegerv( pname, params ); + @Override public void glGetIntegerv (int pname, IntBuffer params) { + gl.glGetIntegerv(pname, params); } - @Override - public String glGetProgramInfoLog(int program) - { - ByteBuffer buffer = ByteBuffer.allocateDirect( 1024*10 ); + @Override public String glGetProgramInfoLog (int program) { + ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 10); buffer.order(ByteOrder.nativeOrder()); - ByteBuffer tmp = ByteBuffer.allocateDirect( 4 ); + ByteBuffer tmp = ByteBuffer.allocateDirect(4); tmp.order(ByteOrder.nativeOrder()); IntBuffer intBuffer = tmp.asIntBuffer(); - - gl.glGetProgramInfoLog( program, 1024 * 10, intBuffer, buffer ); + + gl.glGetProgramInfoLog(program, 1024 * 10, intBuffer, buffer); int numBytes = intBuffer.get(0); byte[] bytes = new byte[numBytes]; buffer.get(bytes); - return new String( bytes ); + return new String(bytes); } - @Override - public void glGetProgramiv(int program, int pname, IntBuffer params) - { - gl.glGetProgramiv( program, pname, params ); + @Override public void glGetProgramiv (int program, int pname, IntBuffer params) { + gl.glGetProgramiv(program, pname, params); } - @Override - public void glGetRenderbufferParameteriv(int target, int pname, - IntBuffer params) - { - gl.glGetRenderbufferParameterivEXT( target, pname, params ); + @Override public void glGetRenderbufferParameteriv (int target, int pname, IntBuffer params) { + gl.glGetRenderbufferParameterivEXT(target, pname, params); } - @Override - public String glGetShaderInfoLog(int shader) - { - ByteBuffer buffer = ByteBuffer.allocateDirect( 1024*10 ); + @Override public String glGetShaderInfoLog (int shader) { + ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 10); buffer.order(ByteOrder.nativeOrder()); - ByteBuffer tmp = ByteBuffer.allocateDirect( 4 ); + ByteBuffer tmp = ByteBuffer.allocateDirect(4); tmp.order(ByteOrder.nativeOrder()); IntBuffer intBuffer = tmp.asIntBuffer(); - - gl.glGetShaderInfoLog( shader, 1024 * 10, intBuffer, buffer ); + + gl.glGetShaderInfoLog(shader, 1024 * 10, intBuffer, buffer); int numBytes = intBuffer.get(0); byte[] bytes = new byte[numBytes]; buffer.get(bytes); - return new String( bytes ); + return new String(bytes); } - @Override - public void glGetShaderPrecisionFormat(int shadertype, int precisiontype, - IntBuffer range, IntBuffer precision) - { - throw new UnsupportedOperationException( "unsupported, won't implement" ); + @Override public void glGetShaderPrecisionFormat (int shadertype, int precisiontype, IntBuffer range, IntBuffer precision) { + throw new UnsupportedOperationException("unsupported, won't implement"); } - @Override - public void glGetShaderSource(int shader, int bufsize, Buffer length, String source) - { - throw new UnsupportedOperationException( "unsupported, won't implement." ); + @Override public void glGetShaderSource (int shader, int bufsize, Buffer length, String source) { + throw new UnsupportedOperationException("unsupported, won't implement."); } - @Override - public void glGetShaderiv(int shader, int pname, IntBuffer params) - { - gl.glGetShaderiv( shader, pname, params ); + @Override public void glGetShaderiv (int shader, int pname, IntBuffer params) { + gl.glGetShaderiv(shader, pname, params); } - @Override - public String glGetString(int name) - { - return gl.glGetString( name ); + @Override public String glGetString (int name) { + return gl.glGetString(name); } - @Override - public void glGetTexParameterfv(int target, int pname, FloatBuffer params) - { - gl.glGetTexParameterfv( target, pname, params ); + @Override public void glGetTexParameterfv (int target, int pname, FloatBuffer params) { + gl.glGetTexParameterfv(target, pname, params); } - @Override - public void glGetTexParameteriv(int target, int pname, IntBuffer params) - { - gl.glGetTexParameteriv( target, pname, params ); + @Override public void glGetTexParameteriv (int target, int pname, IntBuffer params) { + gl.glGetTexParameteriv(target, pname, params); } - @Override - public int glGetUniformLocation(int program, String name) - { - return gl.glGetUniformLocation( program, name ); + @Override public int glGetUniformLocation (int program, String name) { + return gl.glGetUniformLocation(program, name); } - @Override - public void glGetUniformfv(int program, int location, FloatBuffer params) - { - gl.glGetUniformfv( program, location, params ); + @Override public void glGetUniformfv (int program, int location, FloatBuffer params) { + gl.glGetUniformfv(program, location, params); } - @Override - public void glGetUniformiv(int program, int location, IntBuffer params) - { - gl.glGetUniformiv( program, location, params ); + @Override public void glGetUniformiv (int program, int location, IntBuffer params) { + gl.glGetUniformiv(program, location, params); } - @Override - public void glGetVertexAttribPointerv(int index, int pname, Buffer pointer) - { - throw new UnsupportedOperationException( "unsupported, won't implement" ); + @Override public void glGetVertexAttribPointerv (int index, int pname, Buffer pointer) { + throw new UnsupportedOperationException("unsupported, won't implement"); } - @Override - public void glGetVertexAttribfv(int index, int pname, FloatBuffer params) - { - gl.glGetVertexAttribfv( index, pname, params ); + @Override public void glGetVertexAttribfv (int index, int pname, FloatBuffer params) { + gl.glGetVertexAttribfv(index, pname, params); } - @Override - public void glGetVertexAttribiv(int index, int pname, IntBuffer params) - { - gl.glGetVertexAttribiv( index, pname, params ); + @Override public void glGetVertexAttribiv (int index, int pname, IntBuffer params) { + gl.glGetVertexAttribiv(index, pname, params); } - @Override - public void glHint(int target, int mode) - { - gl.glHint( target, mode ); + @Override public void glHint (int target, int mode) { + gl.glHint(target, mode); } - @Override - public boolean glIsBuffer(int buffer) - { - return gl.glIsBuffer( buffer ); + @Override public boolean glIsBuffer (int buffer) { + return gl.glIsBuffer(buffer); } - @Override - public boolean glIsEnabled(int cap) - { - return gl.glIsEnabled( cap ); + @Override public boolean glIsEnabled (int cap) { + return gl.glIsEnabled(cap); } - @Override - public boolean glIsFramebuffer(int framebuffer) - { + @Override public boolean glIsFramebuffer (int framebuffer) { return gl.glIsFramebufferEXT(framebuffer); } - @Override - public boolean glIsProgram(int program) - { - return gl.glIsProgram( program ); + @Override public boolean glIsProgram (int program) { + return gl.glIsProgram(program); } - @Override - public boolean glIsRenderbuffer(int renderbuffer) - { - return gl.glIsRenderbufferEXT( renderbuffer ); + @Override public boolean glIsRenderbuffer (int renderbuffer) { + return gl.glIsRenderbufferEXT(renderbuffer); } - @Override - public boolean glIsShader(int shader) - { - return gl.glIsShader( shader ); + @Override public boolean glIsShader (int shader) { + return gl.glIsShader(shader); } - @Override - public boolean glIsTexture(int texture) - { - return gl.glIsTexture( texture ); + @Override public boolean glIsTexture (int texture) { + return gl.glIsTexture(texture); } - @Override - public void glLineWidth(float width) - { - gl.glLineWidth( width ); + @Override public void glLineWidth (float width) { + gl.glLineWidth(width); } - @Override - public void glLinkProgram(int program) - { - gl.glLinkProgram( program ); + @Override public void glLinkProgram (int program) { + gl.glLinkProgram(program); } - @Override - public void glPixelStorei(int pname, int param) - { - gl.glPixelStorei( pname, param ); + @Override public void glPixelStorei (int pname, int param) { + gl.glPixelStorei(pname, param); } - @Override - public void glPolygonOffset(float factor, float units) - { - gl.glPolygonOffset( factor, units ); + @Override public void glPolygonOffset (float factor, float units) { + gl.glPolygonOffset(factor, units); } - @Override - public void glReadPixels(int x, int y, int width, int height, int format, int type, Buffer pixels) - { - gl.glReadPixels( x, y, width, height, format, type, pixels ); + @Override public void glReadPixels (int x, int y, int width, int height, int format, int type, Buffer pixels) { + gl.glReadPixels(x, y, width, height, format, type, pixels); } - @Override - public void glReleaseShaderCompiler() - { + @Override public void glReleaseShaderCompiler () { // nothing to do here } - @Override - public void glRenderbufferStorage(int target, int internalformat, int width, int height) - { - gl.glRenderbufferStorageEXT( target, internalformat, width, height ); + @Override public void glRenderbufferStorage (int target, int internalformat, int width, int height) { + gl.glRenderbufferStorageEXT(target, internalformat, width, height); } - @Override - public void glSampleCoverage(float value, boolean invert) - { - gl.glSampleCoverage( value, invert ); + @Override public void glSampleCoverage (float value, boolean invert) { + gl.glSampleCoverage(value, invert); } - @Override - public void glScissor(int x, int y, int width, int height) - { - gl.glScissor( x, y, width, height ); + @Override public void glScissor (int x, int y, int width, int height) { + gl.glScissor(x, y, width, height); } - @Override - public void glShaderBinary(int n, IntBuffer shaders, int binaryformat, - Buffer binary, int length) - { - throw new UnsupportedOperationException( "unsupported, won't implement" ); + @Override public void glShaderBinary (int n, IntBuffer shaders, int binaryformat, Buffer binary, int length) { + throw new UnsupportedOperationException("unsupported, won't implement"); } - @Override - public void glShaderSource(int shader, String string) - { - gl.glShaderSource( shader, 1, new String[] { string }, null, 0 ); - + @Override public void glShaderSource (int shader, String string) { + gl.glShaderSource(shader, 1, new String[] {string}, null, 0); + } - @Override - public void glStencilFunc(int func, int ref, int mask) - { - gl.glStencilFunc( func, ref, mask ); + @Override public void glStencilFunc (int func, int ref, int mask) { + gl.glStencilFunc(func, ref, mask); } - @Override - public void glStencilFuncSeparate(int face, int func, int ref, int mask) - { - gl.glStencilFuncSeparate( face, func, ref, mask ); + @Override public void glStencilFuncSeparate (int face, int func, int ref, int mask) { + gl.glStencilFuncSeparate(face, func, ref, mask); } - @Override - public void glStencilMask(int mask) - { - gl.glStencilMask( mask ); + @Override public void glStencilMask (int mask) { + gl.glStencilMask(mask); } - @Override - public void glStencilMaskSeparate(int face, int mask) - { - gl.glStencilMaskSeparate( face, mask ); + @Override public void glStencilMaskSeparate (int face, int mask) { + gl.glStencilMaskSeparate(face, mask); } - @Override - public void glStencilOp(int fail, int zfail, int zpass) - { - gl.glStencilOp( fail, zfail, zpass ); + @Override public void glStencilOp (int fail, int zfail, int zpass) { + gl.glStencilOp(fail, zfail, zpass); } - @Override - public void glStencilOpSeparate(int face, int fail, int zfail, int zpass) - { - gl.glStencilOpSeparate( face, fail, zfail, zpass ); + @Override public void glStencilOpSeparate (int face, int fail, int zfail, int zpass) { + gl.glStencilOpSeparate(face, fail, zfail, zpass); } - @Override - public void glTexImage2D(int target, int level, int internalformat, - int width, int height, int border, int format, int type, - Buffer pixels) - { - gl.glTexImage2D( target, level, internalformat, width, height, border, format, type, pixels ); + @Override public void glTexImage2D (int target, int level, int internalformat, int width, int height, int border, int format, + int type, Buffer pixels) { + gl.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); } - @Override - public void glTexParameterf(int target, int pname, float param) - { - gl.glTexParameterf( target, pname, param ); + @Override public void glTexParameterf (int target, int pname, float param) { + gl.glTexParameterf(target, pname, param); } - @Override - public void glTexParameterfv(int target, int pname, FloatBuffer params) - { - gl.glTexParameterfv( target, pname, params ); + @Override public void glTexParameterfv (int target, int pname, FloatBuffer params) { + gl.glTexParameterfv(target, pname, params); } - @Override - public void glTexParameteri(int target, int pname, int param) - { - gl.glTexParameteri( target, pname, param ); + @Override public void glTexParameteri (int target, int pname, int param) { + gl.glTexParameteri(target, pname, param); } - @Override - public void glTexParameteriv(int target, int pname, IntBuffer params) - { - gl.glTexParameteriv( target, pname, params ); + @Override public void glTexParameteriv (int target, int pname, IntBuffer params) { + gl.glTexParameteriv(target, pname, params); } - @Override - public void glTexSubImage2D(int target, int level, int xoffset, - int yoffset, int width, int height, int format, int type, - Buffer pixels) - { - gl.glTexSubImage2D( target, level, xoffset, yoffset, width, height, format, type, pixels ); + @Override public void glTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, int format, + int type, Buffer pixels) { + gl.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); } - @Override - public void glUniform1f(int location, float x) - { - gl.glUniform1f( location, x ); + @Override public void glUniform1f (int location, float x) { + gl.glUniform1f(location, x); } - @Override - public void glUniform1fv(int location, int count, FloatBuffer v) - { - gl.glUniform1fv( location, count, v ); + @Override public void glUniform1fv (int location, int count, FloatBuffer v) { + gl.glUniform1fv(location, count, v); } - @Override - public void glUniform1i(int location, int x) - { - gl.glUniform1i( location, x ); + @Override public void glUniform1i (int location, int x) { + gl.glUniform1i(location, x); } - @Override - public void glUniform1iv(int location, int count, IntBuffer v) - { - gl.glUniform1iv( location, count, v ); + @Override public void glUniform1iv (int location, int count, IntBuffer v) { + gl.glUniform1iv(location, count, v); } - @Override - public void glUniform2f(int location, float x, float y) - { - gl.glUniform2f( location, x, y ); + @Override public void glUniform2f (int location, float x, float y) { + gl.glUniform2f(location, x, y); } - @Override - public void glUniform2fv(int location, int count, FloatBuffer v) - { - gl.glUniform2fv( location, count, v ); + @Override public void glUniform2fv (int location, int count, FloatBuffer v) { + gl.glUniform2fv(location, count, v); } - @Override - public void glUniform2i(int location, int x, int y) - { - gl.glUniform2i( location, x, y ); + @Override public void glUniform2i (int location, int x, int y) { + gl.glUniform2i(location, x, y); } - @Override - public void glUniform2iv(int location, int count, IntBuffer v) - { - gl.glUniform2iv( location, count, v ); + @Override public void glUniform2iv (int location, int count, IntBuffer v) { + gl.glUniform2iv(location, count, v); } - @Override - public void glUniform3f(int location, float x, float y, float z) - { - gl.glUniform3f( location, x, y, z ); + @Override public void glUniform3f (int location, float x, float y, float z) { + gl.glUniform3f(location, x, y, z); } - @Override - public void glUniform3fv(int location, int count, FloatBuffer v) - { - gl.glUniform3fv( location, count, v ); + @Override public void glUniform3fv (int location, int count, FloatBuffer v) { + gl.glUniform3fv(location, count, v); } - @Override - public void glUniform3i(int location, int x, int y, int z) - { - gl.glUniform3i( location, x, y, z ); + @Override public void glUniform3i (int location, int x, int y, int z) { + gl.glUniform3i(location, x, y, z); } - @Override - public void glUniform3iv(int location, int count, IntBuffer v) - { - gl.glUniform3iv( location, count, v ); + @Override public void glUniform3iv (int location, int count, IntBuffer v) { + gl.glUniform3iv(location, count, v); } - @Override - public void glUniform4f(int location, float x, float y, float z, float w) - { - gl.glUniform4f( location, x, y, z, w ); + @Override public void glUniform4f (int location, float x, float y, float z, float w) { + gl.glUniform4f(location, x, y, z, w); } - @Override - public void glUniform4fv(int location, int count, FloatBuffer v) - { - gl.glUniform4fv( location, count, v ); + @Override public void glUniform4fv (int location, int count, FloatBuffer v) { + gl.glUniform4fv(location, count, v); } - @Override - public void glUniform4i(int location, int x, int y, int z, int w) - { - gl.glUniform4i( location, x, y, z, w ); + @Override public void glUniform4i (int location, int x, int y, int z, int w) { + gl.glUniform4i(location, x, y, z, w); } - @Override - public void glUniform4iv(int location, int count, IntBuffer v) - { - gl.glUniform4iv( location, count, v ); + @Override public void glUniform4iv (int location, int count, IntBuffer v) { + gl.glUniform4iv(location, count, v); } - @Override - public void glUniformMatrix2fv(int location, int count, boolean transpose, - FloatBuffer value) - { - gl.glUniformMatrix2fv( location, count, transpose, value ); + @Override public void glUniformMatrix2fv (int location, int count, boolean transpose, FloatBuffer value) { + gl.glUniformMatrix2fv(location, count, transpose, value); } - @Override - public void glUniformMatrix3fv(int location, int count, boolean transpose, - FloatBuffer value) - { - gl.glUniformMatrix3fv( location, count, transpose, value ); + @Override public void glUniformMatrix3fv (int location, int count, boolean transpose, FloatBuffer value) { + gl.glUniformMatrix3fv(location, count, transpose, value); } - @Override - public void glUniformMatrix4fv(int location, int count, boolean transpose, - FloatBuffer value) - { - gl.glUniformMatrix4fv( location, count, transpose, value ); + @Override public void glUniformMatrix4fv (int location, int count, boolean transpose, FloatBuffer value) { + gl.glUniformMatrix4fv(location, count, transpose, value); } - @Override - public void glUseProgram(int program) - { - gl.glUseProgram( program ); + @Override public void glUseProgram (int program) { + gl.glUseProgram(program); } - @Override - public void glValidateProgram(int program) - { - gl.glValidateProgram( program ); + @Override public void glValidateProgram (int program) { + gl.glValidateProgram(program); } - @Override - public void glVertexAttrib1f(int indx, float x) - { - gl.glVertexAttrib1f( indx, x ); + @Override public void glVertexAttrib1f (int indx, float x) { + gl.glVertexAttrib1f(indx, x); } - @Override - public void glVertexAttrib1fv(int indx, FloatBuffer values) - { - gl.glVertexAttrib1fv( indx, values ); + @Override public void glVertexAttrib1fv (int indx, FloatBuffer values) { + gl.glVertexAttrib1fv(indx, values); } - @Override - public void glVertexAttrib2f(int indx, float x, float y) - { - gl.glVertexAttrib2f( indx, x, y ); + @Override public void glVertexAttrib2f (int indx, float x, float y) { + gl.glVertexAttrib2f(indx, x, y); } - @Override - public void glVertexAttrib2fv(int indx, FloatBuffer values) - { - gl.glVertexAttrib2fv( indx, values ); + @Override public void glVertexAttrib2fv (int indx, FloatBuffer values) { + gl.glVertexAttrib2fv(indx, values); } - @Override - public void glVertexAttrib3f(int indx, float x, float y, float z) - { - gl.glVertexAttrib3f( indx, x, y, z ); + @Override public void glVertexAttrib3f (int indx, float x, float y, float z) { + gl.glVertexAttrib3f(indx, x, y, z); } - @Override - public void glVertexAttrib3fv(int indx, FloatBuffer values) - { - gl.glVertexAttrib3fv( indx, values ); + @Override public void glVertexAttrib3fv (int indx, FloatBuffer values) { + gl.glVertexAttrib3fv(indx, values); } - @Override - public void glVertexAttrib4f(int indx, float x, float y, float z, float w) - { - gl.glVertexAttrib4f( indx, x, y, z, w ); + @Override public void glVertexAttrib4f (int indx, float x, float y, float z, float w) { + gl.glVertexAttrib4f(indx, x, y, z, w); } - @Override - public void glVertexAttrib4fv(int indx, FloatBuffer values) - { - gl.glVertexAttrib4fv( indx, values ); + @Override public void glVertexAttrib4fv (int indx, FloatBuffer values) { + gl.glVertexAttrib4fv(indx, values); } - @Override - public void glVertexAttribPointer(int indx, int size, int type, - boolean normalized, int stride, Buffer ptr) - { - gl.glVertexAttribPointer( indx, size, type, normalized, stride, ptr ); + @Override public void glVertexAttribPointer (int indx, int size, int type, boolean normalized, int stride, Buffer ptr) { + gl.glVertexAttribPointer(indx, size, type, normalized, stride, ptr); } - @Override - public void glViewport(int x, int y, int width, int height) - { - gl.glViewport( x, y, width, height ); + @Override public void glViewport (int x, int y, int width, int height) { + gl.glViewport(x, y, width, height); } - @Override - public void glDrawElements(int mode, int count, int type, int indices) - { - gl.glDrawElements( mode, count, type, indices ); + @Override public void glDrawElements (int mode, int count, int type, int indices) { + gl.glDrawElements(mode, count, type, indices); } - @Override - public void glVertexAttribPointer(int indx, int size, int type, boolean normalized, int stride, int ptr) - { - gl.glVertexAttribPointer( indx, size, type, normalized, stride, ptr ); + @Override public void glVertexAttribPointer (int indx, int size, int type, boolean normalized, int stride, int ptr) { + gl.glVertexAttribPointer(indx, size, type, normalized, stride, ptr); } } diff --git a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletGraphics.java b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletGraphics.java index 9d351bf12..be25c6845 100644 --- a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletGraphics.java +++ b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletGraphics.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.applet; import java.applet.Applet; @@ -29,14 +27,14 @@ import com.badlogic.gdx.Graphics; import com.badlogic.gdx.RenderListener; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Font; +import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.GL11; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.GLCommon; import com.badlogic.gdx.graphics.Pixmap; -import com.badlogic.gdx.graphics.Texture; -import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.Pixmap.Format; +import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; import com.badlogic.gdx.math.WindowedMean; @@ -44,230 +42,178 @@ import com.badlogic.gdx.math.WindowedMean; /** * An implementation of the {@link Graphics} interface based on Jogl. * @author mzechner - * + * */ -public final class AppletGraphics implements Graphics, RenderListener -{ - /** the graphic panel **/ +public final class AppletGraphics implements Graphics, RenderListener { + /** the graphic panel **/ protected final AppletPanel graphicPanel; - + /** the render listener **/ - private RenderListener listener; - + private RenderListener listener; + /** GLCommon instance **/ private GLCommon gl; - + /** GL10 instance **/ private GL10 gl10; - + /** GL11 instance **/ private GL11 gl11; - + /** GL20 instance **/ private GL20 gl20; - + /** wheter to use opengl 2 **/ private final boolean useGL2; - + /** the last frame time **/ private long lastFrameTime = System.nanoTime(); - + /** the deltaTime **/ private float deltaTime = 0; - + /** the deltaTime mean **/ - private WindowedMean mean = new WindowedMean( 5 ); - + private WindowedMean mean = new WindowedMean(5); + /** whether to allow fixed point or not **/ private boolean allowFixedPoint; - - AppletGraphics( Application application, Applet applet, boolean useGL2IfAvailable, boolean allowFixedPoint ) - { - graphicPanel = new AppletPanel( application ); - applet.setLayout( new BorderLayout() ); - applet.add( graphicPanel, BorderLayout.CENTER ); - useGL2 = useGL2IfAvailable; - graphicPanel.addGraphicListener( this ); - graphicPanel.requestFocusInWindow(); - this.allowFixedPoint = allowFixedPoint; + + AppletGraphics (Application application, Applet applet, boolean useGL2IfAvailable, boolean allowFixedPoint) { + graphicPanel = new AppletPanel(application); + applet.setLayout(new BorderLayout()); + applet.add(graphicPanel, BorderLayout.CENTER); + useGL2 = useGL2IfAvailable; + graphicPanel.addGraphicListener(this); + graphicPanel.requestFocusInWindow(); + this.allowFixedPoint = allowFixedPoint; } - @Override - public GL10 getGL10() - { + @Override public GL10 getGL10 () { return gl10; } - @Override - public GL11 getGL11() - { + @Override public GL11 getGL11 () { return gl11; } - @Override - public GL20 getGL20() - { + @Override public GL20 getGL20 () { return gl20; } - @Override - public int getHeight() - { + @Override public int getHeight () { return graphicPanel.getHeight(); } - @Override - public int getWidth() - { + @Override public int getWidth () { return graphicPanel.getWidth(); } - @Override - public boolean isGL11Available() - { + @Override public boolean isGL11Available () { return gl11 != null; } - @Override - public boolean isGL20Available() - { + @Override public boolean isGL20Available () { return gl20 != null; } - @Override - public Font newFont(String fontName, int size, FontStyle style ) - { - return new AppletFont( this, fontName, size, style ); + @Override public Font newFont (String fontName, int size, FontStyle style) { + return new AppletFont(this, fontName, size, style); } - @Override - public Font newFont(FileHandle file, int size, FontStyle style ) - { + @Override public Font newFont (FileHandle file, int size, FontStyle style) { AppletFileHandle jHandle = (AppletFileHandle)file; InputStream in; try { in = jHandle.getInputStream(); - AppletFont font = new AppletFont(this, in, size, style ); + AppletFont font = new AppletFont(this, in, size, style); in.close(); - + return font; - } catch (Exception e) - { + } catch (Exception e) { return null; - } + } } - @Override - public Pixmap newPixmap(int width, int height, Format format) - { - return new AppletPixmap( width, height, format ); + @Override public Pixmap newPixmap (int width, int height, Format format) { + return new AppletPixmap(width, height, format); } - @Override - public Pixmap newPixmap(InputStream in) - { - try - { - BufferedImage img = (BufferedImage)ImageIO.read( in ); - return new AppletPixmap( img ); - } - catch( Exception ex ) - { + @Override public Pixmap newPixmap (InputStream in) { + try { + BufferedImage img = (BufferedImage)ImageIO.read(in); + return new AppletPixmap(img); + } catch (Exception ex) { return null; - } + } } - - @Override - public Pixmap newPixmap(FileHandle file) - { - try - { + + @Override public Pixmap newPixmap (FileHandle file) { + try { InputStream in = ((AppletFileHandle)file).getInputStream(); - BufferedImage img = (BufferedImage)ImageIO.read( in ); + BufferedImage img = (BufferedImage)ImageIO.read(in); in.close(); - return new AppletPixmap( img ); - } - catch( Exception ex ) - { + return new AppletPixmap(img); + } catch (Exception ex) { return null; - } + } } - @Override - public Pixmap newPixmap(Object nativePixmap) - { - return new AppletPixmap( (BufferedImage)nativePixmap ); + @Override public Pixmap newPixmap (Object nativePixmap) { + return new AppletPixmap((BufferedImage)nativePixmap); } - @Override - public Texture newUnmanagedTexture(int width, int height, Pixmap.Format format, TextureFilter minFilter, TextureFilter magFilter, TextureWrap uWrap, TextureWrap vWrap ) - { - if( format == Format.Alpha ) - return new AppletTexture( width, height, BufferedImage.TYPE_BYTE_GRAY, minFilter, magFilter, uWrap, vWrap, false ); + @Override public Texture newUnmanagedTexture (int width, int height, Pixmap.Format format, TextureFilter minFilter, + TextureFilter magFilter, TextureWrap uWrap, TextureWrap vWrap) { + if (format == Format.Alpha) + return new AppletTexture(width, height, BufferedImage.TYPE_BYTE_GRAY, minFilter, magFilter, uWrap, vWrap, false); else - return new AppletTexture( width, height, BufferedImage.TYPE_4BYTE_ABGR, minFilter, magFilter, uWrap, vWrap, false ); + return new AppletTexture(width, height, BufferedImage.TYPE_4BYTE_ABGR, minFilter, magFilter, uWrap, vWrap, false); } - @Override - public Texture newUnmanagedTexture(Pixmap pixmap, TextureFilter minFilter, TextureFilter magFilter, TextureWrap uWrap, TextureWrap vWrap ) - { - return new AppletTexture( (BufferedImage)pixmap.getNativePixmap(), minFilter, magFilter, uWrap, vWrap, false ); + @Override public Texture newUnmanagedTexture (Pixmap pixmap, TextureFilter minFilter, TextureFilter magFilter, + TextureWrap uWrap, TextureWrap vWrap) { + return new AppletTexture((BufferedImage)pixmap.getNativePixmap(), minFilter, magFilter, uWrap, vWrap, false); } /** * {@inheritDoc} */ - @Override - public void setRenderListener( RenderListener listener) - { - if( this.listener != null ) - graphicPanel.removeGraphicListener( this.listener ); + @Override public void setRenderListener (RenderListener listener) { + if (this.listener != null) graphicPanel.removeGraphicListener(this.listener); graphicPanel.addGraphicListener(listener); this.listener = listener; } - @Override - public void dispose( ) - { - + @Override public void dispose () { + } - @Override - public void render( ) - { + @Override public void render () { // calculate delta time - deltaTime = ( System.nanoTime() - lastFrameTime ) / 1000000000.0f; + deltaTime = (System.nanoTime() - lastFrameTime) / 1000000000.0f; lastFrameTime = System.nanoTime(); - mean.addValue( deltaTime ); + mean.addValue(deltaTime); } - @Override - public void surfaceCreated( ) - { - String version = graphicPanel.getGL().glGetString( GL.GL_VERSION ); + @Override public void surfaceCreated () { + String version = graphicPanel.getGL().glGetString(GL.GL_VERSION); int major = Integer.parseInt("" + version.charAt(0)); int minor = Integer.parseInt("" + version.charAt(2)); - - if( useGL2 && major >= 2 ) - { + + if (useGL2 && major >= 2) { // FIXME add check wheter gl 2.0 is supported - gl20 = new AppletGL20( graphicPanel.getGL() ); + gl20 = new AppletGL20(graphicPanel.getGL()); gl = gl20; - } - else - { - if( major == 1 && minor < 5 ) - { - gl10 = new AppletGL10( graphicPanel.getGL(), allowFixedPoint ); - } - else - { - gl11 = new AppletGL11( graphicPanel.getGL(), allowFixedPoint ); - gl10 = gl11; + } else { + if (major == 1 && minor < 5) { + gl10 = new AppletGL10(graphicPanel.getGL(), allowFixedPoint); + } else { + gl11 = new AppletGL11(graphicPanel.getGL(), allowFixedPoint); + gl10 = gl11; } gl = gl10; } - + Gdx.gl = gl; Gdx.gl10 = gl10; Gdx.gl11 = gl11; @@ -277,42 +223,33 @@ public final class AppletGraphics implements Graphics, RenderListener /** * {@inheritDoc} */ - @Override - public float getDeltaTime() - { - return mean.getMean() == 0?deltaTime:mean.getMean(); + @Override public float getDeltaTime () { + return mean.getMean() == 0 ? deltaTime : mean.getMean(); } - @Override - public void surfaceChanged( int width, int height) { + @Override public void surfaceChanged (int width, int height) { // TODO Auto-generated method stub - + } /** * {@inheritDoc} */ - @Override - public GraphicsType getType() - { + @Override public GraphicsType getType () { return GraphicsType.JoglGL; } - @Override - public int getFramesPerSecond() { + @Override public int getFramesPerSecond () { return 0; // FIXME } - @Override - public Texture newTexture(FileHandle file, TextureFilter minFilter, - TextureFilter magFilter, TextureWrap uWrap, TextureWrap vWrap) - { - Pixmap pixmap = newPixmap( file ); - return new AppletTexture( (BufferedImage)pixmap.getNativePixmap(), minFilter, magFilter, uWrap, vWrap, true ); + @Override public Texture newTexture (FileHandle file, TextureFilter minFilter, TextureFilter magFilter, TextureWrap uWrap, + TextureWrap vWrap) { + Pixmap pixmap = newPixmap(file); + return new AppletTexture((BufferedImage)pixmap.getNativePixmap(), minFilter, magFilter, uWrap, vWrap, true); } - @Override - public GLCommon getGLCommon() { + @Override public GLCommon getGLCommon () { return gl; } } diff --git a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletInput.java b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletInput.java index ba7020153..de2638d5e 100644 --- a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletInput.java +++ b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletInput.java @@ -1,17 +1,14 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ package com.badlogic.gdx.backends.applet; @@ -29,164 +26,123 @@ import com.badlogic.gdx.RenderListener; * An implementation of the {@link Input} interface hooking a Jogl panel for input. * * @author mzechner - * + * */ -final class AppletInput implements Input, RenderListener -{ +final class AppletInput implements Input, RenderListener { /** the multiplexer **/ private final AppletInputMultiplexer multiplexer; - + /** the graphics panel **/ private final AppletPanel panel; - + /** user input **/ private String text; - + /** user input listener **/ private TextInputListener textListener; - - AppletInput( AppletPanel panel ) - { + + AppletInput (AppletPanel panel) { multiplexer = new AppletInputMultiplexer(panel.getCanvas()); this.panel = panel; - this.panel.addGraphicListener( this ); + this.panel.addGraphicListener(this); } - - @Override - public void addInputListener(InputListener listener) - { - multiplexer.addListener( listener ); + + @Override public void addInputListener (InputListener listener) { + multiplexer.addListener(listener); } - @Override - public float getAccelerometerX() - { + @Override public float getAccelerometerX () { return 0; } - @Override - public float getAccelerometerY() - { + @Override public float getAccelerometerY () { return 0; } - @Override - public float getAccelerometerZ() - { + @Override public float getAccelerometerZ () { return 0; } - @Override - public void getTextInput(final TextInputListener listener, final String title, final String text) - { - SwingUtilities.invokeLater( new Runnable() { - @Override - public void run() { - AppletInput.this.text = JOptionPane.showInputDialog(null, title, text ); - if( AppletInput.this.text != null ) - textListener = listener; + @Override public void getTextInput (final TextInputListener listener, final String title, final String text) { + SwingUtilities.invokeLater(new Runnable() { + @Override public void run () { + AppletInput.this.text = JOptionPane.showInputDialog(null, title, text); + if (AppletInput.this.text != null) textListener = listener; } }); } - @Override - public int getX() - { + @Override public int getX () { return panel.getMouseX(); } - @Override - public int getY() - { + @Override public int getY () { return panel.getMouseY(); } - @Override - public boolean isAccelerometerAvailable() - { + @Override public boolean isAccelerometerAvailable () { return false; } - @Override - public boolean isKeyPressed(int key) - { - return panel.isKeyDown( key ); + @Override public boolean isKeyPressed (int key) { + return panel.isKeyDown(key); } - @Override - public boolean isTouched() - { - return panel.isButtonDown(MouseEvent.BUTTON1) || - panel.isButtonDown(MouseEvent.BUTTON2) || - panel.isButtonDown(MouseEvent.BUTTON3); + @Override public boolean isTouched () { + return panel.isButtonDown(MouseEvent.BUTTON1) || panel.isButtonDown(MouseEvent.BUTTON2) + || panel.isButtonDown(MouseEvent.BUTTON3); } - @Override - public void removeInputListener(InputListener listener) - { - multiplexer.removeListener( listener ); + @Override public void removeInputListener (InputListener listener) { + multiplexer.removeListener(listener); } - @Override - public void dispose( ) { + @Override public void dispose () { // TODO Auto-generated method stub - + } - @Override - public void render( ) - { + @Override public void render () { multiplexer.processEvents(); - - if( textListener != null ) - { - textListener.input( text ); + + if (textListener != null) { + textListener.input(text); textListener = null; } } - @Override - public void surfaceCreated( ) { + @Override public void surfaceCreated () { // TODO Auto-generated method stub - + } - @Override - public void surfaceChanged( int width, int height) { + @Override public void surfaceChanged (int width, int height) { // TODO Auto-generated method stub - + } - @Override - public int getX(int pointer) - { - if( pointer > 0 ) + @Override public int getX (int pointer) { + if (pointer > 0) return 0; else return getX(); } - @Override - public int getY(int pointer) - { - if( pointer > 0 ) + @Override public int getY (int pointer) { + if (pointer > 0) return 0; else return getY(); } - @Override - public boolean isTouched(int pointer) - { - if( pointer > 0 ) + @Override public boolean isTouched (int pointer) { + if (pointer > 0) return false; else - return isTouched(); + return isTouched(); } - @Override - public boolean supportsMultitouch() - { + @Override public boolean supportsMultitouch () { return false; } diff --git a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletInputMultiplexer.java b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletInputMultiplexer.java index 26f0a65e9..305b82c57 100644 --- a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletInputMultiplexer.java +++ b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletInputMultiplexer.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.applet; import java.awt.Component; @@ -29,372 +27,257 @@ import java.util.HashMap; import com.badlogic.gdx.Input; import com.badlogic.gdx.InputListener; - - /** - * Hooks a swing component and multiplexes any input - * events to all registered listeners in order. a listener - * can signal wheter he has consumed the event therefor - * ending the multiplexing. + * Hooks a swing component and multiplexes any input events to all registered listeners in order. a listener can signal wheter he + * has consumed the event therefor ending the multiplexing. * * @author badlogicgames@gmail.com - * + * */ -final class AppletInputMultiplexer implements MouseListener, MouseMotionListener, MouseWheelListener, KeyListener -{ - private enum EventType - { - MouseDown, - MouseUp, - MouseMoved, - MouseDragged, - KeyDown, - KeyUp, - KeyTyped +final class AppletInputMultiplexer implements MouseListener, MouseMotionListener, MouseWheelListener, KeyListener { + private enum EventType { + MouseDown, MouseUp, MouseMoved, MouseDragged, KeyDown, KeyUp, KeyTyped } - - private class Event - { - public int x, y; + + private class Event { + public int x, y; public int keycode; public char keychar; public EventType type; - - public void set( EventType type, int x, int y, int keycode, char keychar ) - { + + public void set (EventType type, int x, int y, int keycode, char keychar) { this.type = type; this.x = x; - this.y = y; + this.y = y; this.keycode = keycode; this.keychar = keychar; } - } - - private final ArrayList eventQueue = new ArrayList( ); - private final ArrayList freeEvents = new ArrayList( ); + } + + private final ArrayList eventQueue = new ArrayList(); + private final ArrayList freeEvents = new ArrayList(); private int freeEventIndex = 0; - - private final ArrayList listeners = new ArrayList( ); - private final HashMap disabled = new HashMap( ); + + private final ArrayList listeners = new ArrayList(); + private final HashMap disabled = new HashMap(); private Component component; - + /** * constructor, hooks the given component * @param component the component to hook */ - AppletInputMultiplexer( Component component ) - { - hook( component ); - for( int i = 0; i < 1000; i++ ) - freeEvents.add( new Event() ); + AppletInputMultiplexer (Component component) { + hook(component); + for (int i = 0; i < 1000; i++) + freeEvents.add(new Event()); } /** - * adds callback hooks to the component. unhooks from - * the old component if any was set. + * adds callback hooks to the component. unhooks from the old component if any was set. * * @param component the component to hook */ - public void hook( Component component ) - { - unhook( ); - component.addMouseListener( this ); - component.addMouseMotionListener( this ); - component.addMouseWheelListener( this ); - component.addKeyListener( this ); + public void hook (Component component) { + unhook(); + component.addMouseListener(this); + component.addMouseMotionListener(this); + component.addMouseWheelListener(this); + component.addKeyListener(this); this.component = component; } - + /** * removes the callback hooks from the swing component */ - public void unhook( ) - { - if( component != null ) - { - component.removeMouseListener( this ); - component.removeMouseMotionListener( this ); - component.removeMouseWheelListener( this ); - component.removeKeyListener( this ); + public void unhook () { + if (component != null) { + component.removeMouseListener(this); + component.removeMouseMotionListener(this); + component.removeMouseWheelListener(this); + component.removeKeyListener(this); } } - - public void disableListener( InputListener listener ) - { + + public void disableListener (InputListener listener) { disabled.put(listener, true); } - - public void enableListener( InputListener listener ) - { - disabled.put(listener, false ); + + public void enableListener (InputListener listener) { + disabled.put(listener, false); } - - public void processEvents( ) - { - synchronized( eventQueue ) - { - for( int i = 0; i < eventQueue.size(); i++ ) - { + + public void processEvents () { + synchronized (eventQueue) { + for (int i = 0; i < eventQueue.size(); i++) { Event event = eventQueue.get(i); - if( event.type == EventType.MouseDown ) - for( int j = 0; j < listeners.size(); j++ ) - if( listeners.get(j).touchDown(event.x, event.y, 0 ) ) - break; - if( event.type == EventType.MouseUp ) - for( int j = 0; j < listeners.size(); j++ ) - if( listeners.get(j).touchUp(event.x, event.y, 0 ) ) - break; - if( event.type == EventType.MouseDragged ) - for( int j = 0; j < listeners.size(); j++ ) - if( listeners.get(j).touchDragged(event.x, event.y, 0 ) ) - break; - if( event.type == EventType.KeyDown ) - for( int j = 0; j < listeners.size(); j++ ) - if( listeners.get(j).keyDown(event.keycode) ) - break; - if( event.type == EventType.KeyUp ) - for( int j = 0; j < listeners.size(); j++ ) - if( listeners.get(j).keyUp(event.keycode) ) - break; - if( event.type == EventType.KeyTyped ) - for( int j = 0; j < listeners.size(); j++ ) - if( listeners.get(j).keyTyped(event.keychar) ) - break; + if (event.type == EventType.MouseDown) for (int j = 0; j < listeners.size(); j++) + if (listeners.get(j).touchDown(event.x, event.y, 0)) break; + if (event.type == EventType.MouseUp) for (int j = 0; j < listeners.size(); j++) + if (listeners.get(j).touchUp(event.x, event.y, 0)) break; + if (event.type == EventType.MouseDragged) for (int j = 0; j < listeners.size(); j++) + if (listeners.get(j).touchDragged(event.x, event.y, 0)) break; + if (event.type == EventType.KeyDown) for (int j = 0; j < listeners.size(); j++) + if (listeners.get(j).keyDown(event.keycode)) break; + if (event.type == EventType.KeyUp) for (int j = 0; j < listeners.size(); j++) + if (listeners.get(j).keyUp(event.keycode)) break; + if (event.type == EventType.KeyTyped) for (int j = 0; j < listeners.size(); j++) + if (listeners.get(j).keyTyped(event.keychar)) break; } eventQueue.clear(); freeEventIndex = 0; } } - + /** - * adds an {@link InputListener} to this multiplexer. - * The order in which listeners are added is the - * order in which they are asked to consume events. + * adds an {@link InputListener} to this multiplexer. The order in which listeners are added is the order in which they are + * asked to consume events. * * @param listener the listener to add */ - public void addListener( InputListener listener ) - { - synchronized( eventQueue ) - { - if( !listeners.contains( listener ) ) - { - listeners.add( listener ); + public void addListener (InputListener listener) { + synchronized (eventQueue) { + if (!listeners.contains(listener)) { + listeners.add(listener); disabled.put(listener, false); } } } - - public void removeListener( InputListener listener ) - { - synchronized( eventQueue ) - { - listeners.remove( listener ); + + public void removeListener (InputListener listener) { + synchronized (eventQueue) { + listeners.remove(listener); disabled.remove(listener); } } - - public void mouseClicked(MouseEvent e) - { - - } - - public void mousePressed(MouseEvent e) - { - synchronized( eventQueue ) - { - Event event = freeEvents.get( freeEventIndex++ ); - event.set(EventType.MouseDown, e.getX(), e.getY(), 0, '\0' ); + + public void mouseClicked (MouseEvent e) { + + } + + public void mousePressed (MouseEvent e) { + synchronized (eventQueue) { + Event event = freeEvents.get(freeEventIndex++); + event.set(EventType.MouseDown, e.getX(), e.getY(), 0, '\0'); eventQueue.add(event); } } - public void mouseReleased(MouseEvent e) - { - synchronized( eventQueue ) - { - Event event = freeEvents.get( freeEventIndex++ ); - event.set(EventType.MouseUp, e.getX(), e.getY(), 0, '\0' ); + public void mouseReleased (MouseEvent e) { + synchronized (eventQueue) { + Event event = freeEvents.get(freeEventIndex++); + event.set(EventType.MouseUp, e.getX(), e.getY(), 0, '\0'); eventQueue.add(event); } - + } - public void mouseDragged(MouseEvent e) - { - synchronized( eventQueue ) - { - Event event = freeEvents.get( freeEventIndex++ ); - event.set(EventType.MouseDragged, e.getX(), e.getY(), 0, '\0' ); + public void mouseDragged (MouseEvent e) { + synchronized (eventQueue) { + Event event = freeEvents.get(freeEventIndex++); + event.set(EventType.MouseDragged, e.getX(), e.getY(), 0, '\0'); eventQueue.add(event); } } - public void mouseMoved(MouseEvent e) - { + public void mouseMoved (MouseEvent e) { } - public void keyPressed(KeyEvent e) - { - synchronized( eventQueue ) - { - Event event = freeEvents.get( freeEventIndex++ ); - event.set(EventType.KeyDown, 0, 0, translateKeyCode(e.getKeyCode()), '\0' ); + public void keyPressed (KeyEvent e) { + synchronized (eventQueue) { + Event event = freeEvents.get(freeEventIndex++); + event.set(EventType.KeyDown, 0, 0, translateKeyCode(e.getKeyCode()), '\0'); eventQueue.add(event); } } - public void keyReleased(KeyEvent e) - { - synchronized( eventQueue ) - { - Event event = freeEvents.get( freeEventIndex++ ); - event.set(EventType.KeyUp, 0, 0, translateKeyCode(e.getKeyCode()), '\0' ); + public void keyReleased (KeyEvent e) { + synchronized (eventQueue) { + Event event = freeEvents.get(freeEventIndex++); + event.set(EventType.KeyUp, 0, 0, translateKeyCode(e.getKeyCode()), '\0'); eventQueue.add(event); } } - public void keyTyped(KeyEvent e) - { - synchronized( eventQueue ) - { - Event event = freeEvents.get( freeEventIndex++ ); - event.set(EventType.KeyTyped, 0, 0, translateKeyCode(e.getKeyCode()), e.getKeyChar() ); + public void keyTyped (KeyEvent e) { + synchronized (eventQueue) { + Event event = freeEvents.get(freeEventIndex++); + event.set(EventType.KeyTyped, 0, 0, translateKeyCode(e.getKeyCode()), e.getKeyChar()); eventQueue.add(event); } } - @Override - public void mouseEntered(MouseEvent e) { + @Override public void mouseEntered (MouseEvent e) { // TODO Auto-generated method stub - + } - @Override - public void mouseExited(MouseEvent e) { + @Override public void mouseExited (MouseEvent e) { // TODO Auto-generated method stub - + } - @Override - public void mouseWheelMoved(MouseWheelEvent arg0) { + @Override public void mouseWheelMoved (MouseWheelEvent arg0) { // TODO Auto-generated method stub - + } - - protected static int translateKeyCode( int keyCode ) - { - if( keyCode == KeyEvent.VK_0 ) - return Input.Keys.KEYCODE_0; - if( keyCode == KeyEvent.VK_1 ) - return Input.Keys.KEYCODE_1; - if( keyCode == KeyEvent.VK_2 ) - return Input.Keys.KEYCODE_2; - if( keyCode == KeyEvent.VK_3 ) - return Input.Keys.KEYCODE_3; - if( keyCode == KeyEvent.VK_4 ) - return Input.Keys.KEYCODE_4; - if( keyCode == KeyEvent.VK_5 ) - return Input.Keys.KEYCODE_5; - if( keyCode == KeyEvent.VK_6 ) - return Input.Keys.KEYCODE_6; - if( keyCode == KeyEvent.VK_7 ) - return Input.Keys.KEYCODE_7; - if( keyCode == KeyEvent.VK_8 ) - return Input.Keys.KEYCODE_8; - if( keyCode == KeyEvent.VK_9 ) - return Input.Keys.KEYCODE_9; - if( keyCode == KeyEvent.VK_A ) - return Input.Keys.KEYCODE_A; - if( keyCode == KeyEvent.VK_B ) - return Input.Keys.KEYCODE_B; - if( keyCode == KeyEvent.VK_C ) - return Input.Keys.KEYCODE_C; - if( keyCode == KeyEvent.VK_D ) - return Input.Keys.KEYCODE_D; - if( keyCode == KeyEvent.VK_E ) - return Input.Keys.KEYCODE_E; - if( keyCode == KeyEvent.VK_F ) - return Input.Keys.KEYCODE_F; - if( keyCode == KeyEvent.VK_G ) - return Input.Keys.KEYCODE_G; - if( keyCode == KeyEvent.VK_H ) - return Input.Keys.KEYCODE_H; - if( keyCode == KeyEvent.VK_I ) - return Input.Keys.KEYCODE_I; - if( keyCode == KeyEvent.VK_J ) - return Input.Keys.KEYCODE_J; - if( keyCode == KeyEvent.VK_K ) - return Input.Keys.KEYCODE_K; - if( keyCode == KeyEvent.VK_L ) - return Input.Keys.KEYCODE_L; - if( keyCode == KeyEvent.VK_M ) - return Input.Keys.KEYCODE_M; - if( keyCode == KeyEvent.VK_N ) - return Input.Keys.KEYCODE_N; - if( keyCode == KeyEvent.VK_O ) - return Input.Keys.KEYCODE_O; - if( keyCode == KeyEvent.VK_P ) - return Input.Keys.KEYCODE_P; - if( keyCode == KeyEvent.VK_Q ) - return Input.Keys.KEYCODE_Q; - if( keyCode == KeyEvent.VK_R ) - return Input.Keys.KEYCODE_R; - if( keyCode == KeyEvent.VK_S ) - return Input.Keys.KEYCODE_S; - if( keyCode == KeyEvent.VK_T ) - return Input.Keys.KEYCODE_T; - if( keyCode == KeyEvent.VK_U ) - return Input.Keys.KEYCODE_U; - if( keyCode == KeyEvent.VK_V ) - return Input.Keys.KEYCODE_V; - if( keyCode == KeyEvent.VK_W ) - return Input.Keys.KEYCODE_W; - if( keyCode == KeyEvent.VK_X ) - return Input.Keys.KEYCODE_X; - if( keyCode == KeyEvent.VK_Y ) - return Input.Keys.KEYCODE_Y; - if( keyCode == KeyEvent.VK_Z ) - return Input.Keys.KEYCODE_Z; - if( keyCode == KeyEvent.VK_ALT ) - return Input.Keys.KEYCODE_ALT_LEFT; - if( keyCode == KeyEvent.VK_ALT_GRAPH ) - return Input.Keys.KEYCODE_ALT_RIGHT; - if( keyCode == KeyEvent.VK_BACK_SLASH ) - return Input.Keys.KEYCODE_BACKSLASH; - if( keyCode == KeyEvent.VK_COMMA ) - return Input.Keys.KEYCODE_COMMA; - if( keyCode == KeyEvent.VK_DELETE ) - return Input.Keys.KEYCODE_DEL; - if( keyCode == KeyEvent.VK_LEFT ) - return Input.Keys.KEYCODE_DPAD_LEFT; - if( keyCode == KeyEvent.VK_RIGHT ) - return Input.Keys.KEYCODE_DPAD_RIGHT; - if( keyCode == KeyEvent.VK_UP ) - return Input.Keys.KEYCODE_DPAD_UP; - if( keyCode == KeyEvent.VK_DOWN ) - return Input.Keys.KEYCODE_DPAD_DOWN; - if( keyCode == KeyEvent.VK_ENTER ) - return Input.Keys.KEYCODE_ENTER; - if( keyCode == KeyEvent.VK_HOME ) - return Input.Keys.KEYCODE_HOME; - if( keyCode == KeyEvent.VK_MINUS ) - return Input.Keys.KEYCODE_MINUS; - if( keyCode == KeyEvent.VK_PERIOD ) - return Input.Keys.KEYCODE_PERIOD; - if( keyCode == KeyEvent.VK_PLUS ) - return Input.Keys.KEYCODE_PLUS; - if( keyCode == KeyEvent.VK_SEMICOLON ) - return Input.Keys.KEYCODE_SEMICOLON; - if( keyCode == KeyEvent.VK_SHIFT ) - return Input.Keys.KEYCODE_SHIFT_LEFT; - if( keyCode == KeyEvent.VK_SLASH ) - return Input.Keys.KEYCODE_SLASH; - if( keyCode == KeyEvent.VK_SPACE ) - return Input.Keys.KEYCODE_SPACE; - if( keyCode == KeyEvent.VK_TAB ) - return Input.Keys.KEYCODE_TAB; - + + protected static int translateKeyCode (int keyCode) { + if (keyCode == KeyEvent.VK_0) return Input.Keys.KEYCODE_0; + if (keyCode == KeyEvent.VK_1) return Input.Keys.KEYCODE_1; + if (keyCode == KeyEvent.VK_2) return Input.Keys.KEYCODE_2; + if (keyCode == KeyEvent.VK_3) return Input.Keys.KEYCODE_3; + if (keyCode == KeyEvent.VK_4) return Input.Keys.KEYCODE_4; + if (keyCode == KeyEvent.VK_5) return Input.Keys.KEYCODE_5; + if (keyCode == KeyEvent.VK_6) return Input.Keys.KEYCODE_6; + if (keyCode == KeyEvent.VK_7) return Input.Keys.KEYCODE_7; + if (keyCode == KeyEvent.VK_8) return Input.Keys.KEYCODE_8; + if (keyCode == KeyEvent.VK_9) return Input.Keys.KEYCODE_9; + if (keyCode == KeyEvent.VK_A) return Input.Keys.KEYCODE_A; + if (keyCode == KeyEvent.VK_B) return Input.Keys.KEYCODE_B; + if (keyCode == KeyEvent.VK_C) return Input.Keys.KEYCODE_C; + if (keyCode == KeyEvent.VK_D) return Input.Keys.KEYCODE_D; + if (keyCode == KeyEvent.VK_E) return Input.Keys.KEYCODE_E; + if (keyCode == KeyEvent.VK_F) return Input.Keys.KEYCODE_F; + if (keyCode == KeyEvent.VK_G) return Input.Keys.KEYCODE_G; + if (keyCode == KeyEvent.VK_H) return Input.Keys.KEYCODE_H; + if (keyCode == KeyEvent.VK_I) return Input.Keys.KEYCODE_I; + if (keyCode == KeyEvent.VK_J) return Input.Keys.KEYCODE_J; + if (keyCode == KeyEvent.VK_K) return Input.Keys.KEYCODE_K; + if (keyCode == KeyEvent.VK_L) return Input.Keys.KEYCODE_L; + if (keyCode == KeyEvent.VK_M) return Input.Keys.KEYCODE_M; + if (keyCode == KeyEvent.VK_N) return Input.Keys.KEYCODE_N; + if (keyCode == KeyEvent.VK_O) return Input.Keys.KEYCODE_O; + if (keyCode == KeyEvent.VK_P) return Input.Keys.KEYCODE_P; + if (keyCode == KeyEvent.VK_Q) return Input.Keys.KEYCODE_Q; + if (keyCode == KeyEvent.VK_R) return Input.Keys.KEYCODE_R; + if (keyCode == KeyEvent.VK_S) return Input.Keys.KEYCODE_S; + if (keyCode == KeyEvent.VK_T) return Input.Keys.KEYCODE_T; + if (keyCode == KeyEvent.VK_U) return Input.Keys.KEYCODE_U; + if (keyCode == KeyEvent.VK_V) return Input.Keys.KEYCODE_V; + if (keyCode == KeyEvent.VK_W) return Input.Keys.KEYCODE_W; + if (keyCode == KeyEvent.VK_X) return Input.Keys.KEYCODE_X; + if (keyCode == KeyEvent.VK_Y) return Input.Keys.KEYCODE_Y; + if (keyCode == KeyEvent.VK_Z) return Input.Keys.KEYCODE_Z; + if (keyCode == KeyEvent.VK_ALT) return Input.Keys.KEYCODE_ALT_LEFT; + if (keyCode == KeyEvent.VK_ALT_GRAPH) return Input.Keys.KEYCODE_ALT_RIGHT; + if (keyCode == KeyEvent.VK_BACK_SLASH) return Input.Keys.KEYCODE_BACKSLASH; + if (keyCode == KeyEvent.VK_COMMA) return Input.Keys.KEYCODE_COMMA; + if (keyCode == KeyEvent.VK_DELETE) return Input.Keys.KEYCODE_DEL; + if (keyCode == KeyEvent.VK_LEFT) return Input.Keys.KEYCODE_DPAD_LEFT; + if (keyCode == KeyEvent.VK_RIGHT) return Input.Keys.KEYCODE_DPAD_RIGHT; + if (keyCode == KeyEvent.VK_UP) return Input.Keys.KEYCODE_DPAD_UP; + if (keyCode == KeyEvent.VK_DOWN) return Input.Keys.KEYCODE_DPAD_DOWN; + if (keyCode == KeyEvent.VK_ENTER) return Input.Keys.KEYCODE_ENTER; + if (keyCode == KeyEvent.VK_HOME) return Input.Keys.KEYCODE_HOME; + if (keyCode == KeyEvent.VK_MINUS) return Input.Keys.KEYCODE_MINUS; + if (keyCode == KeyEvent.VK_PERIOD) return Input.Keys.KEYCODE_PERIOD; + if (keyCode == KeyEvent.VK_PLUS) return Input.Keys.KEYCODE_PLUS; + if (keyCode == KeyEvent.VK_SEMICOLON) return Input.Keys.KEYCODE_SEMICOLON; + if (keyCode == KeyEvent.VK_SHIFT) return Input.Keys.KEYCODE_SHIFT_LEFT; + if (keyCode == KeyEvent.VK_SLASH) return Input.Keys.KEYCODE_SLASH; + if (keyCode == KeyEvent.VK_SPACE) return Input.Keys.KEYCODE_SPACE; + if (keyCode == KeyEvent.VK_TAB) return Input.Keys.KEYCODE_TAB; + return Input.Keys.KEYCODE_UNKNOWN; } } diff --git a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletMusic.java b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletMusic.java index c8eb949a3..39de22b10 100644 --- a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletMusic.java +++ b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletMusic.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.applet; import java.io.IOException; @@ -27,15 +25,11 @@ import javax.sound.sampled.UnsupportedAudioFileException; import com.badlogic.gdx.audio.Music; -public class AppletMusic implements Music, Runnable -{ - private enum State - { - Playing, - Stopped, - Paused +public class AppletMusic implements Music, Runnable { + private enum State { + Playing, Stopped, Paused } - + private State state = State.Stopped; private final Thread thread; private final AppletFileHandle file; @@ -44,182 +38,131 @@ public class AppletMusic implements Music, Runnable private final byte[] buffer; private boolean looping = false; private boolean disposed = false; - - public AppletMusic( AppletFileHandle handle ) throws UnsupportedAudioFileException, IOException, LineUnavailableException - { + + public AppletMusic (AppletFileHandle handle) throws UnsupportedAudioFileException, IOException, LineUnavailableException { this.file = handle; - - openAudioInputStream(); - AudioFormat audioFormat = ain.getFormat(); - line = AudioSystem.getSourceDataLine( audioFormat ); - line.open(audioFormat); //FIXME reduce latency, gotta reimplement the playback thread. + + openAudioInputStream(); + AudioFormat audioFormat = ain.getFormat(); + line = AudioSystem.getSourceDataLine(audioFormat); + line.open(audioFormat); // FIXME reduce latency, gotta reimplement the playback thread. line.start(); - buffer = new byte[10000*ain.getFormat().getFrameSize()]; + buffer = new byte[10000 * ain.getFormat().getFrameSize()]; ain.close(); ain = null; - - - thread = new Thread( this ); + + thread = new Thread(this); thread.setDaemon(true); thread.start(); } - - private void openAudioInputStream( ) throws UnsupportedAudioFileException, IOException - { - ain = AudioSystem.getAudioInputStream(file.getInputStream()); + + private void openAudioInputStream () throws UnsupportedAudioFileException, IOException { + ain = AudioSystem.getAudioInputStream(file.getInputStream()); AudioFormat baseFormat = ain.getFormat(); - AudioFormat decodedFormat = new AudioFormat( - AudioFormat.Encoding.PCM_SIGNED, - baseFormat.getSampleRate(), - 16, - baseFormat.getChannels(), - baseFormat.getChannels() * 2, - baseFormat.getSampleRate(), - false); - - ain = AudioSystem.getAudioInputStream(decodedFormat, ain); + AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, + baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false); + + ain = AudioSystem.getAudioInputStream(decodedFormat, ain); } - - @Override - public void dispose() - { + + @Override public void dispose () { disposed = true; try { thread.join(); line.close(); ain.close(); - } catch (Exception e) - { + } catch (Exception e) { // nothing we can do here - } + } } - @Override - public boolean isLooping() - { + @Override public boolean isLooping () { return looping; } - @Override - public boolean isPlaying() - { + @Override public boolean isPlaying () { return state == State.Playing; } - @Override - public void pause() - { - synchronized( this ) - { - if( state == State.Playing ) - state = State.Paused; + @Override public void pause () { + synchronized (this) { + if (state == State.Playing) state = State.Paused; } } - @Override - public void play() - { - synchronized( this ) - { - if( state == State.Playing ) - return; - - if( state == State.Paused ) - { + @Override public void play () { + synchronized (this) { + if (state == State.Playing) return; + + if (state == State.Paused) { state = State.Playing; return; } - - try - { + + try { openAudioInputStream(); state = State.Playing; - } - catch (Exception e) - { + } catch (Exception e) { state = State.Stopped; - } + } } } - @Override - public void stop() - { - synchronized( this ) - { - if( state == State.Stopped ) - return; - + @Override public void stop () { + synchronized (this) { + if (state == State.Stopped) return; + state = State.Stopped; line.flush(); try { ain.close(); - } catch (IOException e) - { + } catch (IOException e) { e.printStackTrace(); } ain = null; } } - - @Override - public void setLooping(boolean isLooping) - { + + @Override public void setLooping (boolean isLooping) { looping = isLooping; } - @Override - public void setVolume(float volume) - { - try - { - volume = Math.min( 1, volume ); - volume = Math.max( 0, volume ); + @Override public void setVolume (float volume) { + try { + volume = Math.min(1, volume); + volume = Math.max(0, volume); FloatControl control = (FloatControl)line.getControl(FloatControl.Type.MASTER_GAIN); - control.setValue( -80 + volume * 80 ); - } - catch( IllegalArgumentException ex ) - { + control.setValue(-80 + volume * 80); + } catch (IllegalArgumentException ex) { ex.printStackTrace(); } } - @Override - public void run() - { - int readBytes = 0; + @Override public void run () { + int readBytes = 0; long readSamples = 0; - - while( !disposed ) - { - synchronized( this ) - { - if( state == State.Playing ) - { - try - { - - readBytes = ain.read( buffer ); - - if( readBytes != -1 ) - { - int writtenBytes = line.write( buffer, 0, readBytes ); - while( writtenBytes != readBytes ) - writtenBytes += line.write( buffer, writtenBytes, readBytes - writtenBytes ); + + while (!disposed) { + synchronized (this) { + if (state == State.Playing) { + try { + + readBytes = ain.read(buffer); + + if (readBytes != -1) { + int writtenBytes = line.write(buffer, 0, readBytes); + while (writtenBytes != readBytes) + writtenBytes += line.write(buffer, writtenBytes, readBytes - writtenBytes); readSamples += readBytes / ain.getFormat().getFrameSize(); - } - else - { - System.out.println( "samples: " + readSamples ); + } else { + System.out.println("samples: " + readSamples); ain.close(); - if( !isLooping() ) + if (!isLooping()) state = State.Stopped; - else - openAudioInputStream(); - } - } - catch( Exception ex ) - { + else + openAudioInputStream(); + } + } catch (Exception ex) { try { ain.close(); } catch (IOException e) { @@ -231,14 +174,14 @@ public class AppletMusic implements Music, Runnable return; } } - + try { - Thread.sleep( 10 ); + Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } - } + } } diff --git a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletPanel.java b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletPanel.java index 73e60244b..6d9301c63 100644 --- a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletPanel.java +++ b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletPanel.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.applet; import java.awt.BorderLayout; @@ -39,339 +37,292 @@ import com.badlogic.gdx.math.WindowedMean; import com.sun.opengl.util.Animator; /** - * An OpenGL based graphics panel. Shares its context with all - * other GraphicPanels in the application. Has a continous render - * thread constantly invoking the paint method. Note that you have - * to dispose the panel before it is being removed from another + * An OpenGL based graphics panel. Shares its context with all other GraphicPanels in the application. Has a continous render + * thread constantly invoking the paint method. Note that you have to dispose the panel before it is being removed from another * gui component such as a JFrame. * * @author badlogicgames@gmail.com - * + * */ -final class AppletPanel extends JPanel implements GLEventListener, MouseMotionListener, MouseListener, KeyListener -{ +final class AppletPanel extends JPanel implements GLEventListener, MouseMotionListener, MouseListener, KeyListener { private static final long serialVersionUID = -3638194405409146221L; - + /** the context to be used by all GraphicPanels **/ - private static GLContext context = null; - + private static GLContext context = null; + /** the canvas object **/ private final GLCanvas canvas; - + /** animator for continous updates **/ - private final Animator animator; - + private final Animator animator; + /** vsynch flag **/ private boolean vSynch = true; - + /** last mouse position **/ - private final Point mousePosition = new Point( ); - + private final Point mousePosition = new Point(); + /** last mouse button states **/ - private final HashSet buttons = new HashSet( ); - + private final HashSet buttons = new HashSet(); + /** last key states **/ - private final HashSet keys = new HashSet( ); - + private final HashSet keys = new HashSet(); + /** listeners **/ - private final ArrayList listeners = new ArrayList( ); - + private final ArrayList listeners = new ArrayList(); + /** listeners **/ - private final ArrayList setupListeners = new ArrayList( ); - + private final ArrayList setupListeners = new ArrayList(); + /** start time of last frame **/ private long frameStart = System.nanoTime(); - + /** delta time between current and last frame **/ private float deltaTime = 0; - private WindowedMean mean = new WindowedMean(10); + private WindowedMean mean = new WindowedMean(10); + + private AppletInputMultiplexer multiplexer; - private AppletInputMultiplexer multiplexer; - /** - * Constructor loading the libraries if needed and creating/reusing a - * {@link GLContext}. A standard back/depth/stencil buffer combination is - * created (32-bit, 16-bit, 8-bit). Additionally an animator thread is - * created that is responsible for redrawing the panel as fast as possible in - * case the continous flag is set to true. - * Keyboard and Mouse events are processed by the panel so that a client - * can poll for specific states. + * Constructor loading the libraries if needed and creating/reusing a {@link GLContext}. A standard back/depth/stencil buffer + * combination is created (32-bit, 16-bit, 8-bit). Additionally an animator thread is created that is responsible for redrawing + * the panel as fast as possible in case the continous flag is set to true. Keyboard and Mouse events are processed by the + * panel so that a client can poll for specific states. */ - AppletPanel( Application application ) - { - super(); - + AppletPanel (Application application) { + super(); + GLCapabilities caps = new GLCapabilities(); caps.setRedBits(8); - caps.setGreenBits(8); - caps.setBlueBits(8); - caps.setAlphaBits(8); - caps.setDepthBits(16); - caps.setStencilBits(8); - caps.setNumSamples(0); - caps.setSampleBuffers(false); - caps.setDoubleBuffered(true); - - if( context == null ) - { - canvas = new GLCanvas( caps ); - context = canvas.getContext(); - } - else - canvas = new GLCanvas( caps, null, context, null ); - - canvas.addGLEventListener(this); - this.setLayout( new BorderLayout() ); - add(canvas,BorderLayout.CENTER); - - animator = new Animator( canvas ); - animator.start(); - - canvas.addMouseListener( this ); - canvas.addMouseMotionListener( this ); - canvas.addKeyListener( this ); + caps.setGreenBits(8); + caps.setBlueBits(8); + caps.setAlphaBits(8); + caps.setDepthBits(16); + caps.setStencilBits(8); + caps.setNumSamples(0); + caps.setSampleBuffers(false); + caps.setDoubleBuffered(true); + + if (context == null) { + canvas = new GLCanvas(caps); + context = canvas.getContext(); + } else + canvas = new GLCanvas(caps, null, context, null); + + canvas.addGLEventListener(this); + this.setLayout(new BorderLayout()); + add(canvas, BorderLayout.CENTER); + + animator = new Animator(canvas); + animator.start(); + + canvas.addMouseListener(this); + canvas.addMouseMotionListener(this); + canvas.addKeyListener(this); } - + /** * stops the animator thread and releases any resources */ - public void dispose( ) - { + public void dispose () { canvas.getContext().makeCurrent(); - for( RenderListener listener: listeners ) - listener.dispose( ); + for (RenderListener listener : listeners) + listener.dispose(); remove(canvas); - if( animator != null ) - animator.stop(); + if (animator != null) animator.stop(); } - - + /** * @return the delta time between the current and last frame */ - public float getDeltaTime( ) - { - return mean.hasEnoughData()?mean.getMean():deltaTime; + public float getDeltaTime () { + return mean.hasEnoughData() ? mean.getMean() : deltaTime; } - + /** * @return the underlying GLCanvas */ - public GLCanvas getCanvas( ) - { + public GLCanvas getCanvas () { return canvas; } - + /** * sets wheter vsynch is enabled or disabled. true by default. * * @param v_synch */ - public void setVerticalSynch( boolean v_synch ) - { - this.vSynch = v_synch; - if( v_synch ) + public void setVerticalSynch (boolean v_synch) { + this.vSynch = v_synch; + if (v_synch) GLContext.getCurrent().getGL().setSwapInterval(1); else GLContext.getCurrent().getGL().setSwapInterval(0); } - + /** * @return wheter vsynch is on or not */ - public boolean getVerticalSynch( ) - { + public boolean getVerticalSynch () { return vSynch; - } - - public void mouseDragged(MouseEvent arg0) - { + } + + public void mouseDragged (MouseEvent arg0) { mousePosition.x = arg0.getX(); mousePosition.y = arg0.getY(); - + } - public void mouseMoved(MouseEvent arg0) - { + public void mouseMoved (MouseEvent arg0) { mousePosition.x = arg0.getX(); - mousePosition.y = arg0.getY(); + mousePosition.y = arg0.getY(); } - public int getMouseX( ) - { + public int getMouseX () { return mousePosition.x; } - - public int getMouseY( ) - { + + public int getMouseY () { return mousePosition.y; } - - public void mouseClicked(MouseEvent arg0) { + + public void mouseClicked (MouseEvent arg0) { // TODO Auto-generated method stub - + } - public void mouseEntered(MouseEvent arg0) { + public void mouseEntered (MouseEvent arg0) { // TODO Auto-generated method stub - + } - public void mouseExited(MouseEvent arg0) { + public void mouseExited (MouseEvent arg0) { // TODO Auto-generated method stub - + } - public void mousePressed(MouseEvent arg0) - { - buttons.add( arg0.getButton() ); + public void mousePressed (MouseEvent arg0) { + buttons.add(arg0.getButton()); } - public void mouseReleased(MouseEvent arg0) - { - buttons.remove( arg0.getButton() ); + public void mouseReleased (MouseEvent arg0) { + buttons.remove(arg0.getButton()); } - public void keyPressed(KeyEvent arg0) - { - keys.add( AppletInputMultiplexer.translateKeyCode(arg0.getKeyCode()) ); + public void keyPressed (KeyEvent arg0) { + keys.add(AppletInputMultiplexer.translateKeyCode(arg0.getKeyCode())); } - public void keyReleased(KeyEvent arg0) - { -// getCanvas().getContext().makeCurrent(); - keys.remove( AppletInputMultiplexer.translateKeyCode(arg0.getKeyCode()) ); + public void keyReleased (KeyEvent arg0) { +// getCanvas().getContext().makeCurrent(); + keys.remove(AppletInputMultiplexer.translateKeyCode(arg0.getKeyCode())); } - public void keyTyped(KeyEvent arg0) { - + public void keyTyped (KeyEvent arg0) { + } /** - * returns wheter the given mousebutton is down. use - * the constants in {@link MouseEvent}. + * returns wheter the given mousebutton is down. use the constants in {@link MouseEvent}. * * @param button the button in question * @return wheter the button is down or not */ - public boolean isButtonDown( int button ) - { + public boolean isButtonDown (int button) { return buttons.size() > 0; } - + /** - * returns wheter the given key is down. use the - * constants in {@link KeyEvent}. + * returns wheter the given key is down. use the constants in {@link KeyEvent}. * * @param key the key in question * @return wheter the key is down or not */ - public boolean isKeyDown( int key ) - { - return keys.contains( key ); + public boolean isKeyDown (int key) { + return keys.contains(key); } - - /** - * adds a new graphic listener + + /** + * adds a new graphic listener * @param listener the listener */ - public void addGraphicListener( RenderListener listener ) - { - synchronized( this ) - { - setupListeners.add( listener ); - } + public void addGraphicListener (RenderListener listener) { + synchronized (this) { + setupListeners.add(listener); + } } - + /** - * removes a graphic listener + * removes a graphic listener * @param listener the listener */ - public void removeGraphicListener( RenderListener listener ) - { - synchronized( this ) - { + public void removeGraphicListener (RenderListener listener) { + synchronized (this) { setupListeners.remove(listener); - listeners.remove( listener ); - listener.dispose( ); + listeners.remove(listener); + listener.dispose(); } } - @Override - public void display(GLAutoDrawable arg0) - { - if( multiplexer != null ) - multiplexer.processEvents(); - deltaTime = (System.nanoTime() - frameStart ) / 1000000000.0f; + @Override public void display (GLAutoDrawable arg0) { + if (multiplexer != null) multiplexer.processEvents(); + deltaTime = (System.nanoTime() - frameStart) / 1000000000.0f; frameStart = System.nanoTime(); - mean.addValue( deltaTime ); - - synchronized( this ) - { - for( RenderListener listener: setupListeners ) - { - listener.surfaceCreated( ); - listener.surfaceChanged( this.getWidth(), this.getHeight() ); + mean.addValue(deltaTime); + + synchronized (this) { + for (RenderListener listener : setupListeners) { + listener.surfaceCreated(); + listener.surfaceChanged(this.getWidth(), this.getHeight()); } listeners.addAll(setupListeners); setupListeners.clear(); - - for( RenderListener listener: listeners ) - listener.render( ); + + for (RenderListener listener : listeners) + listener.render(); } - + } - @Override - public void displayChanged(GLAutoDrawable arg0, boolean arg1, boolean arg2) - { - deltaTime = (System.nanoTime() - frameStart ) / 1000000000.0f; + @Override public void displayChanged (GLAutoDrawable arg0, boolean arg1, boolean arg2) { + deltaTime = (System.nanoTime() - frameStart) / 1000000000.0f; frameStart = System.nanoTime(); - - for( RenderListener listener: listeners ) - listener.render( ); + + for (RenderListener listener : listeners) + listener.render(); } - @Override - public void init(GLAutoDrawable arg0) - { - for( RenderListener listener: listeners ) - listener.surfaceCreated( ); + @Override public void init (GLAutoDrawable arg0) { + for (RenderListener listener : listeners) + listener.surfaceCreated(); setVerticalSynch(true); } - @Override - public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4) - { - deltaTime = (System.nanoTime() - frameStart ) / 1000000000.0f; + @Override public void reshape (GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4) { + deltaTime = (System.nanoTime() - frameStart) / 1000000000.0f; frameStart = System.nanoTime(); - - for( RenderListener listener: listeners ) - { - listener.surfaceChanged( this.getWidth(), this.getHeight() ); - listener.render( ); + + for (RenderListener listener : listeners) { + listener.surfaceChanged(this.getWidth(), this.getHeight()); + listener.render(); } } - /** * @return the gl context this panel works on */ - public GL getGL( ) - { + public GL getGL () { return canvas.getGL(); } - public Point getLastMousePosition( ) - { + public Point getLastMousePosition () { return mousePosition; } - public void setInputMultiplexer(AppletInputMultiplexer inputMultiplexer) { + public void setInputMultiplexer (AppletInputMultiplexer inputMultiplexer) { multiplexer = inputMultiplexer; } - public boolean isAnyKeyDown() { + public boolean isAnyKeyDown () { return keys.size() > 0; } } diff --git a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletPixmap.java b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletPixmap.java index b21984421..4ce256d3c 100644 --- a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletPixmap.java +++ b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletPixmap.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.applet; import java.awt.AlphaComposite; @@ -25,219 +23,186 @@ import java.awt.image.BufferedImage; import com.badlogic.gdx.graphics.Pixmap; - /** * An implementation of Pixmap based on the java graphics framework. * * @author badlogicgames@gmail.com - * + * */ -final class AppletPixmap implements Pixmap -{ +final class AppletPixmap implements Pixmap { BufferedImage pixmap; Composite composite; - Color color = new Color( 0 ); + Color color = new Color(0); int strokeWidth = 1; - AppletPixmap( int width, int height, Pixmap.Format format ) - { - int internalformat = getInternalFormat( format ); + AppletPixmap (int width, int height, Pixmap.Format format) { + int internalformat = getInternalFormat(format); pixmap = new BufferedImage(width, height, internalformat); composite = AlphaComposite.Src; } - - AppletPixmap(BufferedImage image) - { + + AppletPixmap (BufferedImage image) { pixmap = image; } - private int getInternalFormat( Pixmap.Format format ) - { - if( format == Pixmap.Format.RGBA4444 || format == Pixmap.Format.RGBA8888 || format == Pixmap.Format.RGB565 ) + private int getInternalFormat (Pixmap.Format format) { + if (format == Pixmap.Format.RGBA4444 || format == Pixmap.Format.RGBA8888 || format == Pixmap.Format.RGB565) return BufferedImage.TYPE_4BYTE_ABGR; else return BufferedImage.TYPE_BYTE_GRAY; } - + /** * {@inheritDoc} */ - @Override - public void drawCircle(int x, int y, int radius) { + @Override public void drawCircle (int x, int y, int radius) { Graphics2D g = (Graphics2D)pixmap.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.setComposite( composite ); - g.setColor( color ); - g.setStroke( new BasicStroke( strokeWidth ) ); - g.drawRect(x, y, radius * 2, radius * 2); + g.setComposite(composite); + g.setColor(color); + g.setStroke(new BasicStroke(strokeWidth)); + g.drawRect(x, y, radius * 2, radius * 2); g.dispose(); - + } /** * {@inheritDoc} */ - @Override - public void drawLine(int x, int y, int x2, int y2) { - Graphics2D g = (Graphics2D)pixmap.getGraphics(); + @Override public void drawLine (int x, int y, int x2, int y2) { + Graphics2D g = (Graphics2D)pixmap.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.setComposite( composite ); - g.setColor( color ); - g.setStroke( new BasicStroke( strokeWidth ) ); - g.drawLine(x, y, x2, y2); + g.setComposite(composite); + g.setColor(color); + g.setStroke(new BasicStroke(strokeWidth)); + g.drawLine(x, y, x2, y2); g.dispose(); - + } /** * {@inheritDoc} */ - @Override - public void drawRectangle(int x, int y, int width, int height) { - Graphics2D g = (Graphics2D)pixmap.getGraphics(); + @Override public void drawRectangle (int x, int y, int width, int height) { + Graphics2D g = (Graphics2D)pixmap.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.setComposite( composite ); - g.setColor( color ); - g.setStroke( new BasicStroke( strokeWidth ) ); - g.drawRect(x, y, width, height); + g.setComposite(composite); + g.setColor(color); + g.setStroke(new BasicStroke(strokeWidth)); + g.drawRect(x, y, width, height); g.dispose(); } /** * {@inheritDoc} */ - @Override - public void fill() - { - Graphics2D g = (Graphics2D)pixmap.getGraphics(); + @Override public void fill () { + Graphics2D g = (Graphics2D)pixmap.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.setComposite( composite ); - g.setColor( color ); - g.fillRect( 0, 0, pixmap.getWidth(), pixmap.getHeight() ); + g.setComposite(composite); + g.setColor(color); + g.fillRect(0, 0, pixmap.getWidth(), pixmap.getHeight()); g.dispose(); } /** * {@inheritDoc} */ - @Override - public void fillCircle(int x, int y, int radius) - { - Graphics2D g = (Graphics2D)pixmap.getGraphics(); + @Override public void fillCircle (int x, int y, int radius) { + Graphics2D g = (Graphics2D)pixmap.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.setComposite( composite ); - g.setColor( color ); - g.fillOval( x, y, radius * 2, radius * 2); + g.setComposite(composite); + g.setColor(color); + g.fillOval(x, y, radius * 2, radius * 2); g.dispose(); } /** * {@inheritDoc} */ - @Override - public void fillRectangle(int x, int y, int width, int height) - { - Graphics2D g = (Graphics2D)pixmap.getGraphics(); + @Override public void fillRectangle (int x, int y, int width, int height) { + Graphics2D g = (Graphics2D)pixmap.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.setComposite( composite ); - g.setColor( color ); - g.fillRect( x, y, width, height ); + g.setComposite(composite); + g.setColor(color); + g.fillRect(x, y, width, height); g.dispose(); } /** * {@inheritDoc} */ - @Override - public Object getNativePixmap() - { + @Override public Object getNativePixmap () { return pixmap; } /** * {@inheritDoc} */ - @Override - public void setColor(float r, float g, float b, float a) - { - color = new Color( r, g, b, a ); + @Override public void setColor (float r, float g, float b, float a) { + color = new Color(r, g, b, a); } /** * {@inheritDoc} */ - @Override - public void setStrokeWidth(int width) - { + @Override public void setStrokeWidth (int width) { strokeWidth = width; } /** * {@inheritDoc} */ - @Override - public int getPixel(int x, int y) - { - if( x < 0 || x >= pixmap.getWidth() ) - return 0; - if( y < 0 || y >= pixmap.getHeight() ) - return 0; + @Override public int getPixel (int x, int y) { + if (x < 0 || x >= pixmap.getWidth()) return 0; + if (y < 0 || y >= pixmap.getHeight()) return 0; return pixmap.getRGB(x, y); } /** * {@inheritDoc} */ - @Override - public int getHeight() { + @Override public int getHeight () { return pixmap.getHeight(); } /** * {@inheritDoc} */ - @Override - public int getWidth() { + @Override public int getWidth () { return pixmap.getWidth(); } /** * {@inheritDoc} */ - @Override - public void drawPixmap(Pixmap pixmap, int x, int y, int srcx, int srcy, int width, int height) - { + @Override public void drawPixmap (Pixmap pixmap, int x, int y, int srcx, int srcy, int width, int height) { BufferedImage image = (BufferedImage)pixmap.getNativePixmap(); - + Graphics2D g = (Graphics2D)this.pixmap.getGraphics(); - g.setComposite( composite ); - g.drawImage(image, x, y, x + width, y + height, - srcx, srcy, srcx + width, srcy + height, null); + g.setComposite(composite); + g.drawImage(image, x, y, x + width, y + height, srcx, srcy, srcx + width, srcy + height, null); g.dispose(); - + } /** * {@inheritDoc} */ - @Override - public void dispose() { + @Override public void dispose () { // TODO Auto-generated method stub - + } /** * {@inheritDoc} */ - @Override - public void getPixelRow(int[] pixels, int y) - { - for( int x = 0; x < pixmap.getWidth(); x++ ) - { + @Override public void getPixelRow (int[] pixels, int y) { + for (int x = 0; x < pixmap.getWidth(); x++) { pixels[x] = pixmap.getRGB(x, y); } - + } - + } diff --git a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletSound.java b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletSound.java index 55e50c471..3e7ffbcb1 100644 --- a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletSound.java +++ b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletSound.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.applet; import java.io.BufferedInputStream; @@ -32,167 +30,129 @@ import javax.sound.sampled.UnsupportedAudioFileException; import com.badlogic.gdx.audio.Sound; /** - * Implements the {@link Sound} interface for the desktop - * using {@link Clip}s internally. + * Implements the {@link Sound} interface for the desktop using {@link Clip}s internally. * @author mzechner - * + * */ -public class AppletSound implements Sound -{ +public class AppletSound implements Sound { /** the audio format **/ private final AudioFormat format; - + /** the audio data **/ private final byte[] originalSamples; - + /** the float audio data **/ private float[] samples; - + /** the audio instance **/ private final AppletAudio audio; - - public AppletSound( AppletAudio audio, AppletFileHandle file ) throws UnsupportedAudioFileException, IOException - { + public AppletSound (AppletAudio audio, AppletFileHandle file) throws UnsupportedAudioFileException, IOException { this.audio = audio; - InputStream fin = new BufferedInputStream( file.getInputStream() ); - AudioInputStream ain = AudioSystem.getAudioInputStream( fin ); + InputStream fin = new BufferedInputStream(file.getInputStream()); + AudioInputStream ain = AudioSystem.getAudioInputStream(fin); AudioFormat baseFormat = ain.getFormat(); - AudioFormat decodedFormat = new AudioFormat( - AudioFormat.Encoding.PCM_SIGNED, - baseFormat.getSampleRate(), - 16, - baseFormat.getChannels(), - baseFormat.getChannels() * 2, - baseFormat.getSampleRate(), - false); - - ain = AudioSystem.getAudioInputStream(decodedFormat, ain); + AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, + baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false); + + ain = AudioSystem.getAudioInputStream(decodedFormat, ain); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - byte[] buffer = new byte[1024*10]; - int readBytes = ain.read( buffer ); - while( readBytes != -1 ) - { - bytes.write( buffer, 0, readBytes ); - readBytes = ain.read( buffer ); - } + byte[] buffer = new byte[1024 * 10]; + int readBytes = ain.read(buffer); + while (readBytes != -1) { + bytes.write(buffer, 0, readBytes); + readBytes = ain.read(buffer); + } ain.close(); System.out.println(decodedFormat); format = decodedFormat; - originalSamples = bytes.toByteArray(); - - ByteBuffer tmpBuffer = ByteBuffer.wrap( originalSamples ); + originalSamples = bytes.toByteArray(); + + ByteBuffer tmpBuffer = ByteBuffer.wrap(originalSamples); tmpBuffer.order(ByteOrder.LITTLE_ENDIAN); ShortBuffer shorts = tmpBuffer.asShortBuffer(); - samples = new float[originalSamples.length/2]; - for( int i = 0; i < samples.length; i++ ) - { + samples = new float[originalSamples.length / 2]; + for (int i = 0; i < samples.length; i++) { float value = shorts.get(i) / (float)Short.MAX_VALUE; - if( value < -1 ) - value = -1; - if( value > 1 ) - value = 1; + if (value < -1) value = -1; + if (value > 1) value = 1; samples[i] = value; } - - samples = resample( samples, decodedFormat.getSampleRate(), decodedFormat.getChannels() == 1 ); + + samples = resample(samples, decodedFormat.getSampleRate(), decodedFormat.getChannels() == 1); } - - private float[] resample( float[] samples, float sampleRate, boolean isMono ) - { - if( sampleRate == 44100 ) - return samples; - + + private float[] resample (float[] samples, float sampleRate, boolean isMono) { + if (sampleRate == 44100) return samples; + float idxInc = sampleRate / 44100; int numSamples = (int)((samples.length / (float)sampleRate) * 44100); - if( !isMono && numSamples % 2 != 0 ) - numSamples--; - + if (!isMono && numSamples % 2 != 0) numSamples--; + float[] newSamples = new float[numSamples]; - - if( isMono ) - { + + if (isMono) { float idx = 0; - for( int i = 0; i < newSamples.length; i++ ) - { - int intIdx = (int)idx; - if( intIdx >= samples.length - 1 ) - break; - - float value = samples[intIdx] + samples[intIdx+1]; + for (int i = 0; i < newSamples.length; i++) { + int intIdx = (int)idx; + if (intIdx >= samples.length - 1) break; + + float value = samples[intIdx] + samples[intIdx + 1]; value /= 2; - if( value > 1 ) - value = 1; - if( value < -1 ) - value = -1; + if (value > 1) value = 1; + if (value < -1) value = -1; newSamples[i] = value; idx += idxInc; } - } - else - { - float idx = 0; - for( int i = 0; i < newSamples.length; i+=2 ) - { - int intIdxL = (int)idx * 2; + } else { + float idx = 0; + for (int i = 0; i < newSamples.length; i += 2) { + int intIdxL = (int)idx * 2; int intIdxR = (int)idx * 2 + 1; - if( intIdxL >= samples.length - 2 ) - break; - - float value = samples[intIdxL] + samples[intIdxL+2]; + if (intIdxL >= samples.length - 2) break; + + float value = samples[intIdxL] + samples[intIdxL + 2]; value /= 2; - if( value > 1 ) - value = 1; - if( value < -1 ) - value = -1; + if (value > 1) value = 1; + if (value < -1) value = -1; newSamples[i] = value; - - value = samples[intIdxR] + samples[intIdxR+2]; + + value = samples[intIdxR] + samples[intIdxR + 2]; value /= 2; - if( value > 1 ) - value = 1; - if( value < -1 ) - value = -1; - newSamples[i+1] = value; - + if (value > 1) value = 1; + if (value < -1) value = -1; + newSamples[i + 1] = value; + idx += idxInc; } } - + return newSamples; } - - @Override - public void dispose() - { - + + @Override public void dispose () { + } - @Override - public void play() - { - audio.enqueueSound( this, 1 ); + @Override public void play () { + audio.enqueueSound(this, 1); } - - @Override - public void play( float volume ) - { - audio.enqueueSound( this, volume ); + + @Override public void play (float volume) { + audio.enqueueSound(this, volume); } /** * @return the {@link AudioFormat} of the audio data */ - public AudioFormat getAudioFormat() - { + public AudioFormat getAudioFormat () { return format; } /** * @return the audio samples in form of a byte array */ - public float[] getAudioData() - { + public float[] getAudioData () { return samples; } diff --git a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletTexture.java b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletTexture.java index b9cf4deac..66f15ba65 100644 --- a/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletTexture.java +++ b/backends/gdx-backend-applet/src/com/badlogic/gdx/backends/applet/AppletTexture.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.applet; import java.awt.image.BufferedImage; @@ -31,164 +29,148 @@ import com.sun.opengl.util.texture.TextureIO; * An implementation of {@link Texture} based on Jogl * * @author badlogicgames@gmail.com - * + * */ -final class AppletTexture implements Texture -{ +final class AppletTexture implements Texture { /** height in pixels of texture **/ private int texHeight; /** width in pixels of texture **/ - private int texWidth; + private int texWidth; /** texture wrapper **/ com.sun.opengl.util.texture.Texture texture; /** whether this textures i managed or not **/ private final boolean isManaged; - + /** global number of textures **/ public static int textures = 0; - + /** * Create a new texture - * + * * @param textureID The GL texture ID */ - AppletTexture(InputStream in, TextureFilter minFilter, TextureFilter maxFilter, TextureWrap uWrap, TextureWrap vWrap, boolean managed ) - { + AppletTexture (InputStream in, TextureFilter minFilter, TextureFilter maxFilter, TextureWrap uWrap, TextureWrap vWrap, + boolean managed) { this.isManaged = managed; - try - { - BufferedImage image = ImageIO.read(in); - texture = com.sun.opengl.util.texture.TextureIO.newTexture( image, minFilter == TextureFilter.MipMap?true:false ); - } - catch( Exception ex ) - { - throw new RuntimeException( ex ); + try { + BufferedImage image = ImageIO.read(in); + texture = com.sun.opengl.util.texture.TextureIO.newTexture(image, minFilter == TextureFilter.MipMap ? true : false); + } catch (Exception ex) { + throw new RuntimeException(ex); } GL gl = GLContext.getCurrent().getGL(); - - bind(); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, getTextureFilter( minFilter ) ); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, getTextureFilter( maxFilter ) ); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, getTextureWrap( uWrap ) ); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, getTextureWrap( vWrap ) ); + + bind(); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, getTextureFilter(minFilter)); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, getTextureFilter(maxFilter)); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, getTextureWrap(uWrap)); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, getTextureWrap(vWrap)); this.texWidth = texture.getWidth(); this.texHeight = texture.getHeight(); textures++; - } - - AppletTexture(BufferedImage image, TextureFilter minFilter, TextureFilter maxFilter, TextureWrap uWrap, TextureWrap vWrap, boolean managed ) - { - this.isManaged = managed; - texture = com.sun.opengl.util.texture.TextureIO.newTexture( image, minFilter == TextureFilter.MipMap?true:false ); + } + + AppletTexture (BufferedImage image, TextureFilter minFilter, TextureFilter maxFilter, TextureWrap uWrap, TextureWrap vWrap, + boolean managed) { + this.isManaged = managed; + texture = com.sun.opengl.util.texture.TextureIO.newTexture(image, minFilter == TextureFilter.MipMap ? true : false); GL gl = GLContext.getCurrent().getGL(); - - bind(); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, getTextureFilter( minFilter ) ); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, getTextureFilter( maxFilter ) ); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, getTextureWrap( uWrap ) ); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, getTextureWrap( vWrap ) ); + + bind(); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, getTextureFilter(minFilter)); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, getTextureFilter(maxFilter)); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, getTextureWrap(uWrap)); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, getTextureWrap(vWrap)); this.texWidth = texture.getWidth(); this.texHeight = texture.getHeight(); textures++; - } - + } + /** * Create a new texture - * + * * @param textureID The GL texture ID */ - AppletTexture(int width, int height, int format, TextureFilter minFilter, TextureFilter maxFilter, TextureWrap uWrap, TextureWrap vWrap, boolean managed ) - { + AppletTexture (int width, int height, int format, TextureFilter minFilter, TextureFilter maxFilter, TextureWrap uWrap, + TextureWrap vWrap, boolean managed) { this.isManaged = managed; - BufferedImage image = new BufferedImage( width, height, format ); - texture = com.sun.opengl.util.texture.TextureIO.newTexture( image, minFilter == TextureFilter.MipMap?true:false ); - + BufferedImage image = new BufferedImage(width, height, format); + texture = com.sun.opengl.util.texture.TextureIO.newTexture(image, minFilter == TextureFilter.MipMap ? true : false); + GL gl = GLContext.getCurrent().getGL(); - - bind(); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, getTextureFilter( minFilter ) ); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, getTextureFilter( maxFilter ) ); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, getTextureWrap( uWrap ) ); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, getTextureWrap( vWrap ) ); + + bind(); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, getTextureFilter(minFilter)); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, getTextureFilter(maxFilter)); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, getTextureWrap(uWrap)); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, getTextureWrap(vWrap)); this.texWidth = texture.getWidth(); this.texHeight = texture.getHeight(); textures++; } - private int getTextureFilter( TextureFilter filter ) - { - if( filter == TextureFilter.Linear ) + private int getTextureFilter (TextureFilter filter) { + if (filter == TextureFilter.Linear) return GL.GL_LINEAR; - else - if( filter == TextureFilter.Nearest ) + else if (filter == TextureFilter.Nearest) return GL.GL_NEAREST; else return GL.GL_LINEAR_MIPMAP_LINEAR; } - - private int getTextureWrap( TextureWrap wrap ) - { - if( wrap == TextureWrap.ClampToEdge ) + + private int getTextureWrap (TextureWrap wrap) { + if (wrap == TextureWrap.ClampToEdge) return GL.GL_CLAMP_TO_EDGE; else return GL.GL_REPEAT; } - - public boolean isManaged( ) - { + + public boolean isManaged () { return isManaged; } - + /** * {@inheritDoc} */ - @Override - public void bind() - { + @Override public void bind () { texture.bind(); } /** * {@inheritDoc} */ - @Override - public void dispose() { - texture.dispose(); - textures--; + @Override public void dispose () { + texture.dispose(); + textures--; } /** * {@inheritDoc} */ - @Override - public int getHeight() { + @Override public int getHeight () { return texHeight; } /** * {@inheritDoc} */ - @Override - public int getWidth() { + @Override public int getWidth () { return texWidth; } /** * {@inheritDoc} */ - public void draw( Pixmap pixmap, int x, int y ) - { + public void draw (Pixmap pixmap, int x, int y) { TextureData data = TextureIO.newTextureData((BufferedImage)pixmap.getNativePixmap(), true); texture.bind(); - texture.updateSubImage( data, 0, x, y ); + texture.updateSubImage(data, 0, x, y); } /** * {@inheritDoc} */ - @Override - public int getTextureObjectHandle() - { + @Override public int getTextureObjectHandle () { return texture.getTextureObject(); } } diff --git a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglApplication.java b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglApplication.java index 8ba24046a..c8fedaffa 100644 --- a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglApplication.java +++ b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglApplication.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.desktop; import com.badlogic.gdx.Application; @@ -29,124 +27,99 @@ import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.GL11; /** - * An implemenation of the {@link Application} interface based on Jogl for Windows, Linux and Mac. Instantiate - * this class with apropriate parameters and then register {@link ApplicationListener}, {@link RenderListener} or {@link InputListener} - * instances. + * An implemenation of the {@link Application} interface based on Jogl for Windows, Linux and Mac. Instantiate this class with + * apropriate parameters and then register {@link ApplicationListener}, {@link RenderListener} or {@link InputListener} instances. * * @author mzechner - * + * */ -public final class JoglApplication implements Application -{ - static - { +public final class JoglApplication implements Application { + static { Version.loadLibrary(); } - /** the graphics instance **/ private final JoglGraphics graphics; - + /** the input instance **/ private final JoglInput input; - + /** the audio instance **/ private final JoglAudio audio; - + /** the DestroyListener **/ ApplicationListener listener; - + /** - * Creates a new {@link JoglApplication} with the given - * title and dimensions. If useGL20IfAvailable is set the - * JoglApplication will try to create an OpenGL 2.0 context - * which can then be used via {@link JoglApplication.getGraphics().getGL20()}. The - * {@link GL10} and {@link GL11} interfaces should not be used when - * OpenGL 2.0 is enabled. To query whether enabling OpenGL 2.0 was - * successful use the {@link JoglApplication.getGraphics().isGL20Available()} - * method. + * Creates a new {@link JoglApplication} with the given title and dimensions. If useGL20IfAvailable is set the JoglApplication + * will try to create an OpenGL 2.0 context which can then be used via {@link JoglApplication.getGraphics().getGL20()}. The + * {@link GL10} and {@link GL11} interfaces should not be used when OpenGL 2.0 is enabled. To query whether enabling OpenGL 2.0 + * was successful use the {@link JoglApplication.getGraphics().isGL20Available()} method. * * @param title the title of the application * @param width the width of the surface in pixels * @param height the height of the surface in pixels * @param useGL20IfAvailable wheter to use OpenGL 2.0 if it is available or not */ - public JoglApplication( String title, int width, int height, boolean useGL20IfAvailable ) - { - graphics = new JoglGraphics( this, title, width, height, useGL20IfAvailable ); - input = new JoglInput( graphics.graphicPanel ); - audio = new JoglAudio( ); - + public JoglApplication (String title, int width, int height, boolean useGL20IfAvailable) { + graphics = new JoglGraphics(this, title, width, height, useGL20IfAvailable); + input = new JoglInput(graphics.graphicPanel); + audio = new JoglAudio(); + Gdx.app = this; Gdx.graphics = this.getGraphics(); Gdx.input = this.getInput(); Gdx.audio = this.getAudio(); Gdx.files = this.getFiles(); } - + /** * {@inheritDoc} */ - @Override - public Audio getAudio() - { + @Override public Audio getAudio () { return audio; } /** * {@inheritDoc} */ - @Override - public Files getFiles() - { - return new JoglFiles( ); + @Override public Files getFiles () { + return new JoglFiles(); } /** * {@inheritDoc} */ - @Override - public Graphics getGraphics() - { + @Override public Graphics getGraphics () { return graphics; } /** * {@inheritDoc} */ - @Override - public Input getInput() - { + @Override public Input getInput () { return input; } /** * {@inheritDoc} */ - @Override - public void setApplicationListener(ApplicationListener listener) - { + @Override public void setApplicationListener (ApplicationListener listener) { this.listener = listener; } - @Override - public void log(String tag, String message) - { - System.out.println( tag + ": " + message ); + @Override public void log (String tag, String message) { + System.out.println(tag + ": " + message); } /** * {@inheritDoc} */ - @Override - public ApplicationType getType() - { + @Override public ApplicationType getType () { return ApplicationType.Desktop; } - - @Override - public int getVersion() - { + + @Override public int getVersion () { return 0; } diff --git a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglAudio.java b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglAudio.java index 99d0e685a..df28ccf40 100644 --- a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglAudio.java +++ b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglAudio.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.desktop; import java.util.ArrayList; @@ -35,161 +33,135 @@ import com.badlogic.gdx.files.FileHandle; * An implementation of the {@link Audio} interface for the desktop. * * @author mzechner - * + * */ -final class JoglAudio implements Audio, Runnable -{ +final class JoglAudio implements Audio, Runnable { /** the audio line for sound effects **/ private SourceDataLine line; - - /** The current buffers to play **/ - private final List buffers = new ArrayList( ); - + + /** The current buffers to play **/ + private final List buffers = new ArrayList(); + /** The sound effects thread **/ private Thread thread; - + /** * Helper class for playing back sound effects concurrently. * * @author mzechner - * + * */ - class JoglSoundBuffer - { + class JoglSoundBuffer { private final float[] samples; private final AudioFormat format; private final float volume; private int writtenSamples = 0; - - public JoglSoundBuffer( JoglSound sound, float volume ) throws Exception - { - samples = sound.getAudioData( ); + + public JoglSoundBuffer (JoglSound sound, float volume) throws Exception { + samples = sound.getAudioData(); format = sound.getAudioFormat(); this.volume = volume; } - + /** - * Writes the next numFrames frames to the line for playback + * Writes the next numFrames frames to the line for playback * @return whether playback is done or not. */ - public boolean writeSamples( int numSamples, float[] buffer ) - { - if( format.getChannels() == 1 ) - { - int remainingSamples = Math.min( samples.length, writtenSamples + numSamples / 2 ); - for( int i = writtenSamples, j = 0; i < remainingSamples; i++, j+=2 ) - { + public boolean writeSamples (int numSamples, float[] buffer) { + if (format.getChannels() == 1) { + int remainingSamples = Math.min(samples.length, writtenSamples + numSamples / 2); + for (int i = writtenSamples, j = 0; i < remainingSamples; i++, j += 2) { buffer[j] += samples[i] * volume; - buffer[j+1] += samples[i] * volume; + buffer[j + 1] += samples[i] * volume; writtenSamples++; } - } - else - { - int remainingSamples = Math.min( samples.length, writtenSamples + numSamples ); - for( int i = writtenSamples, j = 0; i < remainingSamples; i+= 2, j+=2 ) - { + } else { + int remainingSamples = Math.min(samples.length, writtenSamples + numSamples); + for (int i = writtenSamples, j = 0; i < remainingSamples; i += 2, j += 2) { buffer[j] += samples[i] * volume; - buffer[j+1] += samples[i+1] * volume; - writtenSamples+=2; - } - } - - if( writtenSamples >= samples.length ) + buffer[j + 1] += samples[i + 1] * volume; + writtenSamples += 2; + } + } + + if (writtenSamples >= samples.length) return false; else return true; } } - - JoglAudio( ) - { + + JoglAudio () { try { - AudioFormat format = new AudioFormat( 44100.0f, 16, 2, true, false ); - line = AudioSystem.getSourceDataLine( format ); + AudioFormat format = new AudioFormat(44100.0f, 16, 2, true, false); + line = AudioSystem.getSourceDataLine(format); line.open(format, 4410); line.start(); - thread = new Thread( this ); - thread.setDaemon( true ); + thread = new Thread(this); + thread.setDaemon(true); thread.start(); } catch (Exception e) { e.printStackTrace(); - } + } } - + /** * {@inheritDoc} */ - @Override - public AudioDevice newAudioDevice(boolean isMono) - { - return new JoglAudioDevice( isMono ); + @Override public AudioDevice newAudioDevice (boolean isMono) { + return new JoglAudioDevice(isMono); } /** * {@inheritDoc} */ - @Override - public Music newMusic(FileHandle file) - { - try { - JoglMusic music = new JoglMusic( ((JoglFileHandle)file) ); + @Override public Music newMusic (FileHandle file) { + try { + JoglMusic music = new JoglMusic(((JoglFileHandle)file)); return music; - } - catch (Exception e) - { - throw new GdxRuntimeException( "Couldn't create Music instance from file '" + file + "'", e ); + } catch (Exception e) { + throw new GdxRuntimeException("Couldn't create Music instance from file '" + file + "'", e); } } /** * {@inheritDoc} */ - @Override - public Sound newSound(FileHandle file) { - try { - JoglSound sound = new JoglSound( this, ((JoglFileHandle)file) ); + @Override public Sound newSound (FileHandle file) { + try { + JoglSound sound = new JoglSound(this, ((JoglFileHandle)file)); return sound; } catch (Exception e) { - throw new GdxRuntimeException( "Couldn't create Sound instance from file '" + file + "'", e ); + throw new GdxRuntimeException("Couldn't create Sound instance from file '" + file + "'", e); } } - protected void enqueueSound( JoglSound sound, float volume ) - { - try - { - synchronized( this ) - { - buffers.add( new JoglSoundBuffer( sound, volume ) ); + protected void enqueueSound (JoglSound sound, float volume) { + try { + synchronized (this) { + buffers.add(new JoglSoundBuffer(sound, volume)); } - } - catch( Exception ex ) - { + } catch (Exception ex) { ex.printStackTrace(); } } - - @Override - public void run() - { - + + @Override public void run () { + int NUM_SAMPLES = 44100 * 2; float[] buffer = new float[NUM_SAMPLES]; - byte[] bytes = new byte[2 * NUM_SAMPLES]; - - while( true ) - { - int samplesToWrite = line.available() / 2; - - if( samplesToWrite > 0 ) - { - fillBuffer( buffer, bytes, samplesToWrite ); - int writtenBytes = line.write(bytes, 0, samplesToWrite * 2 ); - while( writtenBytes != samplesToWrite * 2 ) - writtenBytes += line.write( bytes, writtenBytes, samplesToWrite - writtenBytes ); + byte[] bytes = new byte[2 * NUM_SAMPLES]; + + while (true) { + int samplesToWrite = line.available() / 2; + + if (samplesToWrite > 0) { + fillBuffer(buffer, bytes, samplesToWrite); + int writtenBytes = line.write(bytes, 0, samplesToWrite * 2); + while (writtenBytes != samplesToWrite * 2) + writtenBytes += line.write(bytes, writtenBytes, samplesToWrite - writtenBytes); } - + try { Thread.sleep(5); } catch (InterruptedException e) { @@ -197,47 +169,38 @@ final class JoglAudio implements Audio, Runnable } } } - - private void fillBuffer( float[] buffer, byte[] bytes, int samplesToWrite ) - { - for( int i = 0; i < buffer.length; i++ ) + + private void fillBuffer (float[] buffer, byte[] bytes, int samplesToWrite) { + for (int i = 0; i < buffer.length; i++) buffer[i] = 0.0f; - for( int i = 0; i < bytes.length; i++ ) + for (int i = 0; i < bytes.length; i++) bytes[i] = 0; - + int numBuffers = buffers.size(); - synchronized( this ) - { + synchronized (this) { Iterator bufferIter = buffers.iterator(); - while( bufferIter.hasNext() ) - { + while (bufferIter.hasNext()) { JoglSoundBuffer soundBuffer = bufferIter.next(); - if( !soundBuffer.writeSamples(samplesToWrite, buffer) ) - bufferIter.remove(); + if (!soundBuffer.writeSamples(samplesToWrite, buffer)) bufferIter.remove(); } - } - - if( numBuffers > 0 ) - { - for( int i = 0, j = 0; i < samplesToWrite; i++, j+=2 ) - { - float fValue = buffer[i]; - if( fValue > 1 ) - fValue = 1; - if( fValue < -1 ) - fValue = -1; - short value = (short)( fValue * Short.MAX_VALUE); - bytes[j] = (byte)(value | 0xff); - bytes[j+1] = (byte)(value >> 8 ); - } - } + } + + if (numBuffers > 0) { + for (int i = 0, j = 0; i < samplesToWrite; i++, j += 2) { + float fValue = buffer[i]; + if (fValue > 1) fValue = 1; + if (fValue < -1) fValue = -1; + short value = (short)(fValue * Short.MAX_VALUE); + bytes[j] = (byte)(value | 0xff); + bytes[j + 1] = (byte)(value >> 8); + } + } } /** * {@inheritDoc} */ - @Override - public AudioRecorder newAudioRecoder(int samplingRate, boolean isMono) { - return new JoglAudioRecorder( samplingRate, isMono ); + @Override public AudioRecorder newAudioRecoder (int samplingRate, boolean isMono) { + return new JoglAudioRecorder(samplingRate, isMono); } } diff --git a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglAudioDevice.java b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglAudioDevice.java index b597039be..bd63b983e 100644 --- a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglAudioDevice.java +++ b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglAudioDevice.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.desktop; import javax.sound.sampled.AudioFormat; @@ -23,88 +21,71 @@ import com.badlogic.gdx.GdxRuntimeException; import com.badlogic.gdx.audio.AudioDevice; /** - * Implementation of the {@link AudioDevice} interface for the - * desktop using Java Sound. + * Implementation of the {@link AudioDevice} interface for the desktop using Java Sound. * * @author mzechner - * + * */ -public final class JoglAudioDevice implements AudioDevice -{ +public final class JoglAudioDevice implements AudioDevice { /** the audio line **/ private SourceDataLine line; - + /** whether this device is mono **/ private final boolean isMono; - + /** byte buffer **/ - private byte[] bytes = new byte[44100*2*2]; - - public JoglAudioDevice( boolean isMono ) - { + private byte[] bytes = new byte[44100 * 2 * 2]; + + public JoglAudioDevice (boolean isMono) { this.isMono = isMono; - + try { - AudioFormat format = new AudioFormat( 44100.0f, 16, isMono?1:2, true, false ); - line = AudioSystem.getSourceDataLine( format ); - line.open(format, 4410*2); - line.start(); + AudioFormat format = new AudioFormat(44100.0f, 16, isMono ? 1 : 2, true, false); + line = AudioSystem.getSourceDataLine(format); + line.open(format, 4410 * 2); + line.start(); } catch (Exception e) { - throw new GdxRuntimeException( "Couldn't createa AudioDevice", e ); - } + throw new GdxRuntimeException("Couldn't createa AudioDevice", e); + } } - - @Override - public void dispose() - { + + @Override public void dispose () { line.drain(); line.close(); } - @Override - public boolean isMono() - { + @Override public boolean isMono () { return isMono; } - @Override - public void writeSamples(short[] samples, int offset, int numSamples ) - { - if( bytes.length < samples.length * 2 ) - bytes = new byte[samples.length*2]; - - for( int i = offset, j = 0; i < offset + numSamples; i++, j+=2 ) - { - short value = samples[i]; - bytes[j+1] = (byte)(value & 0xff); - bytes[j] = (byte)(value >> 8 ); - } - - int writtenBytes = line.write( bytes, 0, numSamples * 2 ); - while( writtenBytes != numSamples * 2 ) - writtenBytes += line.write( bytes, writtenBytes, numSamples * 2 - writtenBytes ); + @Override public void writeSamples (short[] samples, int offset, int numSamples) { + if (bytes.length < samples.length * 2) bytes = new byte[samples.length * 2]; + + for (int i = offset, j = 0; i < offset + numSamples; i++, j += 2) { + short value = samples[i]; + bytes[j + 1] = (byte)(value & 0xff); + bytes[j] = (byte)(value >> 8); + } + + int writtenBytes = line.write(bytes, 0, numSamples * 2); + while (writtenBytes != numSamples * 2) + writtenBytes += line.write(bytes, writtenBytes, numSamples * 2 - writtenBytes); } - @Override - public void writeSamples(float[] samples, int offset, int numSamples) - { - if( bytes.length < samples.length * 2 ) - bytes = new byte[samples.length*2]; - - for( int i = offset, j = 0; i < offset + numSamples; i++, j+=2 ) - { - float fValue = samples[i]; - if( fValue > 1 ) - fValue = 1; - if( fValue < -1 ) - fValue = -1; - short value = (short)( fValue * Short.MAX_VALUE); - bytes[j] = (byte)(value | 0xff); - bytes[j+1] = (byte)(value >> 8 ); - } - - int writtenBytes = line.write( bytes, 0, numSamples * 2 ); - while( writtenBytes != numSamples * 2 ) - writtenBytes += line.write( bytes, writtenBytes, numSamples * 2 - writtenBytes ); + @Override public void writeSamples (float[] samples, int offset, int numSamples) { + if (bytes.length < samples.length * 2) bytes = new byte[samples.length * 2]; + + for (int i = offset, j = 0; i < offset + numSamples; i++, j += 2) { + float fValue = samples[i]; + if (fValue > 1) fValue = 1; + if (fValue < -1) fValue = -1; + short value = (short)(fValue * Short.MAX_VALUE); + bytes[j] = (byte)(value | 0xff); + bytes[j + 1] = (byte)(value >> 8); + } + + int writtenBytes = line.write(bytes, 0, numSamples * 2); + while (writtenBytes != numSamples * 2) + writtenBytes += line.write(bytes, writtenBytes, numSamples * 2 - writtenBytes); } } diff --git a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglAudioRecorder.java b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglAudioRecorder.java index f8ac11704..842998974 100644 --- a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglAudioRecorder.java +++ b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglAudioRecorder.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.desktop; import javax.sound.sampled.AudioFormat; @@ -24,56 +22,45 @@ import com.badlogic.gdx.GdxRuntimeException; import com.badlogic.gdx.audio.AudioRecorder; /** - * {@link AudioRecorder} implementation for the desktop using - * the java sound API. + * {@link AudioRecorder} implementation for the desktop using the java sound API. * * @author badlogicgames@gmail.com - * + * */ -public class JoglAudioRecorder implements AudioRecorder -{ +public class JoglAudioRecorder implements AudioRecorder { /** the line we read the audio from **/ private TargetDataLine line; - + /** the buffer to temporarily store the samples **/ - private byte[] buffer = new byte[1024*4]; - - public JoglAudioRecorder( int samplingRate, boolean isMono ) - { - try - { - AudioFormat format = new AudioFormat( Encoding.PCM_SIGNED, samplingRate, 16, isMono?1:2, isMono?2:4, samplingRate, false ); - line = AudioSystem.getTargetDataLine( format ); + private byte[] buffer = new byte[1024 * 4]; + + public JoglAudioRecorder (int samplingRate, boolean isMono) { + try { + AudioFormat format = new AudioFormat(Encoding.PCM_SIGNED, samplingRate, 16, isMono ? 1 : 2, isMono ? 2 : 4, + samplingRate, false); + line = AudioSystem.getTargetDataLine(format); line.open(format, buffer.length); - line.start(); - } - catch( Exception ex ) - { - throw new GdxRuntimeException( "Couldn't create AudioRecorder", ex ); + line.start(); + } catch (Exception ex) { + throw new GdxRuntimeException("Couldn't create AudioRecorder", ex); } } - - @Override - public void read(short[] samples, int offset, int numSamples) - { - if( buffer.length < numSamples * 2 ) - buffer = new byte[numSamples*2]; - + + @Override public void read (short[] samples, int offset, int numSamples) { + if (buffer.length < numSamples * 2) buffer = new byte[numSamples * 2]; + int toRead = numSamples * 2; int read = 0; - - while( read != toRead ) - read += line.read( buffer, read, toRead - read ); - - for( int i = 0, j = 0; i < numSamples * 2; i+=2, j++ ) - { - samples[offset + j] = (short)((buffer[i] << 8) | (buffer[i+1] & 0xff)); - } + + while (read != toRead) + read += line.read(buffer, read, toRead - read); + + for (int i = 0, j = 0; i < numSamples * 2; i += 2, j++) { + samples[offset + j] = (short)((buffer[i] << 8) | (buffer[i + 1] & 0xff)); + } } - - @Override - public void dispose() - { + + @Override public void dispose () { line.close(); } } diff --git a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglFileHandle.java b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglFileHandle.java index 42e920e54..520b5d1f5 100644 --- a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglFileHandle.java +++ b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglFileHandle.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.desktop; import java.io.File; @@ -24,29 +22,26 @@ import com.badlogic.gdx.GdxRuntimeException; import com.badlogic.gdx.files.FileHandle; /** - * A {@link FileHandle} implementation for the desktop. + * A {@link FileHandle} implementation for the desktop. * * @author mzechner - * + * */ -public class JoglFileHandle implements FileHandle -{ +public class JoglFileHandle implements FileHandle { /** the file **/ private final File file; - - JoglFileHandle( File file ) - { + + JoglFileHandle (File file) { this.file = file; } - + /** * @return the underlying {@link File}. */ - public File getFile( ) - { + public File getFile () { return file; } - + public InputStream getInputStream () { try { return new FileInputStream(file); @@ -55,8 +50,7 @@ public class JoglFileHandle implements FileHandle } } - public String toString( ) - { + public String toString () { return file.toString(); } } diff --git a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglFiles.java b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglFiles.java index c246a8a48..49793956c 100644 --- a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglFiles.java +++ b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglFiles.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.desktop; import java.io.File; @@ -27,124 +25,101 @@ import com.badlogic.gdx.GdxRuntimeException; import com.badlogic.gdx.files.FileHandle; /** - * Implementation for a desktop application of {@link Files}. Internal - * resources are relative to the application root directory, external files - * are relative to the user's home directory. - * + * Implementation for a desktop application of {@link Files}. Internal resources are relative to the application root directory, + * external files are relative to the user's home directory. + * * @author mzechner - * + * */ -final class JoglFiles implements Files -{ - private final String externalPath = System.getProperty("user.home") + "/"; - +final class JoglFiles implements Files { + private final String externalPath = System.getProperty("user.home") + "/"; /** * {@inheritDoc} */ - @Override - public FileHandle getFileHandle(String filename, FileType type) - { + @Override public FileHandle getFileHandle (String filename, FileType type) { File file = null; - if( type == FileType.Absolut || type == FileType.Internal ) - file = new File( filename ); + if (type == FileType.Absolut || type == FileType.Internal) + file = new File(filename); else - file = new File( this.externalPath + filename ); - - if( file.exists() == false ) - throw new GdxRuntimeException( "File '" + filename + "' doesn't exist" ); + file = new File(this.externalPath + filename); + + if (file.exists() == false) + throw new GdxRuntimeException("File '" + filename + "' doesn't exist"); else - return new JoglFileHandle( file ); + return new JoglFileHandle(file); } /** * {@inheritDoc} */ - @Override - public String[] listDirectory(String directory, FileType type) - { + @Override public String[] listDirectory (String directory, FileType type) { File file = null; - if( type == FileType.Absolut || type == FileType.Internal ) - file = new File( directory ); + if (type == FileType.Absolut || type == FileType.Internal) + file = new File(directory); else - file = new File( this.externalPath + directory ); - - if( file.exists() == false ) - throw new GdxRuntimeException( "Directory '" + directory + "' does not exist" ); - - return file.list(); + file = new File(this.externalPath + directory); + + if (file.exists() == false) throw new GdxRuntimeException("Directory '" + directory + "' does not exist"); + + return file.list(); } /** * {@inheritDoc} */ - @Override - public boolean makeDirectory(String directory, FileType type) - { + @Override public boolean makeDirectory (String directory, FileType type) { File file = null; - - if( type == FileType.Internal ) - return false; - - if( type == FileType.Absolut ) - file = new File( directory ); + + if (type == FileType.Internal) return false; + + if (type == FileType.Absolut) + file = new File(directory); else - file = new File( this.externalPath + directory ); + file = new File(this.externalPath + directory); return file.mkdirs(); } /** * {@inheritDoc} */ - @Override - public InputStream readFile(String fileName, FileType type) - { + @Override public InputStream readFile (String fileName, FileType type) { File file = null; InputStream in = null; - if( type == FileType.Absolut || type == FileType.Internal ) - file = new File( fileName ); + if (type == FileType.Absolut || type == FileType.Internal) + file = new File(fileName); else - file = new File( this.externalPath + fileName ); - - try - { - in = new FileInputStream( file ); - } - catch (FileNotFoundException e) - { - throw new GdxRuntimeException( "File '" + file + "' does not exist" ); - } - - return in; + file = new File(this.externalPath + fileName); + + try { + in = new FileInputStream(file); + } catch (FileNotFoundException e) { + throw new GdxRuntimeException("File '" + file + "' does not exist"); + } + + return in; } /** * {@inheritDoc} */ - @Override - public OutputStream writeFile(String filename, FileType type) - { + @Override public OutputStream writeFile (String filename, FileType type) { File file = null; FileOutputStream out = null; - - if( type == FileType.Internal ) - return null; - - if( type == FileType.Absolut ) - file = new File( filename ); + + if (type == FileType.Internal) return null; + + if (type == FileType.Absolut) + file = new File(filename); else - file = new File( this.externalPath + filename ); - - - try - { - out = new FileOutputStream( file ); - } - catch (FileNotFoundException e) - { - throw new GdxRuntimeException( "File '" + file + "' does not exist" ); - } - + file = new File(this.externalPath + filename); + + try { + out = new FileOutputStream(file); + } catch (FileNotFoundException e) { + throw new GdxRuntimeException("File '" + file + "' does not exist"); + } + return out; } } diff --git a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglFont.java b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglFont.java index 73a134909..a7eaf12ab 100644 --- a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglFont.java +++ b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglFont.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.desktop; import java.awt.FontMetrics; @@ -28,122 +26,102 @@ import com.badlogic.gdx.graphics.Font; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.math.Rectangle; - /** * An implementation of {@link Font} based on the java graphics framework. * * @author badlogicgames@gmail.com - * + * */ -final class JoglFont extends Font -{ - private final BufferedImage tmpBitmap = new BufferedImage( 1, 1, BufferedImage.TYPE_4BYTE_ABGR ); - private java.awt.Font font; +final class JoglFont extends Font { + private final BufferedImage tmpBitmap = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR); + private java.awt.Font font; private FontMetrics metrics; - - JoglFont( String fontName, int size, FontStyle style) - { - super( ); - font = new java.awt.Font( fontName, getJavaFontStyle(style), size ); + + JoglFont (String fontName, int size, FontStyle style) { + super(); + font = new java.awt.Font(fontName, getJavaFontStyle(style), size); Graphics g = tmpBitmap.getGraphics(); - g.setFont( font ); + g.setFont(font); metrics = g.getFontMetrics(); g.dispose(); } - - JoglFont( InputStream in, int size, FontStyle style ) - { - super( ); - - try - { - java.awt.Font baseFont = java.awt.Font.createFont( java.awt.Font.PLAIN, in); - font = baseFont.deriveFont( getJavaFontStyle(style), size ); - } - catch( Exception ex ) - { - throw new GdxRuntimeException( "Couldn't load font from InputStream", ex ); + + JoglFont (InputStream in, int size, FontStyle style) { + super(); + + try { + java.awt.Font baseFont = java.awt.Font.createFont(java.awt.Font.PLAIN, in); + font = baseFont.deriveFont(getJavaFontStyle(style), size); + } catch (Exception ex) { + throw new GdxRuntimeException("Couldn't load font from InputStream", ex); } Graphics g = tmpBitmap.getGraphics(); - g.setFont( font ); + g.setFont(font); metrics = g.getFontMetrics(); g.dispose(); } - - private int getJavaFontStyle( FontStyle style ) - { - if( style == FontStyle.Plain ) - return java.awt.Font.PLAIN; - if( style == FontStyle.Bold ) - return java.awt.Font.BOLD; - if( style == FontStyle.Italic ) - return java.awt.Font.ITALIC; - if( style == FontStyle.BoldItalic ) - return java.awt.Font.BOLD | java.awt.Font.ITALIC; - + + private int getJavaFontStyle (FontStyle style) { + if (style == FontStyle.Plain) return java.awt.Font.PLAIN; + if (style == FontStyle.Bold) return java.awt.Font.BOLD; + if (style == FontStyle.Italic) return java.awt.Font.ITALIC; + if (style == FontStyle.BoldItalic) return java.awt.Font.BOLD | java.awt.Font.ITALIC; + return java.awt.Font.PLAIN; } - + /** * {@inheritDoc} */ - @Override - public int getGlyphAdvance(char character) - { + @Override public int getGlyphAdvance (char character) { return metrics.charWidth(character); } /** * {@inheritDoc} */ - @Override - public Pixmap getGlyphBitmap(char character) { + @Override public Pixmap getGlyphBitmap (char character) { Graphics2D g = (Graphics2D)tmpBitmap.getGraphics(); - g.setFont( font ); - Rectangle2D bounds = metrics.getStringBounds( "" + character, g); - g.dispose( ); - - BufferedImage bitmap = new BufferedImage( (int)Math.ceil(bounds.getWidth()), getLineHeight(), BufferedImage.TYPE_4BYTE_ABGR ); + g.setFont(font); + Rectangle2D bounds = metrics.getStringBounds("" + character, g); + g.dispose(); + + BufferedImage bitmap = new BufferedImage((int)Math.ceil(bounds.getWidth()), getLineHeight(), BufferedImage.TYPE_4BYTE_ABGR); g = (Graphics2D)bitmap.getGraphics(); - - g.setFont(font); - g.addRenderingHints( new RenderingHints( RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON )); - g.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING, - RenderingHints.VALUE_TEXT_ANTIALIAS_ON ); - - g.setColor( new java.awt.Color( 0x0000000, true ) ); - g.fillRect( 0, 0, bitmap.getWidth(), bitmap.getHeight() ); - g.setColor( new java.awt.Color( 0xffffffff, true ) ); - g.drawString( "" + character, 0, metrics.getAscent()); + + g.setFont(font); + g.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)); + g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + + g.setColor(new java.awt.Color(0x0000000, true)); + g.fillRect(0, 0, bitmap.getWidth(), bitmap.getHeight()); + g.setColor(new java.awt.Color(0xffffffff, true)); + g.drawString("" + character, 0, metrics.getAscent()); g.dispose(); - - return new JoglPixmap( bitmap ); + + return new JoglPixmap(bitmap); } /** * {@inheritDoc} */ - @Override - public int getLineGap() { + @Override public int getLineGap () { return metrics.getLeading(); } /** * {@inheritDoc} */ - @Override - public int getLineHeight() { + @Override public int getLineHeight () { return metrics.getAscent() + metrics.getDescent(); } /** * {@inheritDoc} */ - @Override - public int getStringWidth(String text) { + @Override public int getStringWidth (String text) { Graphics g = tmpBitmap.getGraphics(); - g.setFont( font ); + g.setFont(font); int width = (int)Math.ceil(metrics.getStringBounds(text, g).getWidth()); g.dispose(); return width; @@ -152,14 +130,13 @@ final class JoglFont extends Font /** * {@inheritDoc} */ - @Override - public void getGlyphBounds(char character, Rectangle rect) { + @Override public void getGlyphBounds (char character, Rectangle rect) { Graphics g = tmpBitmap.getGraphics(); - g.setFont( font ); - Rectangle2D bounds = metrics.getStringBounds( "" + character, g); + g.setFont(font); + Rectangle2D bounds = metrics.getStringBounds("" + character, g); g.dispose(); - rect.setWidth( (int)Math.ceil(bounds.getWidth()) ); - rect.setHeight( getLineHeight() ); + rect.setWidth((int)Math.ceil(bounds.getWidth())); + rect.setHeight(getLineHeight()); } } diff --git a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglGL10.java b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglGL10.java index 297d13b52..16b1780cb 100644 --- a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglGL10.java +++ b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglGL10.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.desktop; import java.nio.Buffer; @@ -24,924 +22,633 @@ import java.nio.IntBuffer; import com.badlogic.gdx.graphics.GL10; /** - * An implementation of the {@link GL10} interface based on Jogl. Fixed point vertex - * arrays are emulated. + * An implementation of the {@link GL10} interface based on Jogl. Fixed point vertex arrays are emulated. * * @author mzechner - * + * */ -class JoglGL10 implements GL10 -{ +class JoglGL10 implements GL10 { protected final javax.media.opengl.GL gl; - protected final float FIXED_TO_FLOAT = 1 / 65536.0f; + protected final float FIXED_TO_FLOAT = 1 / 65536.0f; private final FloatBuffer colorBuffer; private final FloatBuffer normalBuffer; private final FloatBuffer vertexBuffer; private final FloatBuffer texCoordBuffer[] = new FloatBuffer[16]; private int activeTexture = 0; - + private float[] tmp = new float[1000]; - - - public JoglGL10( javax.media.opengl.GL gl ) - { + + public JoglGL10 (javax.media.opengl.GL gl) { this.gl = gl; - ByteBuffer buffer = ByteBuffer.allocateDirect( 20000 * 4 * 4 ); + ByteBuffer buffer = ByteBuffer.allocateDirect(20000 * 4 * 4); buffer.order(ByteOrder.nativeOrder()); colorBuffer = buffer.asFloatBuffer(); - - buffer = ByteBuffer.allocateDirect( 20000 * 4 * 3 ); + + buffer = ByteBuffer.allocateDirect(20000 * 4 * 3); buffer.order(ByteOrder.nativeOrder()); normalBuffer = buffer.asFloatBuffer(); - - buffer = ByteBuffer.allocateDirect( 20000 * 4 * 4 ); + + buffer = ByteBuffer.allocateDirect(20000 * 4 * 4); buffer.order(ByteOrder.nativeOrder()); vertexBuffer = buffer.asFloatBuffer(); - - for( int i = 0; i < texCoordBuffer.length; i++ ) - { - buffer = ByteBuffer.allocateDirect( 20000 * 4 * 4 ); - buffer.order(ByteOrder.nativeOrder()); + + for (int i = 0; i < texCoordBuffer.length; i++) { + buffer = ByteBuffer.allocateDirect(20000 * 4 * 4); + buffer.order(ByteOrder.nativeOrder()); texCoordBuffer[i] = buffer.asFloatBuffer(); } - } - - protected final void convertFixedToFloatbuffer( Buffer source, FloatBuffer target, int stride ) - { - if( source instanceof IntBuffer || source instanceof ByteBuffer ) - { - IntBuffer buffer = source instanceof ByteBuffer?((ByteBuffer)source).asIntBuffer():(IntBuffer)source; - if( stride % 4 != 0 ) - throw new IllegalArgumentException( "Can't cope with strides % 4 != 0 for IntBuffers" ); + } + + protected final void convertFixedToFloatbuffer (Buffer source, FloatBuffer target, int stride) { + if (source instanceof IntBuffer || source instanceof ByteBuffer) { + IntBuffer buffer = source instanceof ByteBuffer ? ((ByteBuffer)source).asIntBuffer() : (IntBuffer)source; + if (stride % 4 != 0) throw new IllegalArgumentException("Can't cope with strides % 4 != 0 for IntBuffers"); target.clear(); - for( int i = buffer.position(); i < buffer.limit(); i++ ) - { + for (int i = buffer.position(); i < buffer.limit(); i++) { float value = FIXED_TO_FLOAT * buffer.get(i); - target.put( value ); + target.put(value); } target.flip(); - } - else - { - throw new IllegalArgumentException( "Can't cope with buffer of type " + source.getClass().getName() + ", only ByteBuffers and IntBuffers supported" ); + } else { + throw new IllegalArgumentException("Can't cope with buffer of type " + source.getClass().getName() + + ", only ByteBuffers and IntBuffers supported"); } } - - - @Override - public final void glActiveTexture(int texture) - { - gl.glActiveTexture( texture ); + + @Override public final void glActiveTexture (int texture) { + gl.glActiveTexture(texture); } - @Override - public final void glAlphaFunc(int func, float ref) - { - gl.glAlphaFunc( func, ref ); + @Override public final void glAlphaFunc (int func, float ref) { + gl.glAlphaFunc(func, ref); } - @Override - public final void glAlphaFuncx(int func, int ref) { - gl.glAlphaFunc( func, FIXED_TO_FLOAT * ref ); + @Override public final void glAlphaFuncx (int func, int ref) { + gl.glAlphaFunc(func, FIXED_TO_FLOAT * ref); } - @Override - public final void glBindTexture(int target, int texture) - { - gl.glBindTexture( target, texture ); + @Override public final void glBindTexture (int target, int texture) { + gl.glBindTexture(target, texture); } - @Override - public final void glBlendFunc(int sfactor, int dfactor) - { - gl.glBlendFunc( sfactor, dfactor ); + @Override public final void glBlendFunc (int sfactor, int dfactor) { + gl.glBlendFunc(sfactor, dfactor); } - @Override - public final void glClear(int mask) - { - gl.glClear( mask ); + @Override public final void glClear (int mask) { + gl.glClear(mask); } - @Override - public final void glClearColor(float red, float green, float blue, float alpha) - { - gl.glClearColor( red, green, blue, alpha ); + @Override public final void glClearColor (float red, float green, float blue, float alpha) { + gl.glClearColor(red, green, blue, alpha); } - @Override - public final void glClearColorx(int red, int green, int blue, int alpha) - { - gl.glClearColor( FIXED_TO_FLOAT * red, FIXED_TO_FLOAT * green, FIXED_TO_FLOAT * blue, FIXED_TO_FLOAT * alpha ); + @Override public final void glClearColorx (int red, int green, int blue, int alpha) { + gl.glClearColor(FIXED_TO_FLOAT * red, FIXED_TO_FLOAT * green, FIXED_TO_FLOAT * blue, FIXED_TO_FLOAT * alpha); } - @Override - public final void glClearDepthf(float depth) - { - gl.glClearDepth( depth ); + @Override public final void glClearDepthf (float depth) { + gl.glClearDepth(depth); } - @Override - public final void glClearDepthx(int depth) - { - gl.glClearDepth( FIXED_TO_FLOAT * depth ); + @Override public final void glClearDepthx (int depth) { + gl.glClearDepth(FIXED_TO_FLOAT * depth); } - @Override - public final void glClearStencil(int s) - { - gl.glClearStencil( s ); + @Override public final void glClearStencil (int s) { + gl.glClearStencil(s); } - @Override - public final void glClientActiveTexture(int texture) - { + @Override public final void glClientActiveTexture (int texture) { activeTexture = texture - GL10.GL_TEXTURE0; - try - { - gl.glClientActiveTexture( texture ); - } - catch( Throwable ex ) - { + try { + gl.glClientActiveTexture(texture); + } catch (Throwable ex) { // FIXME this is for my lousy netbook... } } - @Override - public final void glColor4f(float red, float green, float blue, float alpha) - { - gl.glColor4f( red, green, blue, alpha ); + @Override public final void glColor4f (float red, float green, float blue, float alpha) { + gl.glColor4f(red, green, blue, alpha); } - @Override - public final void glColor4x(int red, int green, int blue, int alpha) - { - gl.glColor4f( FIXED_TO_FLOAT * red, FIXED_TO_FLOAT * green, FIXED_TO_FLOAT * blue, FIXED_TO_FLOAT * alpha ); + @Override public final void glColor4x (int red, int green, int blue, int alpha) { + gl.glColor4f(FIXED_TO_FLOAT * red, FIXED_TO_FLOAT * green, FIXED_TO_FLOAT * blue, FIXED_TO_FLOAT * alpha); } - @Override - public final void glColorMask(boolean red, boolean green, boolean blue, boolean alpha) - { - gl.glColorMask( red, green, blue, alpha ); + @Override public final void glColorMask (boolean red, boolean green, boolean blue, boolean alpha) { + gl.glColorMask(red, green, blue, alpha); } - @Override - public final void glColorPointer(int size, int type, int stride, Buffer pointer) - { - if( type == GL10.GL_FIXED ) - { - convertFixedToFloatbuffer(pointer,colorBuffer, stride); - gl.glColorPointer( size, GL10.GL_FLOAT, stride, colorBuffer ); - } - else - { - gl.glColorPointer( size, type, stride, pointer ); + @Override public final void glColorPointer (int size, int type, int stride, Buffer pointer) { + if (type == GL10.GL_FIXED) { + convertFixedToFloatbuffer(pointer, colorBuffer, stride); + gl.glColorPointer(size, GL10.GL_FLOAT, stride, colorBuffer); + } else { + gl.glColorPointer(size, type, stride, pointer); } } - @Override - public final void glCompressedTexImage2D(int target, int level, - int internalformat, int width, int height, int border, - int imageSize, Buffer data) - { - gl.glCompressedTexImage2D( target, level, internalformat, width, height, border, imageSize, data ); + @Override public final void glCompressedTexImage2D (int target, int level, int internalformat, int width, int height, + int border, int imageSize, Buffer data) { + gl.glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); } - @Override - public final void glCompressedTexSubImage2D(int target, int level, int xoffset, - int yoffset, int width, int height, int format, int imageSize, - Buffer data) - { - gl.glCompressedTexSubImage2D( target, level, xoffset, yoffset, width, height, format, imageSize, data ); + @Override public final void glCompressedTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, + int format, int imageSize, Buffer data) { + gl.glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); } - @Override - public final void glCopyTexImage2D(int target, int level, int internalformat, - int x, int y, int width, int height, int border) - { - gl.glCopyTexImage2D( target, level, internalformat, x, y, width, height, border ); + @Override public final void glCopyTexImage2D (int target, int level, int internalformat, int x, int y, int width, int height, + int border) { + gl.glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); } - @Override - public final void glCopyTexSubImage2D(int target, int level, int xoffset, - int yoffset, int x, int y, int width, int height) - { - gl.glCopyTexSubImage2D( target, level, xoffset, yoffset, x, y, width, height ); + @Override public final void glCopyTexSubImage2D (int target, int level, int xoffset, int yoffset, int x, int y, int width, + int height) { + gl.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); } - @Override - public final void glCullFace(int mode) - { - gl.glCullFace( mode ); + @Override public final void glCullFace (int mode) { + gl.glCullFace(mode); } - @Override - public final void glDeleteTextures(int n, IntBuffer textures) - { - gl.glDeleteTextures( n, textures ); + @Override public final void glDeleteTextures (int n, IntBuffer textures) { + gl.glDeleteTextures(n, textures); } - @Override - public final void glDepthFunc(int func) - { - gl.glDepthFunc( func ); + @Override public final void glDepthFunc (int func) { + gl.glDepthFunc(func); } - @Override - public final void glDepthMask(boolean flag) - { - gl.glDepthMask( flag ); + @Override public final void glDepthMask (boolean flag) { + gl.glDepthMask(flag); } - @Override - public final void glDepthRangef(float zNear, float zFar) - { - gl.glDepthRange( zNear, zFar ); + @Override public final void glDepthRangef (float zNear, float zFar) { + gl.glDepthRange(zNear, zFar); } - @Override - public final void glDepthRangex(int zNear, int zFar) - { - gl.glDepthRange( FIXED_TO_FLOAT * zNear, FIXED_TO_FLOAT * zFar ); + @Override public final void glDepthRangex (int zNear, int zFar) { + gl.glDepthRange(FIXED_TO_FLOAT * zNear, FIXED_TO_FLOAT * zFar); } - @Override - public final void glDisable(int cap) - { - gl.glDisable( cap ); + @Override public final void glDisable (int cap) { + gl.glDisable(cap); } - @Override - public final void glDisableClientState(int array) - { - gl.glDisableClientState( array ); + @Override public final void glDisableClientState (int array) { + gl.glDisableClientState(array); } - @Override - public final void glDrawArrays(int mode, int first, int count) - { - gl.glDrawArrays( mode, first, count ); + @Override public final void glDrawArrays (int mode, int first, int count) { + gl.glDrawArrays(mode, first, count); } - @Override - public final void glDrawElements(int mode, int count, int type, Buffer indices) - { - // nothing to do here per documentation - gl.glDrawElements( mode, count, type, indices ); + @Override public final void glDrawElements (int mode, int count, int type, Buffer indices) { + // nothing to do here per documentation + gl.glDrawElements(mode, count, type, indices); } - @Override - public final void glEnable(int cap) - { - gl.glEnable( cap ); + @Override public final void glEnable (int cap) { + gl.glEnable(cap); } - @Override - public final void glEnableClientState(int array) - { - gl.glEnableClientState( array ); + @Override public final void glEnableClientState (int array) { + gl.glEnableClientState(array); } - @Override - public final void glFinish() - { + @Override public final void glFinish () { gl.glFinish(); } - @Override - public final void glFlush() - { + @Override public final void glFlush () { gl.glFlush(); } - @Override - public final void glFogf(int pname, float param) - { - gl.glFogf( pname, param ); + @Override public final void glFogf (int pname, float param) { + gl.glFogf(pname, param); } - @Override - public final void glFogfv(int pname, FloatBuffer params) - { - gl.glFogfv( pname, params ); + @Override public final void glFogfv (int pname, FloatBuffer params) { + gl.glFogfv(pname, params); } - @Override - public final void glFogx(int pname, int param) - { - gl.glFogf( pname, FIXED_TO_FLOAT * param ); + @Override public final void glFogx (int pname, int param) { + gl.glFogf(pname, FIXED_TO_FLOAT * param); } - - @Override - public final void glFogxv(int pname, IntBuffer params) - { - if( tmp.length < params.capacity() ) - tmp = new float[params.capacity()]; + + @Override public final void glFogxv (int pname, IntBuffer params) { + if (tmp.length < params.capacity()) tmp = new float[params.capacity()]; int i = 0; - while( params.hasRemaining() ) + while (params.hasRemaining()) tmp[i++] = FIXED_TO_FLOAT * params.get(); - gl.glFogfv(pname, tmp, 0 ); + gl.glFogfv(pname, tmp, 0); } - @Override - public final void glFrontFace(int mode) - { - gl.glFrontFace( mode ); + @Override public final void glFrontFace (int mode) { + gl.glFrontFace(mode); } - @Override - public final void glFrustumf(float left, float right, float bottom, float top, - float zNear, float zFar) - { - gl.glFrustum( left, right, bottom, top, zNear, zFar ); + @Override public final void glFrustumf (float left, float right, float bottom, float top, float zNear, float zFar) { + gl.glFrustum(left, right, bottom, top, zNear, zFar); } - @Override - public final void glFrustumx(int left, int right, int bottom, int top, int zNear, - int zFar) - { - gl.glFrustum( FIXED_TO_FLOAT * left, FIXED_TO_FLOAT * right, FIXED_TO_FLOAT * bottom, FIXED_TO_FLOAT * top, FIXED_TO_FLOAT * zNear, FIXED_TO_FLOAT * zFar ); + @Override public final void glFrustumx (int left, int right, int bottom, int top, int zNear, int zFar) { + gl.glFrustum(FIXED_TO_FLOAT * left, FIXED_TO_FLOAT * right, FIXED_TO_FLOAT * bottom, FIXED_TO_FLOAT * top, FIXED_TO_FLOAT + * zNear, FIXED_TO_FLOAT * zFar); } - @Override - public final void glGenTextures(int n, IntBuffer textures) - { - gl.glGenTextures( n, textures ); + @Override public final void glGenTextures (int n, IntBuffer textures) { + gl.glGenTextures(n, textures); } - @Override - public final int glGetError() - { + @Override public final int glGetError () { return gl.glGetError(); } - @Override - public final void glGetIntegerv(int pname, IntBuffer params) - { - gl.glGetIntegerv( pname, params ); + @Override public final void glGetIntegerv (int pname, IntBuffer params) { + gl.glGetIntegerv(pname, params); } - @Override - public final String glGetString(int name) - { - return gl.glGetString( name ); + @Override public final String glGetString (int name) { + return gl.glGetString(name); } - @Override - public final void glHint(int target, int mode) - { - gl.glHint( target, mode ); + @Override public final void glHint (int target, int mode) { + gl.glHint(target, mode); } - @Override - public final void glLightModelf(int pname, float param) - { - gl.glLightModelf( pname, param ); + @Override public final void glLightModelf (int pname, float param) { + gl.glLightModelf(pname, param); } - @Override - public final void glLightModelfv(int pname, FloatBuffer params) - { - gl.glLightModelfv( pname, params ); + @Override public final void glLightModelfv (int pname, FloatBuffer params) { + gl.glLightModelfv(pname, params); } - @Override - public final void glLightModelx(int pname, int param) - { - gl.glLightModelf( pname, FIXED_TO_FLOAT * param ); + @Override public final void glLightModelx (int pname, int param) { + gl.glLightModelf(pname, FIXED_TO_FLOAT * param); } - @Override - public final void glLightModelxv(int pname, IntBuffer params) - { + @Override public final void glLightModelxv (int pname, IntBuffer params) { int i = 0; - while( params.hasRemaining() ) + while (params.hasRemaining()) tmp[i++] = FIXED_TO_FLOAT * params.get(); - gl.glLightModelfv( pname, tmp, 0 ); + gl.glLightModelfv(pname, tmp, 0); } - @Override - public final void glLightf(int light, int pname, float param) - { - gl.glLightf( light, pname, param ); + @Override public final void glLightf (int light, int pname, float param) { + gl.glLightf(light, pname, param); } - @Override - public final void glLightfv(int light, int pname, FloatBuffer params) - { - gl.glLightfv( light, pname, params ); + @Override public final void glLightfv (int light, int pname, FloatBuffer params) { + gl.glLightfv(light, pname, params); } - @Override - public final void glLightx(int light, int pname, int param) - { - gl.glLightf( light, pname, FIXED_TO_FLOAT * param ); + @Override public final void glLightx (int light, int pname, int param) { + gl.glLightf(light, pname, FIXED_TO_FLOAT * param); } - @Override - public final void glLightxv(int light, int pname, IntBuffer params) - { - if( tmp.length < params.capacity() ) - tmp = new float[params.capacity()]; + @Override public final void glLightxv (int light, int pname, IntBuffer params) { + if (tmp.length < params.capacity()) tmp = new float[params.capacity()]; int i = 0; - while( params.hasRemaining() ) + while (params.hasRemaining()) tmp[i++] = FIXED_TO_FLOAT * params.get(); - gl.glLightfv( light, pname, tmp, 0 ); + gl.glLightfv(light, pname, tmp, 0); } - @Override - public final void glLineWidth(float width) - { - gl.glLineWidth( width ); + @Override public final void glLineWidth (float width) { + gl.glLineWidth(width); } - @Override - public final void glLineWidthx(int width) - { - gl.glLineWidth( FIXED_TO_FLOAT * width ); + @Override public final void glLineWidthx (int width) { + gl.glLineWidth(FIXED_TO_FLOAT * width); } - @Override - public final void glLoadIdentity() - { + @Override public final void glLoadIdentity () { gl.glLoadIdentity(); } - @Override - public final void glLoadMatrixf(FloatBuffer m) - { - gl.glLoadMatrixf( m ); + @Override public final void glLoadMatrixf (FloatBuffer m) { + gl.glLoadMatrixf(m); } - @Override - public final void glLoadMatrixx(IntBuffer m) - { - if( tmp.length < m.capacity() ) - tmp = new float[m.capacity()]; + @Override public final void glLoadMatrixx (IntBuffer m) { + if (tmp.length < m.capacity()) tmp = new float[m.capacity()]; int i = 0; - while( m.hasRemaining() ) + while (m.hasRemaining()) tmp[i++] = FIXED_TO_FLOAT * m.get(); - - gl.glLoadMatrixf( tmp, 0 ); + + gl.glLoadMatrixf(tmp, 0); } - @Override - public final void glLogicOp(int opcode) - { - gl.glLogicOp( opcode ); + @Override public final void glLogicOp (int opcode) { + gl.glLogicOp(opcode); } - @Override - public final void glMaterialf(int face, int pname, float param) - { - gl.glMaterialf( face, pname, param ); + @Override public final void glMaterialf (int face, int pname, float param) { + gl.glMaterialf(face, pname, param); } - @Override - public final void glMaterialfv(int face, int pname, FloatBuffer params) - { - gl.glMaterialfv( face, pname, params ); + @Override public final void glMaterialfv (int face, int pname, FloatBuffer params) { + gl.glMaterialfv(face, pname, params); } - @Override - public final void glMaterialx(int face, int pname, int param) - { - gl.glMaterialf( face, pname, FIXED_TO_FLOAT * param ); + @Override public final void glMaterialx (int face, int pname, int param) { + gl.glMaterialf(face, pname, FIXED_TO_FLOAT * param); } - @Override - public final void glMaterialxv(int face, int pname, IntBuffer params) - { - if( tmp.length < params.capacity() ) - tmp = new float[params.capacity()]; + @Override public final void glMaterialxv (int face, int pname, IntBuffer params) { + if (tmp.length < params.capacity()) tmp = new float[params.capacity()]; int i = 0; - while( params.hasRemaining() ) + while (params.hasRemaining()) tmp[i++] = FIXED_TO_FLOAT * params.get(); - gl.glMaterialfv( face, pname, tmp, 0 ); + gl.glMaterialfv(face, pname, tmp, 0); } - @Override - public final void glMatrixMode(int mode) - { - gl.glMatrixMode( mode ); + @Override public final void glMatrixMode (int mode) { + gl.glMatrixMode(mode); } - @Override - public final void glMultMatrixf(FloatBuffer m) - { - gl.glMultMatrixf( m ); + @Override public final void glMultMatrixf (FloatBuffer m) { + gl.glMultMatrixf(m); } - @Override - public final void glMultMatrixx(IntBuffer m) - { - if( tmp.length < m.capacity() ) - tmp = new float[m.capacity()]; + @Override public final void glMultMatrixx (IntBuffer m) { + if (tmp.length < m.capacity()) tmp = new float[m.capacity()]; int i = 0; - while( m.hasRemaining() ) + while (m.hasRemaining()) tmp[i++] = FIXED_TO_FLOAT * m.get(); - gl.glMultMatrixf( tmp, 0 ); + gl.glMultMatrixf(tmp, 0); } - @Override - public final void glMultiTexCoord4f(int target, float s, float t, float r, float q) - { - gl.glMultiTexCoord4f( target, s, t, r, q ); + @Override public final void glMultiTexCoord4f (int target, float s, float t, float r, float q) { + gl.glMultiTexCoord4f(target, s, t, r, q); } - @Override - public final void glMultiTexCoord4x(int target, int s, int t, int r, int q) - { - gl.glMultiTexCoord4f( target, FIXED_TO_FLOAT * s, FIXED_TO_FLOAT * t, FIXED_TO_FLOAT * r, FIXED_TO_FLOAT * q ); + @Override public final void glMultiTexCoord4x (int target, int s, int t, int r, int q) { + gl.glMultiTexCoord4f(target, FIXED_TO_FLOAT * s, FIXED_TO_FLOAT * t, FIXED_TO_FLOAT * r, FIXED_TO_FLOAT * q); } - @Override - public final void glNormal3f(float nx, float ny, float nz) - { - gl.glNormal3f( nx, ny, nz ); + @Override public final void glNormal3f (float nx, float ny, float nz) { + gl.glNormal3f(nx, ny, nz); } - @Override - public final void glNormal3x(int nx, int ny, int nz) - { - gl.glNormal3f( FIXED_TO_FLOAT * nx, FIXED_TO_FLOAT * ny, FIXED_TO_FLOAT * nz ); + @Override public final void glNormal3x (int nx, int ny, int nz) { + gl.glNormal3f(FIXED_TO_FLOAT * nx, FIXED_TO_FLOAT * ny, FIXED_TO_FLOAT * nz); } - @Override - public final void glNormalPointer(int type, int stride, Buffer pointer) - { - if( type == GL10.GL_FIXED ) - { - convertFixedToFloatbuffer(pointer,normalBuffer, stride); - gl.glNormalPointer( GL10.GL_FLOAT, stride, normalBuffer ); - } - else - { - gl.glNormalPointer( type, stride, pointer ); + @Override public final void glNormalPointer (int type, int stride, Buffer pointer) { + if (type == GL10.GL_FIXED) { + convertFixedToFloatbuffer(pointer, normalBuffer, stride); + gl.glNormalPointer(GL10.GL_FLOAT, stride, normalBuffer); + } else { + gl.glNormalPointer(type, stride, pointer); } } - @Override - public final void glOrthof(float left, float right, float bottom, float top, - float zNear, float zFar) - { - gl.glOrtho( left, right, bottom, top, zNear, zFar ); + @Override public final void glOrthof (float left, float right, float bottom, float top, float zNear, float zFar) { + gl.glOrtho(left, right, bottom, top, zNear, zFar); } - @Override - public final void glOrthox(int left, int right, int bottom, int top, int zNear, - int zFar) - { - gl.glOrtho( FIXED_TO_FLOAT * left, FIXED_TO_FLOAT * right, FIXED_TO_FLOAT * bottom, FIXED_TO_FLOAT * top, FIXED_TO_FLOAT * zNear, FIXED_TO_FLOAT * zFar ); + @Override public final void glOrthox (int left, int right, int bottom, int top, int zNear, int zFar) { + gl.glOrtho(FIXED_TO_FLOAT * left, FIXED_TO_FLOAT * right, FIXED_TO_FLOAT * bottom, FIXED_TO_FLOAT * top, FIXED_TO_FLOAT + * zNear, FIXED_TO_FLOAT * zFar); } - @Override - public final void glPixelStorei(int pname, int param) - { - gl.glPixelStorei( pname, param ); + @Override public final void glPixelStorei (int pname, int param) { + gl.glPixelStorei(pname, param); } - @Override - public final void glPointSize(float size) - { - gl.glPointSize( size ); + @Override public final void glPointSize (float size) { + gl.glPointSize(size); } - @Override - public final void glPointSizex(int size) - { - gl.glPointSize( FIXED_TO_FLOAT * size ); + @Override public final void glPointSizex (int size) { + gl.glPointSize(FIXED_TO_FLOAT * size); } - @Override - public final void glPolygonOffset(float factor, float units) - { - gl.glPolygonOffset( factor, units ); + @Override public final void glPolygonOffset (float factor, float units) { + gl.glPolygonOffset(factor, units); } - @Override - public final void glPolygonOffsetx(int factor, int units) - { - gl.glPolygonOffset( FIXED_TO_FLOAT * factor, FIXED_TO_FLOAT * units ); + @Override public final void glPolygonOffsetx (int factor, int units) { + gl.glPolygonOffset(FIXED_TO_FLOAT * factor, FIXED_TO_FLOAT * units); } - @Override - public final void glPopMatrix() - { + @Override public final void glPopMatrix () { gl.glPopMatrix(); } - @Override - public final void glPushMatrix() - { + @Override public final void glPushMatrix () { gl.glPushMatrix(); } - @Override - public final void glReadPixels(int x, int y, int width, int height, int format, - int type, Buffer pixels) - { - gl.glReadPixels( x, y, width, height, format, type, pixels ); + @Override public final void glReadPixels (int x, int y, int width, int height, int format, int type, Buffer pixels) { + gl.glReadPixels(x, y, width, height, format, type, pixels); } - @Override - public final void glRotatef(float angle, float x, float y, float z) - { - gl.glRotatef( angle, x, y, z ); + @Override public final void glRotatef (float angle, float x, float y, float z) { + gl.glRotatef(angle, x, y, z); } - @Override - public final void glRotatex(int angle, int x, int y, int z) - { - gl.glRotatef( FIXED_TO_FLOAT * angle, FIXED_TO_FLOAT * x, FIXED_TO_FLOAT * y, FIXED_TO_FLOAT * z ); + @Override public final void glRotatex (int angle, int x, int y, int z) { + gl.glRotatef(FIXED_TO_FLOAT * angle, FIXED_TO_FLOAT * x, FIXED_TO_FLOAT * y, FIXED_TO_FLOAT * z); } - @Override - public final void glSampleCoverage(float value, boolean invert) - { - gl.glSampleCoverage( value, invert ); + @Override public final void glSampleCoverage (float value, boolean invert) { + gl.glSampleCoverage(value, invert); } - @Override - public final void glSampleCoveragex(int value, boolean invert) - { - gl.glSampleCoverage( FIXED_TO_FLOAT * value, invert ); + @Override public final void glSampleCoveragex (int value, boolean invert) { + gl.glSampleCoverage(FIXED_TO_FLOAT * value, invert); } - @Override - public final void glScalef(float x, float y, float z) - { - gl.glScalef( x, y, z ); + @Override public final void glScalef (float x, float y, float z) { + gl.glScalef(x, y, z); } - @Override - public final void glScalex(int x, int y, int z) - { - gl.glScalef( FIXED_TO_FLOAT * x, FIXED_TO_FLOAT * y, FIXED_TO_FLOAT * z ); + @Override public final void glScalex (int x, int y, int z) { + gl.glScalef(FIXED_TO_FLOAT * x, FIXED_TO_FLOAT * y, FIXED_TO_FLOAT * z); } - @Override - public final void glScissor(int x, int y, int width, int height) - { - gl.glScissor( x, y, width, height ); + @Override public final void glScissor (int x, int y, int width, int height) { + gl.glScissor(x, y, width, height); } - @Override - public final void glShadeModel(int mode) - { + @Override public final void glShadeModel (int mode) { gl.glShadeModel(mode); } - @Override - public final void glStencilFunc(int func, int ref, int mask) - { - gl.glStencilFunc( func, ref, mask ); + @Override public final void glStencilFunc (int func, int ref, int mask) { + gl.glStencilFunc(func, ref, mask); } - @Override - public final void glStencilMask(int mask) - { - gl.glStencilMask( mask ); + @Override public final void glStencilMask (int mask) { + gl.glStencilMask(mask); } - @Override - public final void glStencilOp(int fail, int zfail, int zpass) - { - gl.glStencilOp( fail, zfail, zpass ); + @Override public final void glStencilOp (int fail, int zfail, int zpass) { + gl.glStencilOp(fail, zfail, zpass); } - @Override - public final void glTexCoordPointer(int size, int type, int stride, Buffer pointer) - { - if( type == GL10.GL_FIXED ) - { - convertFixedToFloatbuffer(pointer,texCoordBuffer[activeTexture], stride); - gl.glTexCoordPointer( size, GL10.GL_FLOAT, stride, texCoordBuffer[activeTexture] ); - } - else - gl.glTexCoordPointer( size, type, stride, pointer ); + @Override public final void glTexCoordPointer (int size, int type, int stride, Buffer pointer) { + if (type == GL10.GL_FIXED) { + convertFixedToFloatbuffer(pointer, texCoordBuffer[activeTexture], stride); + gl.glTexCoordPointer(size, GL10.GL_FLOAT, stride, texCoordBuffer[activeTexture]); + } else + gl.glTexCoordPointer(size, type, stride, pointer); } - @Override - public final void glTexEnvf(int target, int pname, float param) - { - gl.glTexEnvf( target, pname, param ); + @Override public final void glTexEnvf (int target, int pname, float param) { + gl.glTexEnvf(target, pname, param); } - @Override - public final void glTexEnvfv(int target, int pname, FloatBuffer params) - { - gl.glTexEnvfv( target, pname, params ); + @Override public final void glTexEnvfv (int target, int pname, FloatBuffer params) { + gl.glTexEnvfv(target, pname, params); } - @Override - public final void glTexEnvx(int target, int pname, int param) - { - gl.glTexEnvf( target, pname, FIXED_TO_FLOAT * param ); + @Override public final void glTexEnvx (int target, int pname, int param) { + gl.glTexEnvf(target, pname, FIXED_TO_FLOAT * param); } - @Override - public final void glTexEnvxv(int target, int pname, IntBuffer params) - { - if( tmp.length < params.capacity() ) - tmp = new float[params.capacity()]; + @Override public final void glTexEnvxv (int target, int pname, IntBuffer params) { + if (tmp.length < params.capacity()) tmp = new float[params.capacity()]; int i = 0; - while( params.hasRemaining() ) + while (params.hasRemaining()) tmp[i++] = FIXED_TO_FLOAT * params.get(); - gl.glTexEnvfv( target, pname, tmp, 0 ); + gl.glTexEnvfv(target, pname, tmp, 0); } - @Override - public final void glTexImage2D(int target, int level, int internalformat, - int width, int height, int border, int format, int type, - Buffer pixels) - { - gl.glTexImage2D( target, level, internalformat, width, height, border, format, type, pixels ); + @Override public final void glTexImage2D (int target, int level, int internalformat, int width, int height, int border, + int format, int type, Buffer pixels) { + gl.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); } - @Override - public final void glTexParameterf(int target, int pname, float param) - { - gl.glTexParameterf( target, pname, param ); + @Override public final void glTexParameterf (int target, int pname, float param) { + gl.glTexParameterf(target, pname, param); } - @Override - public final void glTexParameterx(int target, int pname, int param) - { - gl.glTexParameterf( target, pname, FIXED_TO_FLOAT * param ); + @Override public final void glTexParameterx (int target, int pname, int param) { + gl.glTexParameterf(target, pname, FIXED_TO_FLOAT * param); } - @Override - public final void glTexSubImage2D(int target, int level, int xoffset, - int yoffset, int width, int height, int format, int type, - Buffer pixels) - { - gl.glTexSubImage2D( target, level, xoffset, yoffset, width, height, format, type, pixels ); + @Override public final void glTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, + int format, int type, Buffer pixels) { + gl.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); } - @Override - public final void glTranslatef(float x, float y, float z) - { - gl.glTranslatef( x, y, z ); + @Override public final void glTranslatef (float x, float y, float z) { + gl.glTranslatef(x, y, z); } - @Override - public final void glTranslatex(int x, int y, int z) - { - gl.glTranslatef( FIXED_TO_FLOAT * x, FIXED_TO_FLOAT * y, FIXED_TO_FLOAT * z ); + @Override public final void glTranslatex (int x, int y, int z) { + gl.glTranslatef(FIXED_TO_FLOAT * x, FIXED_TO_FLOAT * y, FIXED_TO_FLOAT * z); } - @Override - public final void glVertexPointer(int size, int type, int stride, Buffer pointer) - { - if( type == GL10.GL_FIXED ) - { - convertFixedToFloatbuffer(pointer,vertexBuffer, stride); - gl.glVertexPointer( size, GL10.GL_FLOAT, stride, vertexBuffer ); - } - else - gl.glVertexPointer( size, GL10.GL_FLOAT, stride, pointer ); + @Override public final void glVertexPointer (int size, int type, int stride, Buffer pointer) { + if (type == GL10.GL_FIXED) { + convertFixedToFloatbuffer(pointer, vertexBuffer, stride); + gl.glVertexPointer(size, GL10.GL_FLOAT, stride, vertexBuffer); + } else + gl.glVertexPointer(size, GL10.GL_FLOAT, stride, pointer); } - @Override - public final void glViewport(int x, int y, int width, int height) - { - gl.glViewport( x, y, width, height ); + @Override public final void glViewport (int x, int y, int width, int height) { + gl.glViewport(x, y, width, height); } - @Override - public final void glDeleteTextures(int n, int[] textures, int offset) - { - gl.glDeleteTextures( n, textures, offset ); + @Override public final void glDeleteTextures (int n, int[] textures, int offset) { + gl.glDeleteTextures(n, textures, offset); } - @Override - public final void glFogfv(int pname, float[] params, int offset) - { - gl.glFogfv( pname, params, offset ); + @Override public final void glFogfv (int pname, float[] params, int offset) { + gl.glFogfv(pname, params, offset); } - @Override - public final void glFogxv(int pname, int[] params, int offset) - { - if( params.length > tmp.length ) - tmp = new float[params.length]; - for( int i = 0; i + offset< params.length; i++ ) + @Override public final void glFogxv (int pname, int[] params, int offset) { + if (params.length > tmp.length) tmp = new float[params.length]; + for (int i = 0; i + offset < params.length; i++) tmp[i] = FIXED_TO_FLOAT * params[i + offset]; - gl.glFogfv( pname, tmp, 0 ); + gl.glFogfv(pname, tmp, 0); } - @Override - public final void glGenTextures(int n, int[] textures, int offset) - { - gl.glGenTextures( n, textures, offset ); + @Override public final void glGenTextures (int n, int[] textures, int offset) { + gl.glGenTextures(n, textures, offset); } - @Override - public final void glGetIntegerv(int pname, int[] params, int offset) - { - gl.glGetIntegerv( pname, params, offset ); + @Override public final void glGetIntegerv (int pname, int[] params, int offset) { + gl.glGetIntegerv(pname, params, offset); } - @Override - public final void glLightModelfv(int pname, float[] params, int offset) - { - gl.glLightModelfv( pname, params, offset ); + @Override public final void glLightModelfv (int pname, float[] params, int offset) { + gl.glLightModelfv(pname, params, offset); } - @Override - public final void glLightModelxv(int pname, int[] params, int offset) - { - if( params.length > tmp.length ) - tmp = new float[params.length]; - for( int i = 0; i + offset< params.length; i++ ) + @Override public final void glLightModelxv (int pname, int[] params, int offset) { + if (params.length > tmp.length) tmp = new float[params.length]; + for (int i = 0; i + offset < params.length; i++) tmp[i] = FIXED_TO_FLOAT * params[i + offset]; - gl.glLightModelfv( pname, tmp, 0 ); + gl.glLightModelfv(pname, tmp, 0); } - @Override - public final void glLightfv(int light, int pname, float[] params, int offset) - { - gl.glLightfv( light, pname, params, offset ); + @Override public final void glLightfv (int light, int pname, float[] params, int offset) { + gl.glLightfv(light, pname, params, offset); } - @Override - public final void glLightxv(int light, int pname, int[] params, int offset) - { - if( params.length > tmp.length ) - tmp = new float[params.length]; - for( int i = 0; i + offset < params.length; i++ ) + @Override public final void glLightxv (int light, int pname, int[] params, int offset) { + if (params.length > tmp.length) tmp = new float[params.length]; + for (int i = 0; i + offset < params.length; i++) tmp[i] = FIXED_TO_FLOAT * params[i + offset]; - gl.glLightfv( light, pname, tmp, 0 ); + gl.glLightfv(light, pname, tmp, 0); } - @Override - public final void glLoadMatrixf(float[] m, int offset) - { - gl.glLoadMatrixf( m, offset ); + @Override public final void glLoadMatrixf (float[] m, int offset) { + gl.glLoadMatrixf(m, offset); } - @Override - public final void glLoadMatrixx(int[] m, int offset) - { - if( m.length > tmp.length ) - tmp = new float[m.length]; - for( int i = 0; i + offset< m.length; i++ ) + @Override public final void glLoadMatrixx (int[] m, int offset) { + if (m.length > tmp.length) tmp = new float[m.length]; + for (int i = 0; i + offset < m.length; i++) tmp[i] = FIXED_TO_FLOAT * m[i + offset]; - gl.glLoadMatrixf( tmp, 0 ); + gl.glLoadMatrixf(tmp, 0); } - @Override - public final void glMaterialfv(int face, int pname, float[] params, int offset) - { - gl.glMaterialfv( face, pname, params, offset ); + @Override public final void glMaterialfv (int face, int pname, float[] params, int offset) { + gl.glMaterialfv(face, pname, params, offset); } - @Override - public final void glMaterialxv(int face, int pname, int[] params, int offset) - { - if( params.length > tmp.length ) - tmp = new float[params.length]; - for( int i = 0; i + offset < params.length; i++ ) + @Override public final void glMaterialxv (int face, int pname, int[] params, int offset) { + if (params.length > tmp.length) tmp = new float[params.length]; + for (int i = 0; i + offset < params.length; i++) tmp[i] = FIXED_TO_FLOAT * params[i + offset]; - gl.glMaterialfv( face, pname, tmp, 0 ); + gl.glMaterialfv(face, pname, tmp, 0); } - @Override - public final void glMultMatrixf(float[] m, int offset) - { - gl.glMultMatrixf( m, offset ); + @Override public final void glMultMatrixf (float[] m, int offset) { + gl.glMultMatrixf(m, offset); } - @Override - public final void glMultMatrixx(int[] m, int offset) - { - if( m.length > tmp.length ) - tmp = new float[m.length]; - for( int i = 0; i + offset< m.length; i++ ) + @Override public final void glMultMatrixx (int[] m, int offset) { + if (m.length > tmp.length) tmp = new float[m.length]; + for (int i = 0; i + offset < m.length; i++) tmp[i] = FIXED_TO_FLOAT * m[i + offset]; - gl.glMultMatrixf( tmp, 0 ); + gl.glMultMatrixf(tmp, 0); } - @Override - public final void glTexEnvfv(int target, int pname, float[] params, int offset) - { - gl.glTexEnvfv( target, pname, params, offset ); + @Override public final void glTexEnvfv (int target, int pname, float[] params, int offset) { + gl.glTexEnvfv(target, pname, params, offset); } - @Override - public final void glTexEnvxv(int target, int pname, int[] params, int offset) - { - if( params.length > tmp.length ) - tmp = new float[params.length]; - for( int i = 0; i + offset< params.length; i++ ) + @Override public final void glTexEnvxv (int target, int pname, int[] params, int offset) { + if (params.length > tmp.length) tmp = new float[params.length]; + for (int i = 0; i + offset < params.length; i++) tmp[i] = FIXED_TO_FLOAT * params[i + offset]; - gl.glTexEnvfv( target, pname, tmp, 0 ); + gl.glTexEnvfv(target, pname, tmp, 0); } - @Override - public void glPolygonMode(int face, int mode) - { - gl.glPolygonMode( face, mode ); - } + @Override public void glPolygonMode (int face, int mode) { + gl.glPolygonMode(face, mode); + } } diff --git a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglGL11.java b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglGL11.java index c668f9634..0699d5a53 100644 --- a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglGL11.java +++ b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglGL11.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.desktop; import java.nio.Buffer; @@ -25,453 +23,307 @@ import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.GL11; /** - * An implementation of the {@link GL11} interface based on Jogl. Fixed point - * vertex arrays are emulated. Some glGetXXX methods are not implemented. + * An implementation of the {@link GL11} interface based on Jogl. Fixed point vertex arrays are emulated. Some glGetXXX methods + * are not implemented. * * @author mzechner - * + * */ -public final class JoglGL11 extends JoglGL10 implements GL11 -{ +public final class JoglGL11 extends JoglGL10 implements GL11 { double tmpDouble[] = new double[1000]; float tmpFloat[] = new float[1000]; - - public JoglGL11(GL gl) - { + + public JoglGL11 (GL gl) { super(gl); } - @Override - public void glBindBuffer(int target, int buffer) - { - gl.glBindBuffer( target, buffer ); + @Override public void glBindBuffer (int target, int buffer) { + gl.glBindBuffer(target, buffer); } - @Override - public void glBufferData(int target, int size, Buffer data, int usage) - { - gl.glBufferData( target, size, data, usage ); + @Override public void glBufferData (int target, int size, Buffer data, int usage) { + gl.glBufferData(target, size, data, usage); } - @Override - public void glBufferSubData(int target, int offset, int size, Buffer data) - { - gl.glBufferSubData( target, offset, size, data ); + @Override public void glBufferSubData (int target, int offset, int size, Buffer data) { + gl.glBufferSubData(target, offset, size, data); } - @Override - public void glClipPlanef(int plane, float[] equation, int offset) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glClipPlanef (int plane, float[] equation, int offset) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glClipPlanef(int plane, FloatBuffer equation) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glClipPlanef (int plane, FloatBuffer equation) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glClipPlanex(int plane, int[] equation, int offset) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glClipPlanex (int plane, int[] equation, int offset) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glClipPlanex(int plane, IntBuffer equation) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glClipPlanex (int plane, IntBuffer equation) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glColor4ub(byte red, byte green, byte blue, byte alpha) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glColor4ub (byte red, byte green, byte blue, byte alpha) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glDeleteBuffers(int n, int[] buffers, int offset) - { - gl.glDeleteBuffers( n, buffers, offset ); + @Override public void glDeleteBuffers (int n, int[] buffers, int offset) { + gl.glDeleteBuffers(n, buffers, offset); } - @Override - public void glDeleteBuffers(int n, IntBuffer buffers) - { - gl.glDeleteBuffers( n, buffers ); + @Override public void glDeleteBuffers (int n, IntBuffer buffers) { + gl.glDeleteBuffers(n, buffers); } - @Override - public void glGenBuffers(int n, int[] buffers, int offset) - { - gl.glGenBuffers( n, buffers, offset ); + @Override public void glGenBuffers (int n, int[] buffers, int offset) { + gl.glGenBuffers(n, buffers, offset); } - @Override - public void glGenBuffers(int n, IntBuffer buffers) - { - gl.glGenBuffers( n, buffers ); + @Override public void glGenBuffers (int n, IntBuffer buffers) { + gl.glGenBuffers(n, buffers); } - @Override - public void glGetBooleanv(int pname, boolean[] params, int offset) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetBooleanv (int pname, boolean[] params, int offset) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetBooleanv(int pname, IntBuffer params) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetBooleanv (int pname, IntBuffer params) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetBufferParameteriv(int target, int pname, int[] params, int offset) - { - gl.glGetBufferParameteriv( target, pname, params, offset ); + @Override public void glGetBufferParameteriv (int target, int pname, int[] params, int offset) { + gl.glGetBufferParameteriv(target, pname, params, offset); } - @Override - public void glGetBufferParameteriv(int target, int pname, IntBuffer params) - { - gl.glGetBufferParameteriv(target, pname, params ); + @Override public void glGetBufferParameteriv (int target, int pname, IntBuffer params) { + gl.glGetBufferParameteriv(target, pname, params); } - @Override - public void glGetClipPlanef(int pname, float[] eqn, int offset) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetClipPlanef (int pname, float[] eqn, int offset) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetClipPlanef(int pname, FloatBuffer eqn) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetClipPlanef (int pname, FloatBuffer eqn) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetClipPlanex(int pname, int[] eqn, int offset) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetClipPlanex (int pname, int[] eqn, int offset) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetClipPlanex(int pname, IntBuffer eqn) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetClipPlanex (int pname, IntBuffer eqn) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetFixedv(int pname, int[] params, int offset) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetFixedv (int pname, int[] params, int offset) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetFixedv(int pname, IntBuffer params) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetFixedv (int pname, IntBuffer params) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetFloatv(int pname, float[] params, int offset) - { - gl.glGetFloatv( pname, params, offset ); + @Override public void glGetFloatv (int pname, float[] params, int offset) { + gl.glGetFloatv(pname, params, offset); } - @Override - public void glGetFloatv(int pname, FloatBuffer params) - { - gl.glGetFloatv( pname, params ); + @Override public void glGetFloatv (int pname, FloatBuffer params) { + gl.glGetFloatv(pname, params); } - @Override - public void glGetLightfv(int light, int pname, float[] params, int offset) - { - gl.glGetLightfv( light, pname, params, offset ); + @Override public void glGetLightfv (int light, int pname, float[] params, int offset) { + gl.glGetLightfv(light, pname, params, offset); } - @Override - public void glGetLightfv(int light, int pname, FloatBuffer params) - { - gl.glGetLightfv( light, pname, params ); + @Override public void glGetLightfv (int light, int pname, FloatBuffer params) { + gl.glGetLightfv(light, pname, params); } - @Override - public void glGetLightxv(int light, int pname, int[] params, int offset) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetLightxv (int light, int pname, int[] params, int offset) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetLightxv(int light, int pname, IntBuffer params) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetLightxv (int light, int pname, IntBuffer params) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetMaterialfv(int face, int pname, float[] params, int offset) - { - gl.glGetMaterialfv( face, pname, params, offset ); + @Override public void glGetMaterialfv (int face, int pname, float[] params, int offset) { + gl.glGetMaterialfv(face, pname, params, offset); } - @Override - public void glGetMaterialfv(int face, int pname, FloatBuffer params) - { - gl.glGetMaterialfv( face, pname, params ); + @Override public void glGetMaterialfv (int face, int pname, FloatBuffer params) { + gl.glGetMaterialfv(face, pname, params); } - @Override - public void glGetMaterialxv(int face, int pname, int[] params, int offset) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetMaterialxv (int face, int pname, int[] params, int offset) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetMaterialxv(int face, int pname, IntBuffer params) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetMaterialxv (int face, int pname, IntBuffer params) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetPointerv(int pname, Buffer[] params) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetPointerv (int pname, Buffer[] params) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetTexEnviv(int env, int pname, int[] params, int offset) - { - gl.glGetTexEnviv( env, pname, params, offset ); + @Override public void glGetTexEnviv (int env, int pname, int[] params, int offset) { + gl.glGetTexEnviv(env, pname, params, offset); } - @Override - public void glGetTexEnviv(int env, int pname, IntBuffer params) - { - gl.glGetTexEnviv( env, pname, params ); + @Override public void glGetTexEnviv (int env, int pname, IntBuffer params) { + gl.glGetTexEnviv(env, pname, params); } - @Override - public void glGetTexEnvxv(int env, int pname, int[] params, int offset) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetTexEnvxv (int env, int pname, int[] params, int offset) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetTexEnvxv(int env, int pname, IntBuffer params) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetTexEnvxv (int env, int pname, IntBuffer params) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetTexParameterfv(int target, int pname, float[] params, int offset) - { - gl.glGetTexParameterfv( target, pname, params, offset ); + @Override public void glGetTexParameterfv (int target, int pname, float[] params, int offset) { + gl.glGetTexParameterfv(target, pname, params, offset); } - @Override - public void glGetTexParameterfv(int target, int pname, FloatBuffer params) - { - gl.glGetTexParameterfv( target, pname, params ); + @Override public void glGetTexParameterfv (int target, int pname, FloatBuffer params) { + gl.glGetTexParameterfv(target, pname, params); } - @Override - public void glGetTexParameteriv(int target, int pname, int[] params, int offset) - { - gl.glGetTexParameteriv( target, pname, params, offset ); + @Override public void glGetTexParameteriv (int target, int pname, int[] params, int offset) { + gl.glGetTexParameteriv(target, pname, params, offset); } - @Override - public void glGetTexParameteriv(int target, int pname, IntBuffer params) - { - gl.glGetTexParameteriv( target, pname, params ); + @Override public void glGetTexParameteriv (int target, int pname, IntBuffer params) { + gl.glGetTexParameteriv(target, pname, params); } - @Override - public void glGetTexParameterxv(int target, int pname, int[] params, int offset) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetTexParameterxv (int target, int pname, int[] params, int offset) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glGetTexParameterxv(int target, int pname, IntBuffer params) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glGetTexParameterxv (int target, int pname, IntBuffer params) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public boolean glIsBuffer(int buffer) - { - return gl.glIsBuffer( buffer ); + @Override public boolean glIsBuffer (int buffer) { + return gl.glIsBuffer(buffer); } - @Override - public boolean glIsEnabled(int cap) - { - return gl.glIsEnabled( cap ); + @Override public boolean glIsEnabled (int cap) { + return gl.glIsEnabled(cap); } - @Override - public boolean glIsTexture(int texture) - { - return gl.glIsTexture( texture ); + @Override public boolean glIsTexture (int texture) { + return gl.glIsTexture(texture); } - @Override - public void glPointParameterf(int pname, float param) - { - gl.glPointParameterf( pname, param ); + @Override public void glPointParameterf (int pname, float param) { + gl.glPointParameterf(pname, param); } - @Override - public void glPointParameterfv(int pname, float[] params, int offset) - { - gl.glPointParameterfv( pname, params, offset ); + @Override public void glPointParameterfv (int pname, float[] params, int offset) { + gl.glPointParameterfv(pname, params, offset); } - @Override - public void glPointParameterfv(int pname, FloatBuffer params) - { - gl.glPointParameterfv( pname, params ); + @Override public void glPointParameterfv (int pname, FloatBuffer params) { + gl.glPointParameterfv(pname, params); } - @Override - public void glPointParameterx(int pname, int param) - { - gl.glPointParameterf(pname, FIXED_TO_FLOAT * param ); + @Override public void glPointParameterx (int pname, int param) { + gl.glPointParameterf(pname, FIXED_TO_FLOAT * param); } - @Override - public void glPointParameterxv(int pname, int[] params, int offset) - { - if( tmpFloat.length < params.length ) - tmpFloat = new float[params.length]; - for( int i = 0; i < params.length; i++ ) + @Override public void glPointParameterxv (int pname, int[] params, int offset) { + if (tmpFloat.length < params.length) tmpFloat = new float[params.length]; + for (int i = 0; i < params.length; i++) tmpFloat[i] = FIXED_TO_FLOAT * params[i]; - gl.glPointParameterfv( pname, tmpFloat, offset ); + gl.glPointParameterfv(pname, tmpFloat, offset); } - @Override - public void glPointParameterxv(int pname, IntBuffer params) - { - if( tmpFloat.length < params.capacity() ) - tmpFloat = new float[params.capacity()]; + @Override public void glPointParameterxv (int pname, IntBuffer params) { + if (tmpFloat.length < params.capacity()) tmpFloat = new float[params.capacity()]; int i = 0; - while( params.hasRemaining() ) + while (params.hasRemaining()) tmpFloat[i] = FIXED_TO_FLOAT * params.get(); - gl.glPointParameterfv( pname, tmpFloat, 0 ); + gl.glPointParameterfv(pname, tmpFloat, 0); } - @Override - public void glPointSizePointerOES(int type, int stride, Buffer pointer) - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void glPointSizePointerOES (int type, int stride, Buffer pointer) { + throw new UnsupportedOperationException("not implemented"); } - @Override - public void glTexEnvi(int target, int pname, int param) - { - gl.glTexEnvi( target, pname, param ); + @Override public void glTexEnvi (int target, int pname, int param) { + gl.glTexEnvi(target, pname, param); } - @Override - public void glTexEnviv(int target, int pname, int[] params, int offset) - { - gl.glTexEnviv( target, pname, params, offset ); + @Override public void glTexEnviv (int target, int pname, int[] params, int offset) { + gl.glTexEnviv(target, pname, params, offset); } - @Override - public void glTexEnviv(int target, int pname, IntBuffer params) - { - gl.glTexEnviv( target, pname, params ); + @Override public void glTexEnviv (int target, int pname, IntBuffer params) { + gl.glTexEnviv(target, pname, params); } - @Override - public void glTexParameterfv(int target, int pname, float[] params, int offset) - { - gl.glTexParameterfv( target, pname, params, offset ); + @Override public void glTexParameterfv (int target, int pname, float[] params, int offset) { + gl.glTexParameterfv(target, pname, params, offset); } - @Override - public void glTexParameterfv(int target, int pname, FloatBuffer params) - { - gl.glTexParameterfv( target, pname, params ); + @Override public void glTexParameterfv (int target, int pname, FloatBuffer params) { + gl.glTexParameterfv(target, pname, params); } - @Override - public void glTexParameteri(int target, int pname, int param) - { - gl.glTexParameteri( target, pname, param ); + @Override public void glTexParameteri (int target, int pname, int param) { + gl.glTexParameteri(target, pname, param); } - @Override - public void glTexParameteriv(int target, int pname, int[] params, int offset) - { - gl.glTexParameteriv( target, pname, params, offset ); + @Override public void glTexParameteriv (int target, int pname, int[] params, int offset) { + gl.glTexParameteriv(target, pname, params, offset); } - @Override - public void glTexParameteriv(int target, int pname, IntBuffer params) - { - gl.glTexParameteriv( target, pname, params ); + @Override public void glTexParameteriv (int target, int pname, IntBuffer params) { + gl.glTexParameteriv(target, pname, params); } - @Override - public void glTexParameterxv(int target, int pname, int[] params, int offset) - { - if( tmpFloat.length < params.length ) - tmpFloat = new float[params.length]; - for( int i = 0; i < params.length; i++ ) + @Override public void glTexParameterxv (int target, int pname, int[] params, int offset) { + if (tmpFloat.length < params.length) tmpFloat = new float[params.length]; + for (int i = 0; i < params.length; i++) tmpFloat[i] = params[i]; - gl.glTexParameterfv( target, pname, tmpFloat, offset ); + gl.glTexParameterfv(target, pname, tmpFloat, offset); } - @Override - public void glTexParameterxv(int target, int pname, IntBuffer params) - { - if( tmpFloat.length < params.capacity() ) - tmpFloat = new float[params.capacity()]; + @Override public void glTexParameterxv (int target, int pname, IntBuffer params) { + if (tmpFloat.length < params.capacity()) tmpFloat = new float[params.capacity()]; int i = 0; - while( params.hasRemaining() ) + while (params.hasRemaining()) tmpFloat[i] = FIXED_TO_FLOAT * params.get(); - gl.glTexParameterfv( target, pname, tmpFloat, 0 ); + gl.glTexParameterfv(target, pname, tmpFloat, 0); } - @Override - public void glColorPointer(int size, int type, int stride, int pointer) - { - if( type == GL10.GL_FIXED ) - type = GL10.GL_FLOAT; - gl.glColorPointer( size, type, stride, pointer ); + @Override public void glColorPointer (int size, int type, int stride, int pointer) { + if (type == GL10.GL_FIXED) type = GL10.GL_FLOAT; + gl.glColorPointer(size, type, stride, pointer); } - @Override - public void glNormalPointer( int type, int stride, int pointer) - { - if( type == GL10.GL_FIXED ) - type = GL10.GL_FLOAT; - gl.glNormalPointer( type, stride, pointer ); + @Override public void glNormalPointer (int type, int stride, int pointer) { + if (type == GL10.GL_FIXED) type = GL10.GL_FLOAT; + gl.glNormalPointer(type, stride, pointer); } - @Override - public void glTexCoordPointer(int size, int type, int stride, int pointer) - { - if( type == GL10.GL_FIXED ) - type = GL10.GL_FLOAT; - gl.glTexCoordPointer( size, type, stride, pointer ); + @Override public void glTexCoordPointer (int size, int type, int stride, int pointer) { + if (type == GL10.GL_FIXED) type = GL10.GL_FLOAT; + gl.glTexCoordPointer(size, type, stride, pointer); } - @Override - public void glVertexPointer(int size, int type, int stride, int pointer) - { - if( type == GL10.GL_FIXED ) - type = GL10.GL_FLOAT; - gl.glVertexPointer( size, type, stride, pointer ); + @Override public void glVertexPointer (int size, int type, int stride, int pointer) { + if (type == GL10.GL_FIXED) type = GL10.GL_FLOAT; + gl.glVertexPointer(size, type, stride, pointer); } - - @Override - public void glDrawElements( int mode, int count, int type, int indices ) - { - gl.glDrawElements( mode, count, type, indices ); + + @Override public void glDrawElements (int mode, int count, int type, int indices) { + gl.glDrawElements(mode, count, type, indices); } } diff --git a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglGL20.java b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglGL20.java index 414af532d..80d51a2fb 100644 --- a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglGL20.java +++ b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglGL20.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.desktop; import java.nio.Buffer; @@ -26,927 +24,619 @@ import javax.media.opengl.GL; import com.badlogic.gdx.graphics.GL20; /** - * An implementation of the {@link GL20} interface based on Jogl. Note that - * Jogl shaders and OpenGL ES shaders will not be 100% compatible. Some glGetXXX - * methods are not implemented. + * An implementation of the {@link GL20} interface based on Jogl. Note that Jogl shaders and OpenGL ES shaders will not be 100% + * compatible. Some glGetXXX methods are not implemented. * * @author mzechner - * + * */ -final class JoglGL20 implements GL20 -{ +final class JoglGL20 implements GL20 { private final GL gl; - public JoglGL20( GL gl ) - { + public JoglGL20 (GL gl) { this.gl = gl; } - - @Override - public void glActiveTexture(int texture) - { - gl.glActiveTexture( texture ); + + @Override public void glActiveTexture (int texture) { + gl.glActiveTexture(texture); } - @Override - public void glAttachShader(int program, int shader) - { - gl.glAttachShader( program, shader ); + @Override public void glAttachShader (int program, int shader) { + gl.glAttachShader(program, shader); } - @Override - public void glBindAttribLocation(int program, int index, String name) - { - gl.glBindAttribLocation( program, index, name ); + @Override public void glBindAttribLocation (int program, int index, String name) { + gl.glBindAttribLocation(program, index, name); } - @Override - public void glBindBuffer(int target, int buffer) - { - gl.glBindBuffer( target, buffer ); + @Override public void glBindBuffer (int target, int buffer) { + gl.glBindBuffer(target, buffer); } - @Override - public void glBindFramebuffer(int target, int framebuffer) - { - gl.glBindFramebufferEXT( target, framebuffer ); + @Override public void glBindFramebuffer (int target, int framebuffer) { + gl.glBindFramebufferEXT(target, framebuffer); } - @Override - public void glBindRenderbuffer(int target, int renderbuffer) - { - gl.glBindRenderbufferEXT( target, renderbuffer ); + @Override public void glBindRenderbuffer (int target, int renderbuffer) { + gl.glBindRenderbufferEXT(target, renderbuffer); } - @Override - public void glBindTexture(int target, int texture) - { - gl.glBindTexture( target, texture ); + @Override public void glBindTexture (int target, int texture) { + gl.glBindTexture(target, texture); } - @Override - public void glBlendColor(float red, float green, float blue, float alpha) - { - gl.glBlendColor( red, green, blue, alpha ); + @Override public void glBlendColor (float red, float green, float blue, float alpha) { + gl.glBlendColor(red, green, blue, alpha); } - @Override - public void glBlendEquation(int mode) - { - gl.glBlendEquation( mode ); + @Override public void glBlendEquation (int mode) { + gl.glBlendEquation(mode); } - @Override - public void glBlendEquationSeparate(int modeRGB, int modeAlpha) - { - gl.glBlendEquationSeparate( modeRGB, modeAlpha ); + @Override public void glBlendEquationSeparate (int modeRGB, int modeAlpha) { + gl.glBlendEquationSeparate(modeRGB, modeAlpha); } - @Override - public void glBlendFunc(int sfactor, int dfactor) - { - gl.glBlendFunc( sfactor, dfactor ); + @Override public void glBlendFunc (int sfactor, int dfactor) { + gl.glBlendFunc(sfactor, dfactor); } - @Override - public void glBlendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) - { - gl.glBlendFuncSeparate( srcRGB, dstRGB, srcAlpha, dstAlpha ); + @Override public void glBlendFuncSeparate (int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) { + gl.glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha); } - @Override - public void glBufferData(int target, int size, Buffer data, int usage) - { - gl.glBufferData( target, size, data, usage ); + @Override public void glBufferData (int target, int size, Buffer data, int usage) { + gl.glBufferData(target, size, data, usage); } - @Override - public void glBufferSubData(int target, int offset, int size, Buffer data) - { - gl.glBufferSubData( target, offset, size, data ); + @Override public void glBufferSubData (int target, int offset, int size, Buffer data) { + gl.glBufferSubData(target, offset, size, data); } - @Override - public int glCheckFramebufferStatus(int target) - { - return gl.glCheckFramebufferStatusEXT( target ); + @Override public int glCheckFramebufferStatus (int target) { + return gl.glCheckFramebufferStatusEXT(target); } - @Override - public void glClear(int mask) - { - gl.glClear( mask ); + @Override public void glClear (int mask) { + gl.glClear(mask); } - @Override - public void glClearColor(float red, float green, float blue, float alpha) - { - gl.glClearColor( red, green, blue, alpha ); + @Override public void glClearColor (float red, float green, float blue, float alpha) { + gl.glClearColor(red, green, blue, alpha); } - @Override - public void glClearDepthf(float depth) - { - gl.glClearDepth( depth ); + @Override public void glClearDepthf (float depth) { + gl.glClearDepth(depth); } - @Override - public void glClearStencil(int s) - { - gl.glClearStencil( s ); + @Override public void glClearStencil (int s) { + gl.glClearStencil(s); } - @Override - public void glColorMask(boolean red, boolean green, boolean blue, boolean alpha) - { - gl.glColorMask( red, green, blue, alpha ); + @Override public void glColorMask (boolean red, boolean green, boolean blue, boolean alpha) { + gl.glColorMask(red, green, blue, alpha); } - @Override - public void glCompileShader(int shader) - { - gl.glCompileShader( shader ); + @Override public void glCompileShader (int shader) { + gl.glCompileShader(shader); } - @Override - public void glCompressedTexImage2D(int target, int level, - int internalformat, int width, int height, int border, - int imageSize, Buffer data) - { - gl.glCompressedTexImage2D( target, level, internalformat, width, height, border, imageSize, data ); + @Override public void glCompressedTexImage2D (int target, int level, int internalformat, int width, int height, int border, + int imageSize, Buffer data) { + gl.glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); } - @Override - public void glCompressedTexSubImage2D(int target, int level, int xoffset, - int yoffset, int width, int height, int format, int imageSize, - Buffer data) - { - gl.glCompressedTexSubImage2D( target, level, xoffset, yoffset, width, height, format, imageSize, data ); + @Override public void glCompressedTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, + int format, int imageSize, Buffer data) { + gl.glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); } - @Override - public void glCopyTexImage2D(int target, int level, int internalformat, - int x, int y, int width, int height, int border) - { - gl.glCopyTexImage2D( target, level, internalformat, x, y, width, height, border ); + @Override public void glCopyTexImage2D (int target, int level, int internalformat, int x, int y, int width, int height, + int border) { + gl.glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); } - @Override - public void glCopyTexSubImage2D(int target, int level, int xoffset, - int yoffset, int x, int y, int width, int height) - { - gl.glCopyTexSubImage2D( target, level, xoffset, yoffset, x, y, width, height ); + @Override public void glCopyTexSubImage2D (int target, int level, int xoffset, int yoffset, int x, int y, int width, int height) { + gl.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); } - @Override - public int glCreateProgram() - { + @Override public int glCreateProgram () { return gl.glCreateProgram(); } - @Override - public int glCreateShader(int type) - { - return gl.glCreateShader( type ); + @Override public int glCreateShader (int type) { + return gl.glCreateShader(type); } - @Override - public void glCullFace(int mode) - { - gl.glCullFace( mode ); + @Override public void glCullFace (int mode) { + gl.glCullFace(mode); } - @Override - public void glDeleteBuffers(int n, IntBuffer buffers) - { - gl.glDeleteBuffers( n, buffers ); + @Override public void glDeleteBuffers (int n, IntBuffer buffers) { + gl.glDeleteBuffers(n, buffers); } - @Override - public void glDeleteFramebuffers(int n, IntBuffer framebuffers) - { - gl.glDeleteFramebuffersEXT( n, framebuffers ); + @Override public void glDeleteFramebuffers (int n, IntBuffer framebuffers) { + gl.glDeleteFramebuffersEXT(n, framebuffers); } - @Override - public void glDeleteProgram(int program) - { - gl.glDeleteProgram( program ); - } + @Override public void glDeleteProgram (int program) { + gl.glDeleteProgram(program); + } - @Override - public void glDeleteRenderbuffers(int n, IntBuffer renderbuffers) - { - gl.glDeleteRenderbuffersEXT( n, renderbuffers ); + @Override public void glDeleteRenderbuffers (int n, IntBuffer renderbuffers) { + gl.glDeleteRenderbuffersEXT(n, renderbuffers); } - @Override - public void glDeleteShader(int shader) - { - gl.glDeleteShader( shader ); + @Override public void glDeleteShader (int shader) { + gl.glDeleteShader(shader); } - @Override - public void glDeleteTextures(int n, IntBuffer textures) - { - gl.glDeleteTextures( n, textures ); + @Override public void glDeleteTextures (int n, IntBuffer textures) { + gl.glDeleteTextures(n, textures); } - @Override - public void glDepthFunc(int func) - { - gl.glDepthFunc( func ); + @Override public void glDepthFunc (int func) { + gl.glDepthFunc(func); } - @Override - public void glDepthMask(boolean flag) - { - gl.glDepthMask( flag ); + @Override public void glDepthMask (boolean flag) { + gl.glDepthMask(flag); } - @Override - public void glDepthRangef(float zNear, float zFar) - { - gl.glDepthRange( zNear, zFar ); + @Override public void glDepthRangef (float zNear, float zFar) { + gl.glDepthRange(zNear, zFar); } - @Override - public void glDetachShader(int program, int shader) - { - gl.glDetachShader( program, shader ); + @Override public void glDetachShader (int program, int shader) { + gl.glDetachShader(program, shader); } - @Override - public void glDisable(int cap) - { - gl.glDisable( cap ); + @Override public void glDisable (int cap) { + gl.glDisable(cap); } - @Override - public void glDisableVertexAttribArray(int index) - { - gl.glDisableVertexAttribArray( index ); + @Override public void glDisableVertexAttribArray (int index) { + gl.glDisableVertexAttribArray(index); } - @Override - public void glDrawArrays(int mode, int first, int count) - { - gl.glDrawArrays( mode, first, count ); + @Override public void glDrawArrays (int mode, int first, int count) { + gl.glDrawArrays(mode, first, count); } - @Override - public void glDrawElements(int mode, int count, int type, Buffer indices) - { - gl.glDrawElements( mode, count, type, indices ); + @Override public void glDrawElements (int mode, int count, int type, Buffer indices) { + gl.glDrawElements(mode, count, type, indices); } - @Override - public void glEnable(int cap) - { - gl.glEnable( cap ); + @Override public void glEnable (int cap) { + gl.glEnable(cap); } - @Override - public void glEnableVertexAttribArray(int index) - { - gl.glEnableVertexAttribArray( index ); + @Override public void glEnableVertexAttribArray (int index) { + gl.glEnableVertexAttribArray(index); } - @Override - public void glFinish() - { - gl.glFinish( ); + @Override public void glFinish () { + gl.glFinish(); } - @Override - public void glFlush() - { - gl.glFlush( ); + @Override public void glFlush () { + gl.glFlush(); } - @Override - public void glFramebufferRenderbuffer(int target, int attachment, - int renderbuffertarget, int renderbuffer) - { - gl.glFramebufferRenderbufferEXT( target, attachment, renderbuffertarget, renderbuffer ); + @Override public void glFramebufferRenderbuffer (int target, int attachment, int renderbuffertarget, int renderbuffer) { + gl.glFramebufferRenderbufferEXT(target, attachment, renderbuffertarget, renderbuffer); } - @Override - public void glFramebufferTexture2D(int target, int attachment, - int textarget, int texture, int level) - { - gl.glFramebufferTexture2DEXT( target, attachment, textarget, texture, level ); + @Override public void glFramebufferTexture2D (int target, int attachment, int textarget, int texture, int level) { + gl.glFramebufferTexture2DEXT(target, attachment, textarget, texture, level); } - @Override - public void glFrontFace(int mode) - { - gl.glFrontFace( mode ); + @Override public void glFrontFace (int mode) { + gl.glFrontFace(mode); } - @Override - public void glGenBuffers(int n, IntBuffer buffers) - { - gl.glGenBuffers( n, buffers ); + @Override public void glGenBuffers (int n, IntBuffer buffers) { + gl.glGenBuffers(n, buffers); } - @Override - public void glGenFramebuffers(int n, IntBuffer framebuffers) - { - gl.glGenFramebuffersEXT( n, framebuffers ); + @Override public void glGenFramebuffers (int n, IntBuffer framebuffers) { + gl.glGenFramebuffersEXT(n, framebuffers); } - @Override - public void glGenRenderbuffers(int n, IntBuffer renderbuffers) - { - gl.glGenRenderbuffersEXT( n, renderbuffers ); + @Override public void glGenRenderbuffers (int n, IntBuffer renderbuffers) { + gl.glGenRenderbuffersEXT(n, renderbuffers); } - @Override - public void glGenTextures(int n, IntBuffer textures) - { - gl.glGenTextures( n, textures ); + @Override public void glGenTextures (int n, IntBuffer textures) { + gl.glGenTextures(n, textures); } - @Override - public void glGenerateMipmap(int target) - { - gl.glGenerateMipmapEXT( target ); + @Override public void glGenerateMipmap (int target) { + gl.glGenerateMipmapEXT(target); } - @Override - public String glGetActiveAttrib(int program, int index, IntBuffer size, - Buffer type) - { - throw new UnsupportedOperationException( "not implemented" ); // FIXME + @Override public String glGetActiveAttrib (int program, int index, IntBuffer size, Buffer type) { + throw new UnsupportedOperationException("not implemented"); // FIXME } - @Override - public String glGetActiveUniform(int program, int index, IntBuffer size, - Buffer type) { - throw new UnsupportedOperationException( "not implemented" ); // FIXME + @Override public String glGetActiveUniform (int program, int index, IntBuffer size, Buffer type) { + throw new UnsupportedOperationException("not implemented"); // FIXME } - @Override - public void glGetAttachedShaders(int program, int maxcount, Buffer count, - IntBuffer shaders) - { - gl.glGetAttachedShaders( program, maxcount, (IntBuffer)count, shaders ); + @Override public void glGetAttachedShaders (int program, int maxcount, Buffer count, IntBuffer shaders) { + gl.glGetAttachedShaders(program, maxcount, (IntBuffer)count, shaders); } - @Override - public int glGetAttribLocation(int program, String name) - { - return gl.glGetAttribLocation( program, name ); + @Override public int glGetAttribLocation (int program, String name) { + return gl.glGetAttribLocation(program, name); } - @Override - public void glGetBooleanv(int pname, Buffer params) - { - throw new UnsupportedOperationException( "not implemented" ); // FIXME + @Override public void glGetBooleanv (int pname, Buffer params) { + throw new UnsupportedOperationException("not implemented"); // FIXME } - @Override - public void glGetBufferParameteriv(int target, int pname, IntBuffer params) - { - gl.glGetBufferParameteriv( target, pname, params ); + @Override public void glGetBufferParameteriv (int target, int pname, IntBuffer params) { + gl.glGetBufferParameteriv(target, pname, params); } - @Override - public int glGetError() - { + @Override public int glGetError () { return gl.glGetError(); } - @Override - public void glGetFloatv(int pname, FloatBuffer params) - { - gl.glGetFloatv( pname, params ); + @Override public void glGetFloatv (int pname, FloatBuffer params) { + gl.glGetFloatv(pname, params); } - @Override - public void glGetFramebufferAttachmentParameteriv(int target, - int attachment, int pname, IntBuffer params) - { - gl.glGetFramebufferAttachmentParameterivEXT( target, attachment, pname, params ); + @Override public void glGetFramebufferAttachmentParameteriv (int target, int attachment, int pname, IntBuffer params) { + gl.glGetFramebufferAttachmentParameterivEXT(target, attachment, pname, params); } - @Override - public void glGetIntegerv(int pname, IntBuffer params) - { - gl.glGetIntegerv( pname, params ); + @Override public void glGetIntegerv (int pname, IntBuffer params) { + gl.glGetIntegerv(pname, params); } - @Override - public String glGetProgramInfoLog(int program) - { - ByteBuffer buffer = ByteBuffer.allocateDirect( 1024*10 ); + @Override public String glGetProgramInfoLog (int program) { + ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 10); buffer.order(ByteOrder.nativeOrder()); - ByteBuffer tmp = ByteBuffer.allocateDirect( 4 ); + ByteBuffer tmp = ByteBuffer.allocateDirect(4); tmp.order(ByteOrder.nativeOrder()); IntBuffer intBuffer = tmp.asIntBuffer(); - - gl.glGetProgramInfoLog( program, 1024 * 10, intBuffer, buffer ); + + gl.glGetProgramInfoLog(program, 1024 * 10, intBuffer, buffer); int numBytes = intBuffer.get(0); byte[] bytes = new byte[numBytes]; buffer.get(bytes); - return new String( bytes ); + return new String(bytes); } - @Override - public void glGetProgramiv(int program, int pname, IntBuffer params) - { - gl.glGetProgramiv( program, pname, params ); + @Override public void glGetProgramiv (int program, int pname, IntBuffer params) { + gl.glGetProgramiv(program, pname, params); } - @Override - public void glGetRenderbufferParameteriv(int target, int pname, - IntBuffer params) - { - gl.glGetRenderbufferParameterivEXT( target, pname, params ); + @Override public void glGetRenderbufferParameteriv (int target, int pname, IntBuffer params) { + gl.glGetRenderbufferParameterivEXT(target, pname, params); } - @Override - public String glGetShaderInfoLog(int shader) - { - ByteBuffer buffer = ByteBuffer.allocateDirect( 1024*10 ); + @Override public String glGetShaderInfoLog (int shader) { + ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 10); buffer.order(ByteOrder.nativeOrder()); - ByteBuffer tmp = ByteBuffer.allocateDirect( 4 ); + ByteBuffer tmp = ByteBuffer.allocateDirect(4); tmp.order(ByteOrder.nativeOrder()); IntBuffer intBuffer = tmp.asIntBuffer(); - - gl.glGetShaderInfoLog( shader, 1024 * 10, intBuffer, buffer ); + + gl.glGetShaderInfoLog(shader, 1024 * 10, intBuffer, buffer); int numBytes = intBuffer.get(0); byte[] bytes = new byte[numBytes]; buffer.get(bytes); - return new String( bytes ); + return new String(bytes); } - @Override - public void glGetShaderPrecisionFormat(int shadertype, int precisiontype, - IntBuffer range, IntBuffer precision) - { - throw new UnsupportedOperationException( "unsupported, won't implement" ); + @Override public void glGetShaderPrecisionFormat (int shadertype, int precisiontype, IntBuffer range, IntBuffer precision) { + throw new UnsupportedOperationException("unsupported, won't implement"); } - @Override - public void glGetShaderSource(int shader, int bufsize, Buffer length, String source) - { - throw new UnsupportedOperationException( "unsupported, won't implement." ); + @Override public void glGetShaderSource (int shader, int bufsize, Buffer length, String source) { + throw new UnsupportedOperationException("unsupported, won't implement."); } - @Override - public void glGetShaderiv(int shader, int pname, IntBuffer params) - { - gl.glGetShaderiv( shader, pname, params ); + @Override public void glGetShaderiv (int shader, int pname, IntBuffer params) { + gl.glGetShaderiv(shader, pname, params); } - @Override - public String glGetString(int name) - { - return gl.glGetString( name ); + @Override public String glGetString (int name) { + return gl.glGetString(name); } - @Override - public void glGetTexParameterfv(int target, int pname, FloatBuffer params) - { - gl.glGetTexParameterfv( target, pname, params ); + @Override public void glGetTexParameterfv (int target, int pname, FloatBuffer params) { + gl.glGetTexParameterfv(target, pname, params); } - @Override - public void glGetTexParameteriv(int target, int pname, IntBuffer params) - { - gl.glGetTexParameteriv( target, pname, params ); + @Override public void glGetTexParameteriv (int target, int pname, IntBuffer params) { + gl.glGetTexParameteriv(target, pname, params); } - @Override - public int glGetUniformLocation(int program, String name) - { - return gl.glGetUniformLocation( program, name ); + @Override public int glGetUniformLocation (int program, String name) { + return gl.glGetUniformLocation(program, name); } - @Override - public void glGetUniformfv(int program, int location, FloatBuffer params) - { - gl.glGetUniformfv( program, location, params ); + @Override public void glGetUniformfv (int program, int location, FloatBuffer params) { + gl.glGetUniformfv(program, location, params); } - @Override - public void glGetUniformiv(int program, int location, IntBuffer params) - { - gl.glGetUniformiv( program, location, params ); + @Override public void glGetUniformiv (int program, int location, IntBuffer params) { + gl.glGetUniformiv(program, location, params); } - @Override - public void glGetVertexAttribPointerv(int index, int pname, Buffer pointer) - { - throw new UnsupportedOperationException( "unsupported, won't implement" ); + @Override public void glGetVertexAttribPointerv (int index, int pname, Buffer pointer) { + throw new UnsupportedOperationException("unsupported, won't implement"); } - @Override - public void glGetVertexAttribfv(int index, int pname, FloatBuffer params) - { - gl.glGetVertexAttribfv( index, pname, params ); + @Override public void glGetVertexAttribfv (int index, int pname, FloatBuffer params) { + gl.glGetVertexAttribfv(index, pname, params); } - @Override - public void glGetVertexAttribiv(int index, int pname, IntBuffer params) - { - gl.glGetVertexAttribiv( index, pname, params ); + @Override public void glGetVertexAttribiv (int index, int pname, IntBuffer params) { + gl.glGetVertexAttribiv(index, pname, params); } - @Override - public void glHint(int target, int mode) - { - gl.glHint( target, mode ); + @Override public void glHint (int target, int mode) { + gl.glHint(target, mode); } - @Override - public boolean glIsBuffer(int buffer) - { - return gl.glIsBuffer( buffer ); + @Override public boolean glIsBuffer (int buffer) { + return gl.glIsBuffer(buffer); } - @Override - public boolean glIsEnabled(int cap) - { - return gl.glIsEnabled( cap ); + @Override public boolean glIsEnabled (int cap) { + return gl.glIsEnabled(cap); } - @Override - public boolean glIsFramebuffer(int framebuffer) - { + @Override public boolean glIsFramebuffer (int framebuffer) { return gl.glIsFramebufferEXT(framebuffer); } - @Override - public boolean glIsProgram(int program) - { - return gl.glIsProgram( program ); + @Override public boolean glIsProgram (int program) { + return gl.glIsProgram(program); } - @Override - public boolean glIsRenderbuffer(int renderbuffer) - { - return gl.glIsRenderbufferEXT( renderbuffer ); + @Override public boolean glIsRenderbuffer (int renderbuffer) { + return gl.glIsRenderbufferEXT(renderbuffer); } - @Override - public boolean glIsShader(int shader) - { - return gl.glIsShader( shader ); + @Override public boolean glIsShader (int shader) { + return gl.glIsShader(shader); } - @Override - public boolean glIsTexture(int texture) - { - return gl.glIsTexture( texture ); + @Override public boolean glIsTexture (int texture) { + return gl.glIsTexture(texture); } - @Override - public void glLineWidth(float width) - { - gl.glLineWidth( width ); + @Override public void glLineWidth (float width) { + gl.glLineWidth(width); } - @Override - public void glLinkProgram(int program) - { - gl.glLinkProgram( program ); + @Override public void glLinkProgram (int program) { + gl.glLinkProgram(program); } - @Override - public void glPixelStorei(int pname, int param) - { - gl.glPixelStorei( pname, param ); + @Override public void glPixelStorei (int pname, int param) { + gl.glPixelStorei(pname, param); } - @Override - public void glPolygonOffset(float factor, float units) - { - gl.glPolygonOffset( factor, units ); + @Override public void glPolygonOffset (float factor, float units) { + gl.glPolygonOffset(factor, units); } - @Override - public void glReadPixels(int x, int y, int width, int height, int format, int type, Buffer pixels) - { - gl.glReadPixels( x, y, width, height, format, type, pixels ); + @Override public void glReadPixels (int x, int y, int width, int height, int format, int type, Buffer pixels) { + gl.glReadPixels(x, y, width, height, format, type, pixels); } - @Override - public void glReleaseShaderCompiler() - { + @Override public void glReleaseShaderCompiler () { // nothing to do here } - @Override - public void glRenderbufferStorage(int target, int internalformat, int width, int height) - { - gl.glRenderbufferStorageEXT( target, internalformat, width, height ); + @Override public void glRenderbufferStorage (int target, int internalformat, int width, int height) { + gl.glRenderbufferStorageEXT(target, internalformat, width, height); } - @Override - public void glSampleCoverage(float value, boolean invert) - { - gl.glSampleCoverage( value, invert ); + @Override public void glSampleCoverage (float value, boolean invert) { + gl.glSampleCoverage(value, invert); } - @Override - public void glScissor(int x, int y, int width, int height) - { - gl.glScissor( x, y, width, height ); + @Override public void glScissor (int x, int y, int width, int height) { + gl.glScissor(x, y, width, height); } - @Override - public void glShaderBinary(int n, IntBuffer shaders, int binaryformat, - Buffer binary, int length) - { - throw new UnsupportedOperationException( "unsupported, won't implement" ); + @Override public void glShaderBinary (int n, IntBuffer shaders, int binaryformat, Buffer binary, int length) { + throw new UnsupportedOperationException("unsupported, won't implement"); } - @Override - public void glShaderSource(int shader, String string) - { - gl.glShaderSource( shader, 1, new String[] { string }, null, 0 ); - + @Override public void glShaderSource (int shader, String string) { + gl.glShaderSource(shader, 1, new String[] {string}, null, 0); + } - @Override - public void glStencilFunc(int func, int ref, int mask) - { - gl.glStencilFunc( func, ref, mask ); + @Override public void glStencilFunc (int func, int ref, int mask) { + gl.glStencilFunc(func, ref, mask); } - @Override - public void glStencilFuncSeparate(int face, int func, int ref, int mask) - { - gl.glStencilFuncSeparate( face, func, ref, mask ); + @Override public void glStencilFuncSeparate (int face, int func, int ref, int mask) { + gl.glStencilFuncSeparate(face, func, ref, mask); } - @Override - public void glStencilMask(int mask) - { - gl.glStencilMask( mask ); + @Override public void glStencilMask (int mask) { + gl.glStencilMask(mask); } - @Override - public void glStencilMaskSeparate(int face, int mask) - { - gl.glStencilMaskSeparate( face, mask ); + @Override public void glStencilMaskSeparate (int face, int mask) { + gl.glStencilMaskSeparate(face, mask); } - @Override - public void glStencilOp(int fail, int zfail, int zpass) - { - gl.glStencilOp( fail, zfail, zpass ); + @Override public void glStencilOp (int fail, int zfail, int zpass) { + gl.glStencilOp(fail, zfail, zpass); } - @Override - public void glStencilOpSeparate(int face, int fail, int zfail, int zpass) - { - gl.glStencilOpSeparate( face, fail, zfail, zpass ); + @Override public void glStencilOpSeparate (int face, int fail, int zfail, int zpass) { + gl.glStencilOpSeparate(face, fail, zfail, zpass); } - @Override - public void glTexImage2D(int target, int level, int internalformat, - int width, int height, int border, int format, int type, - Buffer pixels) - { - gl.glTexImage2D( target, level, internalformat, width, height, border, format, type, pixels ); + @Override public void glTexImage2D (int target, int level, int internalformat, int width, int height, int border, int format, + int type, Buffer pixels) { + gl.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); } - @Override - public void glTexParameterf(int target, int pname, float param) - { - gl.glTexParameterf( target, pname, param ); + @Override public void glTexParameterf (int target, int pname, float param) { + gl.glTexParameterf(target, pname, param); } - @Override - public void glTexParameterfv(int target, int pname, FloatBuffer params) - { - gl.glTexParameterfv( target, pname, params ); + @Override public void glTexParameterfv (int target, int pname, FloatBuffer params) { + gl.glTexParameterfv(target, pname, params); } - @Override - public void glTexParameteri(int target, int pname, int param) - { - gl.glTexParameteri( target, pname, param ); + @Override public void glTexParameteri (int target, int pname, int param) { + gl.glTexParameteri(target, pname, param); } - @Override - public void glTexParameteriv(int target, int pname, IntBuffer params) - { - gl.glTexParameteriv( target, pname, params ); + @Override public void glTexParameteriv (int target, int pname, IntBuffer params) { + gl.glTexParameteriv(target, pname, params); } - @Override - public void glTexSubImage2D(int target, int level, int xoffset, - int yoffset, int width, int height, int format, int type, - Buffer pixels) - { - gl.glTexSubImage2D( target, level, xoffset, yoffset, width, height, format, type, pixels ); + @Override public void glTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, int format, + int type, Buffer pixels) { + gl.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); } - @Override - public void glUniform1f(int location, float x) - { - gl.glUniform1f( location, x ); + @Override public void glUniform1f (int location, float x) { + gl.glUniform1f(location, x); } - @Override - public void glUniform1fv(int location, int count, FloatBuffer v) - { - gl.glUniform1fv( location, count, v ); + @Override public void glUniform1fv (int location, int count, FloatBuffer v) { + gl.glUniform1fv(location, count, v); } - @Override - public void glUniform1i(int location, int x) - { - gl.glUniform1i( location, x ); + @Override public void glUniform1i (int location, int x) { + gl.glUniform1i(location, x); } - @Override - public void glUniform1iv(int location, int count, IntBuffer v) - { - gl.glUniform1iv( location, count, v ); + @Override public void glUniform1iv (int location, int count, IntBuffer v) { + gl.glUniform1iv(location, count, v); } - @Override - public void glUniform2f(int location, float x, float y) - { - gl.glUniform2f( location, x, y ); + @Override public void glUniform2f (int location, float x, float y) { + gl.glUniform2f(location, x, y); } - @Override - public void glUniform2fv(int location, int count, FloatBuffer v) - { - gl.glUniform2fv( location, count, v ); + @Override public void glUniform2fv (int location, int count, FloatBuffer v) { + gl.glUniform2fv(location, count, v); } - @Override - public void glUniform2i(int location, int x, int y) - { - gl.glUniform2i( location, x, y ); + @Override public void glUniform2i (int location, int x, int y) { + gl.glUniform2i(location, x, y); } - @Override - public void glUniform2iv(int location, int count, IntBuffer v) - { - gl.glUniform2iv( location, count, v ); + @Override public void glUniform2iv (int location, int count, IntBuffer v) { + gl.glUniform2iv(location, count, v); } - @Override - public void glUniform3f(int location, float x, float y, float z) - { - gl.glUniform3f( location, x, y, z ); + @Override public void glUniform3f (int location, float x, float y, float z) { + gl.glUniform3f(location, x, y, z); } - @Override - public void glUniform3fv(int location, int count, FloatBuffer v) - { - gl.glUniform3fv( location, count, v ); + @Override public void glUniform3fv (int location, int count, FloatBuffer v) { + gl.glUniform3fv(location, count, v); } - @Override - public void glUniform3i(int location, int x, int y, int z) - { - gl.glUniform3i( location, x, y, z ); + @Override public void glUniform3i (int location, int x, int y, int z) { + gl.glUniform3i(location, x, y, z); } - @Override - public void glUniform3iv(int location, int count, IntBuffer v) - { - gl.glUniform3iv( location, count, v ); + @Override public void glUniform3iv (int location, int count, IntBuffer v) { + gl.glUniform3iv(location, count, v); } - @Override - public void glUniform4f(int location, float x, float y, float z, float w) - { - gl.glUniform4f( location, x, y, z, w ); + @Override public void glUniform4f (int location, float x, float y, float z, float w) { + gl.glUniform4f(location, x, y, z, w); } - @Override - public void glUniform4fv(int location, int count, FloatBuffer v) - { - gl.glUniform4fv( location, count, v ); + @Override public void glUniform4fv (int location, int count, FloatBuffer v) { + gl.glUniform4fv(location, count, v); } - @Override - public void glUniform4i(int location, int x, int y, int z, int w) - { - gl.glUniform4i( location, x, y, z, w ); + @Override public void glUniform4i (int location, int x, int y, int z, int w) { + gl.glUniform4i(location, x, y, z, w); } - @Override - public void glUniform4iv(int location, int count, IntBuffer v) - { - gl.glUniform4iv( location, count, v ); + @Override public void glUniform4iv (int location, int count, IntBuffer v) { + gl.glUniform4iv(location, count, v); } - @Override - public void glUniformMatrix2fv(int location, int count, boolean transpose, - FloatBuffer value) - { - gl.glUniformMatrix2fv( location, count, transpose, value ); + @Override public void glUniformMatrix2fv (int location, int count, boolean transpose, FloatBuffer value) { + gl.glUniformMatrix2fv(location, count, transpose, value); } - @Override - public void glUniformMatrix3fv(int location, int count, boolean transpose, - FloatBuffer value) - { - gl.glUniformMatrix3fv( location, count, transpose, value ); + @Override public void glUniformMatrix3fv (int location, int count, boolean transpose, FloatBuffer value) { + gl.glUniformMatrix3fv(location, count, transpose, value); } - @Override - public void glUniformMatrix4fv(int location, int count, boolean transpose, - FloatBuffer value) - { - gl.glUniformMatrix4fv( location, count, transpose, value ); + @Override public void glUniformMatrix4fv (int location, int count, boolean transpose, FloatBuffer value) { + gl.glUniformMatrix4fv(location, count, transpose, value); } - @Override - public void glUseProgram(int program) - { - gl.glUseProgram( program ); + @Override public void glUseProgram (int program) { + gl.glUseProgram(program); } - @Override - public void glValidateProgram(int program) - { - gl.glValidateProgram( program ); + @Override public void glValidateProgram (int program) { + gl.glValidateProgram(program); } - @Override - public void glVertexAttrib1f(int indx, float x) - { - gl.glVertexAttrib1f( indx, x ); + @Override public void glVertexAttrib1f (int indx, float x) { + gl.glVertexAttrib1f(indx, x); } - @Override - public void glVertexAttrib1fv(int indx, FloatBuffer values) - { - gl.glVertexAttrib1fv( indx, values ); + @Override public void glVertexAttrib1fv (int indx, FloatBuffer values) { + gl.glVertexAttrib1fv(indx, values); } - @Override - public void glVertexAttrib2f(int indx, float x, float y) - { - gl.glVertexAttrib2f( indx, x, y ); + @Override public void glVertexAttrib2f (int indx, float x, float y) { + gl.glVertexAttrib2f(indx, x, y); } - @Override - public void glVertexAttrib2fv(int indx, FloatBuffer values) - { - gl.glVertexAttrib2fv( indx, values ); + @Override public void glVertexAttrib2fv (int indx, FloatBuffer values) { + gl.glVertexAttrib2fv(indx, values); } - @Override - public void glVertexAttrib3f(int indx, float x, float y, float z) - { - gl.glVertexAttrib3f( indx, x, y, z ); + @Override public void glVertexAttrib3f (int indx, float x, float y, float z) { + gl.glVertexAttrib3f(indx, x, y, z); } - @Override - public void glVertexAttrib3fv(int indx, FloatBuffer values) - { - gl.glVertexAttrib3fv( indx, values ); + @Override public void glVertexAttrib3fv (int indx, FloatBuffer values) { + gl.glVertexAttrib3fv(indx, values); } - @Override - public void glVertexAttrib4f(int indx, float x, float y, float z, float w) - { - gl.glVertexAttrib4f( indx, x, y, z, w ); + @Override public void glVertexAttrib4f (int indx, float x, float y, float z, float w) { + gl.glVertexAttrib4f(indx, x, y, z, w); } - @Override - public void glVertexAttrib4fv(int indx, FloatBuffer values) - { - gl.glVertexAttrib4fv( indx, values ); + @Override public void glVertexAttrib4fv (int indx, FloatBuffer values) { + gl.glVertexAttrib4fv(indx, values); } - @Override - public void glVertexAttribPointer(int indx, int size, int type, - boolean normalized, int stride, Buffer ptr) - { - gl.glVertexAttribPointer( indx, size, type, normalized, stride, ptr ); + @Override public void glVertexAttribPointer (int indx, int size, int type, boolean normalized, int stride, Buffer ptr) { + gl.glVertexAttribPointer(indx, size, type, normalized, stride, ptr); } - @Override - public void glViewport(int x, int y, int width, int height) - { - gl.glViewport( x, y, width, height ); + @Override public void glViewport (int x, int y, int width, int height) { + gl.glViewport(x, y, width, height); } - @Override - public void glDrawElements(int mode, int count, int type, int indices) - { - gl.glDrawElements( mode, count, type, indices ); + @Override public void glDrawElements (int mode, int count, int type, int indices) { + gl.glDrawElements(mode, count, type, indices); } - @Override - public void glVertexAttribPointer(int indx, int size, int type, boolean normalized, int stride, int ptr) - { - gl.glVertexAttribPointer( indx, size, type, normalized, stride, ptr ); + @Override public void glVertexAttribPointer (int indx, int size, int type, boolean normalized, int stride, int ptr) { + gl.glVertexAttribPointer(indx, size, type, normalized, stride, ptr); } } diff --git a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglGraphics.java b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglGraphics.java index 20b91ee68..ab7327a4f 100644 --- a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglGraphics.java +++ b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglGraphics.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.desktop; import java.awt.BorderLayout; @@ -33,14 +31,14 @@ import com.badlogic.gdx.Graphics; import com.badlogic.gdx.RenderListener; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Font; +import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.GL11; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.GLCommon; import com.badlogic.gdx.graphics.Pixmap; -import com.badlogic.gdx.graphics.Texture; -import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.Pixmap.Format; +import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; import com.badlogic.gdx.math.WindowedMean; @@ -48,250 +46,198 @@ import com.badlogic.gdx.math.WindowedMean; /** * An implementation of the {@link Graphics} interface based on Jogl. * @author mzechner - * + * */ -public final class JoglGraphics implements Graphics, RenderListener -{ +public final class JoglGraphics implements Graphics, RenderListener { /** the jframe **/ private final JFrame frame; - - /** the graphic panel **/ + + /** the graphic panel **/ protected final JoglPanel graphicPanel; - + /** the render listener **/ - private RenderListener listener; - + private RenderListener listener; + /** Common instance **/ private GLCommon gl; - + /** GL10 instance **/ private GL10 gl10; - + /** GL11 instance **/ private GL11 gl11; - + /** GL20 instance **/ private GL20 gl20; - + /** wheter to use opengl 2 **/ private final boolean useGL2; - + /** the last frame time **/ private long lastFrameTime = System.nanoTime(); - + /** the deltaTime **/ private float deltaTime = 0; - + /** frame start time **/ private long frameStart = System.nanoTime(); - + /** frame counter **/ private int frames = 0; - + /** last fps **/ private int fps; - - + /** the deltaTime mean **/ - private WindowedMean mean = new WindowedMean( 5 ); - - JoglGraphics( final JoglApplication application, String title, int width, int height, boolean useGL2IfAvailable ) - { - frame = new JFrame( title ); - graphicPanel = new JoglPanel( application ); - graphicPanel.setPreferredSize( new Dimension( width, height ) ); - frame.setSize( width + frame.getInsets().left + frame.getInsets().right, frame.getInsets().top + frame.getInsets().bottom + height ); - frame.add(graphicPanel, BorderLayout.CENTER); - frame.pack(); - frame.setVisible( true ); - frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); - frame.setLocationRelativeTo(null); - frame.addWindowListener(new WindowAdapter() - { - public void windowClosing(WindowEvent e) - { - if( application.listener != null ) - application.listener.pause( ); - graphicPanel.dispose(); - if( application.listener != null ) - application.listener.destroy( ); - } - }); - useGL2 = useGL2IfAvailable; - graphicPanel.addGraphicListener( this ); - graphicPanel.requestFocusInWindow(); + private WindowedMean mean = new WindowedMean(5); + + JoglGraphics (final JoglApplication application, String title, int width, int height, boolean useGL2IfAvailable) { + frame = new JFrame(title); + graphicPanel = new JoglPanel(application); + graphicPanel.setPreferredSize(new Dimension(width, height)); + frame.setSize(width + frame.getInsets().left + frame.getInsets().right, frame.getInsets().top + frame.getInsets().bottom + + height); + frame.add(graphicPanel, BorderLayout.CENTER); + frame.pack(); + frame.setVisible(true); + frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + frame.setLocationRelativeTo(null); + frame.addWindowListener(new WindowAdapter() { + public void windowClosing (WindowEvent e) { + if (application.listener != null) application.listener.pause(); + graphicPanel.dispose(); + if (application.listener != null) application.listener.destroy(); + } + }); + useGL2 = useGL2IfAvailable; + graphicPanel.addGraphicListener(this); + graphicPanel.requestFocusInWindow(); } - @Override - public GL10 getGL10() - { + @Override public GL10 getGL10 () { return gl10; } - @Override - public GL11 getGL11() - { + @Override public GL11 getGL11 () { return gl11; } - @Override - public GL20 getGL20() - { + @Override public GL20 getGL20 () { return gl20; } - @Override - public int getHeight() - { + @Override public int getHeight () { return graphicPanel.getHeight(); } - @Override - public int getWidth() - { + @Override public int getWidth () { return graphicPanel.getWidth(); } - @Override - public boolean isGL11Available() - { + @Override public boolean isGL11Available () { return gl11 != null; } - @Override - public boolean isGL20Available() - { + @Override public boolean isGL20Available () { return gl20 != null; } - @Override - public Font newFont(String fontName, int size, FontStyle style) - { - return new JoglFont( fontName, size, style); + @Override public Font newFont (String fontName, int size, FontStyle style) { + return new JoglFont(fontName, size, style); } - @Override - public Font newFont(FileHandle file, int size, FontStyle style) - { + @Override public Font newFont (FileHandle file, int size, FontStyle style) { JoglFileHandle jHandle = (JoglFileHandle)file; InputStream in; try { - in = new FileInputStream( jHandle.getFile() ); - JoglFont font = new JoglFont(in, size, style); + in = new FileInputStream(jHandle.getFile()); + JoglFont font = new JoglFont(in, size, style); in.close(); - + return font; - } catch (Exception e) - { - throw new GdxRuntimeException( "Couldn't load font from file '" + file + "'", e ); - } + } catch (Exception e) { + throw new GdxRuntimeException("Couldn't load font from file '" + file + "'", e); + } } - @Override - public Pixmap newPixmap(int width, int height, Format format) - { - return new JoglPixmap( width, height, format ); + @Override public Pixmap newPixmap (int width, int height, Format format) { + return new JoglPixmap(width, height, format); } - @Override - public Pixmap newPixmap(InputStream in) - { - try - { - BufferedImage img = (BufferedImage)ImageIO.read( in ); - return new JoglPixmap( img ); + @Override public Pixmap newPixmap (InputStream in) { + try { + BufferedImage img = (BufferedImage)ImageIO.read(in); + return new JoglPixmap(img); + } catch (Exception ex) { + throw new GdxRuntimeException("Couldn't load Pixmap from InputStream", ex); } - catch( Exception ex ) - { - throw new GdxRuntimeException( "Couldn't load Pixmap from InputStream", ex ); - } } - - @Override - public Pixmap newPixmap(FileHandle file) - { - try - { - BufferedImage img = (BufferedImage)ImageIO.read( ((JoglFileHandle)file).getFile() ); - return new JoglPixmap( img ); + + @Override public Pixmap newPixmap (FileHandle file) { + try { + BufferedImage img = (BufferedImage)ImageIO.read(((JoglFileHandle)file).getFile()); + return new JoglPixmap(img); + } catch (Exception ex) { + throw new GdxRuntimeException("Couldn't load Pixmap from file '" + file + "'", ex); } - catch( Exception ex ) - { - throw new GdxRuntimeException( "Couldn't load Pixmap from file '" + file + "'", ex ); - } } - @Override - public Pixmap newPixmap(Object nativePixmap) - { - return new JoglPixmap( (BufferedImage)nativePixmap ); + @Override public Pixmap newPixmap (Object nativePixmap) { + return new JoglPixmap((BufferedImage)nativePixmap); } - private static boolean isPowerOfTwo( int value ) - { - return ((value!=0) && (value&(value-1))==0); + private static boolean isPowerOfTwo (int value) { + return ((value != 0) && (value & (value - 1)) == 0); } - - @Override - public Texture newUnmanagedTexture(int width, int height, Pixmap.Format format, TextureFilter minFilter, TextureFilter magFilter, TextureWrap uWrap, TextureWrap vWrap) - { - if( !isPowerOfTwo( width ) || !isPowerOfTwo( height ) ) - throw new GdxRuntimeException( "Texture dimensions must be a power of two" ); - - if( format == Format.Alpha ) - return new JoglTexture( width, height, BufferedImage.TYPE_BYTE_GRAY, minFilter, magFilter, uWrap, vWrap, false ); + + @Override public Texture newUnmanagedTexture (int width, int height, Pixmap.Format format, TextureFilter minFilter, + TextureFilter magFilter, TextureWrap uWrap, TextureWrap vWrap) { + if (!isPowerOfTwo(width) || !isPowerOfTwo(height)) + throw new GdxRuntimeException("Texture dimensions must be a power of two"); + + if (format == Format.Alpha) + return new JoglTexture(width, height, BufferedImage.TYPE_BYTE_GRAY, minFilter, magFilter, uWrap, vWrap, false); else - return new JoglTexture( width, height, BufferedImage.TYPE_4BYTE_ABGR, minFilter, magFilter, uWrap, vWrap, false ); + return new JoglTexture(width, height, BufferedImage.TYPE_4BYTE_ABGR, minFilter, magFilter, uWrap, vWrap, false); } - @Override - public Texture newUnmanagedTexture(Pixmap pixmap, TextureFilter minFilter, TextureFilter magFilter, TextureWrap uWrap, TextureWrap vWrap) - { - if( !isPowerOfTwo( pixmap.getHeight() ) || !isPowerOfTwo( pixmap.getWidth() ) ) - throw new GdxRuntimeException( "Texture dimensions must be a power of two" ); - - return new JoglTexture( (BufferedImage)pixmap.getNativePixmap(), minFilter, magFilter, uWrap, vWrap, false ); + @Override public Texture newUnmanagedTexture (Pixmap pixmap, TextureFilter minFilter, TextureFilter magFilter, + TextureWrap uWrap, TextureWrap vWrap) { + if (!isPowerOfTwo(pixmap.getHeight()) || !isPowerOfTwo(pixmap.getWidth())) + throw new GdxRuntimeException("Texture dimensions must be a power of two"); + + return new JoglTexture((BufferedImage)pixmap.getNativePixmap(), minFilter, magFilter, uWrap, vWrap, false); } - @Override - public Texture newTexture(FileHandle file, TextureFilter minFilter, - TextureFilter magFilter, TextureWrap uWrap, TextureWrap vWrap) - { - Pixmap pixmap = newPixmap( file ); - if( !isPowerOfTwo( pixmap.getHeight() ) || !isPowerOfTwo( pixmap.getWidth() ) ) - throw new GdxRuntimeException( "Texture dimensions must be a power of two" ); - - return new JoglTexture( (BufferedImage)pixmap.getNativePixmap(), minFilter, magFilter, uWrap, vWrap, false ); + @Override public Texture newTexture (FileHandle file, TextureFilter minFilter, TextureFilter magFilter, TextureWrap uWrap, + TextureWrap vWrap) { + Pixmap pixmap = newPixmap(file); + if (!isPowerOfTwo(pixmap.getHeight()) || !isPowerOfTwo(pixmap.getWidth())) + throw new GdxRuntimeException("Texture dimensions must be a power of two"); + + return new JoglTexture((BufferedImage)pixmap.getNativePixmap(), minFilter, magFilter, uWrap, vWrap, false); } - + /** * {@inheritDoc} */ - @Override - public void setRenderListener( RenderListener listener) - { - if( this.listener != null ) - graphicPanel.removeGraphicListener( this.listener ); + @Override public void setRenderListener (RenderListener listener) { + if (this.listener != null) graphicPanel.removeGraphicListener(this.listener); graphicPanel.addGraphicListener(listener); this.listener = listener; } - @Override - public void dispose() - { - + @Override public void dispose () { + } - @Override - public void render() - { + @Override public void render () { // calculate delta time - deltaTime = ( System.nanoTime() - lastFrameTime ) / 1000000000.0f; + deltaTime = (System.nanoTime() - lastFrameTime) / 1000000000.0f; lastFrameTime = System.nanoTime(); - mean.addValue( deltaTime ); - - if( System.nanoTime() - frameStart > 1000000000 ) - { + mean.addValue(deltaTime); + + if (System.nanoTime() - frameStart > 1000000000) { fps = frames; frames = 0; frameStart = System.nanoTime(); @@ -299,33 +245,25 @@ public final class JoglGraphics implements Graphics, RenderListener frames++; } - @Override - public void surfaceCreated() - { - String version = graphicPanel.getGL().glGetString( GL.GL_VERSION ); + @Override public void surfaceCreated () { + String version = graphicPanel.getGL().glGetString(GL.GL_VERSION); int major = Integer.parseInt("" + version.charAt(0)); int minor = Integer.parseInt("" + version.charAt(2)); - - if( useGL2 && major >= 2 ) - { + + if (useGL2 && major >= 2) { // FIXME add check wheter gl 2.0 is supported - gl20 = new JoglGL20( graphicPanel.getGL() ); + gl20 = new JoglGL20(graphicPanel.getGL()); gl = gl20; - } - else - { - if( major == 1 && minor < 5 ) - { - gl10 = new JoglGL10( graphicPanel.getGL() ); - } - else - { - gl11 = new JoglGL11( graphicPanel.getGL() ); + } else { + if (major == 1 && minor < 5) { + gl10 = new JoglGL10(graphicPanel.getGL()); + } else { + gl11 = new JoglGL11(graphicPanel.getGL()); gl10 = gl11; } gl = gl10; } - + Gdx.gl = gl; Gdx.gl10 = gl10; Gdx.gl11 = gl11; @@ -335,38 +273,30 @@ public final class JoglGraphics implements Graphics, RenderListener /** * {@inheritDoc} */ - @Override - public float getDeltaTime() - { - return mean.getMean() == 0?deltaTime:mean.getMean(); + @Override public float getDeltaTime () { + return mean.getMean() == 0 ? deltaTime : mean.getMean(); } - @Override - public void surfaceChanged( int width, int height) { + @Override public void surfaceChanged (int width, int height) { // TODO Auto-generated method stub - + } /** * {@inheritDoc} */ - @Override - public GraphicsType getType() - { + @Override public GraphicsType getType () { return GraphicsType.JoglGL; } /** * {@inheritDoc} */ - @Override - public int getFramesPerSecond() - { + @Override public int getFramesPerSecond () { return fps; } - @Override - public GLCommon getGLCommon() { + @Override public GLCommon getGLCommon () { return gl; } } diff --git a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglInput.java b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglInput.java index acea79501..687ae8a2a 100644 --- a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglInput.java +++ b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglInput.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.desktop; import java.awt.event.MouseEvent; @@ -28,164 +26,123 @@ import com.badlogic.gdx.RenderListener; * An implementation of the {@link Input} interface hooking a Jogl panel for input. * * @author mzechner - * + * */ -final class JoglInput implements Input, RenderListener -{ +final class JoglInput implements Input, RenderListener { /** the multiplexer **/ private final JoglInputMultiplexer multiplexer; - + /** the graphics panel **/ private final JoglPanel panel; - + /** user input **/ private String text; - + /** user input listener **/ private TextInputListener textListener; - - JoglInput( JoglPanel panel ) - { + + JoglInput (JoglPanel panel) { multiplexer = new JoglInputMultiplexer(panel.getCanvas()); this.panel = panel; - this.panel.addGraphicListener( this ); + this.panel.addGraphicListener(this); } - - @Override - public void addInputListener(InputListener listener) - { - multiplexer.addListener( listener ); + + @Override public void addInputListener (InputListener listener) { + multiplexer.addListener(listener); } - @Override - public float getAccelerometerX() - { + @Override public float getAccelerometerX () { return 0; } - @Override - public float getAccelerometerY() - { + @Override public float getAccelerometerY () { return 0; } - @Override - public float getAccelerometerZ() - { + @Override public float getAccelerometerZ () { return 0; } - @Override - public void getTextInput(final TextInputListener listener, final String title, final String text) - { - SwingUtilities.invokeLater( new Runnable() { - @Override - public void run() { - JoglInput.this.text = JOptionPane.showInputDialog(null, title, text ); - if( JoglInput.this.text != null ) - textListener = listener; + @Override public void getTextInput (final TextInputListener listener, final String title, final String text) { + SwingUtilities.invokeLater(new Runnable() { + @Override public void run () { + JoglInput.this.text = JOptionPane.showInputDialog(null, title, text); + if (JoglInput.this.text != null) textListener = listener; } }); } - @Override - public int getX() - { + @Override public int getX () { return panel.getMouseX(); } - @Override - public int getY() - { + @Override public int getY () { return panel.getMouseY(); } - @Override - public boolean isAccelerometerAvailable() - { + @Override public boolean isAccelerometerAvailable () { return false; } - @Override - public boolean isKeyPressed(int key) - { - return panel.isKeyDown( key ); + @Override public boolean isKeyPressed (int key) { + return panel.isKeyDown(key); } - @Override - public boolean isTouched() - { - return panel.isButtonDown(MouseEvent.BUTTON1) || - panel.isButtonDown(MouseEvent.BUTTON2) || - panel.isButtonDown(MouseEvent.BUTTON3); + @Override public boolean isTouched () { + return panel.isButtonDown(MouseEvent.BUTTON1) || panel.isButtonDown(MouseEvent.BUTTON2) + || panel.isButtonDown(MouseEvent.BUTTON3); } - @Override - public void removeInputListener(InputListener listener) - { - multiplexer.removeListener( listener ); + @Override public void removeInputListener (InputListener listener) { + multiplexer.removeListener(listener); } - @Override - public void dispose() { + @Override public void dispose () { // TODO Auto-generated method stub - + } - @Override - public void render() - { + @Override public void render () { multiplexer.processEvents(); - - if( textListener != null ) - { - textListener.input( text ); + + if (textListener != null) { + textListener.input(text); textListener = null; } } - @Override - public void surfaceCreated() { + @Override public void surfaceCreated () { // TODO Auto-generated method stub - + } - @Override - public void surfaceChanged(int width, int height) { + @Override public void surfaceChanged (int width, int height) { // TODO Auto-generated method stub - + } - @Override - public int getX(int pointer) - { - if( pointer > 0 ) + @Override public int getX (int pointer) { + if (pointer > 0) return 0; else return getX(); } - @Override - public int getY(int pointer) - { - if( pointer > 0 ) + @Override public int getY (int pointer) { + if (pointer > 0) return 0; else return getY(); } - @Override - public boolean isTouched(int pointer) - { - if( pointer > 0 ) + @Override public boolean isTouched (int pointer) { + if (pointer > 0) return false; else - return isTouched(); + return isTouched(); } - @Override - public boolean supportsMultitouch() - { + @Override public boolean supportsMultitouch () { return false; } } diff --git a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglInputMultiplexer.java b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglInputMultiplexer.java index 4772c9546..f45f174c3 100644 --- a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglInputMultiplexer.java +++ b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglInputMultiplexer.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.desktop; import java.awt.Component; @@ -29,372 +27,257 @@ import java.util.HashMap; import com.badlogic.gdx.Input; import com.badlogic.gdx.InputListener; - - /** - * Hooks a swing component and multiplexes any input - * events to all registered listeners in order. a listener - * can signal wheter he has consumed the event therefor - * ending the multiplexing. + * Hooks a swing component and multiplexes any input events to all registered listeners in order. a listener can signal wheter he + * has consumed the event therefor ending the multiplexing. * * @author badlogicgames@gmail.com - * + * */ -final class JoglInputMultiplexer implements MouseListener, MouseMotionListener, MouseWheelListener, KeyListener -{ - private enum EventType - { - MouseDown, - MouseUp, - MouseMoved, - MouseDragged, - KeyDown, - KeyUp, - KeyTyped +final class JoglInputMultiplexer implements MouseListener, MouseMotionListener, MouseWheelListener, KeyListener { + private enum EventType { + MouseDown, MouseUp, MouseMoved, MouseDragged, KeyDown, KeyUp, KeyTyped } - - private class Event - { - public int x, y; + + private class Event { + public int x, y; public int keycode; public char keychar; public EventType type; - - public void set( EventType type, int x, int y, int keycode, char keychar ) - { + + public void set (EventType type, int x, int y, int keycode, char keychar) { this.type = type; this.x = x; - this.y = y; + this.y = y; this.keycode = keycode; this.keychar = keychar; } - } - - private final ArrayList eventQueue = new ArrayList( ); - private final ArrayList freeEvents = new ArrayList( ); + } + + private final ArrayList eventQueue = new ArrayList(); + private final ArrayList freeEvents = new ArrayList(); private int freeEventIndex = 0; - - private final ArrayList listeners = new ArrayList( ); - private final HashMap disabled = new HashMap( ); + + private final ArrayList listeners = new ArrayList(); + private final HashMap disabled = new HashMap(); private Component component; - + /** * constructor, hooks the given component * @param component the component to hook */ - JoglInputMultiplexer( Component component ) - { - hook( component ); - for( int i = 0; i < 1000; i++ ) - freeEvents.add( new Event() ); + JoglInputMultiplexer (Component component) { + hook(component); + for (int i = 0; i < 1000; i++) + freeEvents.add(new Event()); } /** - * adds callback hooks to the component. unhooks from - * the old component if any was set. + * adds callback hooks to the component. unhooks from the old component if any was set. * * @param component the component to hook */ - public void hook( Component component ) - { - unhook( ); - component.addMouseListener( this ); - component.addMouseMotionListener( this ); - component.addMouseWheelListener( this ); - component.addKeyListener( this ); + public void hook (Component component) { + unhook(); + component.addMouseListener(this); + component.addMouseMotionListener(this); + component.addMouseWheelListener(this); + component.addKeyListener(this); this.component = component; } - + /** * removes the callback hooks from the swing component */ - public void unhook( ) - { - if( component != null ) - { - component.removeMouseListener( this ); - component.removeMouseMotionListener( this ); - component.removeMouseWheelListener( this ); - component.removeKeyListener( this ); + public void unhook () { + if (component != null) { + component.removeMouseListener(this); + component.removeMouseMotionListener(this); + component.removeMouseWheelListener(this); + component.removeKeyListener(this); } } - - public void disableListener( InputListener listener ) - { + + public void disableListener (InputListener listener) { disabled.put(listener, true); } - - public void enableListener( InputListener listener ) - { - disabled.put(listener, false ); + + public void enableListener (InputListener listener) { + disabled.put(listener, false); } - - public void processEvents( ) - { - synchronized( eventQueue ) - { - for( int i = 0; i < eventQueue.size(); i++ ) - { + + public void processEvents () { + synchronized (eventQueue) { + for (int i = 0; i < eventQueue.size(); i++) { Event event = eventQueue.get(i); - if( event.type == EventType.MouseDown ) - for( int j = 0; j < listeners.size(); j++ ) - if( listeners.get(j).touchDown(event.x, event.y, 0 ) ) - break; - if( event.type == EventType.MouseUp ) - for( int j = 0; j < listeners.size(); j++ ) - if( listeners.get(j).touchUp(event.x, event.y, 0 ) ) - break; - if( event.type == EventType.MouseDragged ) - for( int j = 0; j < listeners.size(); j++ ) - if( listeners.get(j).touchDragged(event.x, event.y, 0 ) ) - break; - if( event.type == EventType.KeyDown ) - for( int j = 0; j < listeners.size(); j++ ) - if( listeners.get(j).keyDown(event.keycode) ) - break; - if( event.type == EventType.KeyUp ) - for( int j = 0; j < listeners.size(); j++ ) - if( listeners.get(j).keyUp(event.keycode) ) - break; - if( event.type == EventType.KeyTyped ) - for( int j = 0; j < listeners.size(); j++ ) - if( listeners.get(j).keyTyped(event.keychar) ) - break; + if (event.type == EventType.MouseDown) for (int j = 0; j < listeners.size(); j++) + if (listeners.get(j).touchDown(event.x, event.y, 0)) break; + if (event.type == EventType.MouseUp) for (int j = 0; j < listeners.size(); j++) + if (listeners.get(j).touchUp(event.x, event.y, 0)) break; + if (event.type == EventType.MouseDragged) for (int j = 0; j < listeners.size(); j++) + if (listeners.get(j).touchDragged(event.x, event.y, 0)) break; + if (event.type == EventType.KeyDown) for (int j = 0; j < listeners.size(); j++) + if (listeners.get(j).keyDown(event.keycode)) break; + if (event.type == EventType.KeyUp) for (int j = 0; j < listeners.size(); j++) + if (listeners.get(j).keyUp(event.keycode)) break; + if (event.type == EventType.KeyTyped) for (int j = 0; j < listeners.size(); j++) + if (listeners.get(j).keyTyped(event.keychar)) break; } eventQueue.clear(); freeEventIndex = 0; } } - + /** - * adds an {@link InputListener} to this multiplexer. - * The order in which listeners are added is the - * order in which they are asked to consume events. + * adds an {@link InputListener} to this multiplexer. The order in which listeners are added is the order in which they are + * asked to consume events. * * @param listener the listener to add */ - public void addListener( InputListener listener ) - { - synchronized( eventQueue ) - { - if( !listeners.contains( listener ) ) - { - listeners.add( listener ); + public void addListener (InputListener listener) { + synchronized (eventQueue) { + if (!listeners.contains(listener)) { + listeners.add(listener); disabled.put(listener, false); } } } - - public void removeListener( InputListener listener ) - { - synchronized( eventQueue ) - { - listeners.remove( listener ); + + public void removeListener (InputListener listener) { + synchronized (eventQueue) { + listeners.remove(listener); disabled.remove(listener); } } - - public void mouseClicked(MouseEvent e) - { - - } - - public void mousePressed(MouseEvent e) - { - synchronized( eventQueue ) - { - Event event = freeEvents.get( freeEventIndex++ ); - event.set(EventType.MouseDown, e.getX(), e.getY(), 0, '\0' ); + + public void mouseClicked (MouseEvent e) { + + } + + public void mousePressed (MouseEvent e) { + synchronized (eventQueue) { + Event event = freeEvents.get(freeEventIndex++); + event.set(EventType.MouseDown, e.getX(), e.getY(), 0, '\0'); eventQueue.add(event); } } - public void mouseReleased(MouseEvent e) - { - synchronized( eventQueue ) - { - Event event = freeEvents.get( freeEventIndex++ ); - event.set(EventType.MouseUp, e.getX(), e.getY(), 0, '\0' ); + public void mouseReleased (MouseEvent e) { + synchronized (eventQueue) { + Event event = freeEvents.get(freeEventIndex++); + event.set(EventType.MouseUp, e.getX(), e.getY(), 0, '\0'); eventQueue.add(event); } - + } - public void mouseDragged(MouseEvent e) - { - synchronized( eventQueue ) - { - Event event = freeEvents.get( freeEventIndex++ ); - event.set(EventType.MouseDragged, e.getX(), e.getY(), 0, '\0' ); + public void mouseDragged (MouseEvent e) { + synchronized (eventQueue) { + Event event = freeEvents.get(freeEventIndex++); + event.set(EventType.MouseDragged, e.getX(), e.getY(), 0, '\0'); eventQueue.add(event); } } - public void mouseMoved(MouseEvent e) - { + public void mouseMoved (MouseEvent e) { } - public void keyPressed(KeyEvent e) - { - synchronized( eventQueue ) - { - Event event = freeEvents.get( freeEventIndex++ ); - event.set(EventType.KeyDown, 0, 0, translateKeyCode(e.getKeyCode()), '\0' ); + public void keyPressed (KeyEvent e) { + synchronized (eventQueue) { + Event event = freeEvents.get(freeEventIndex++); + event.set(EventType.KeyDown, 0, 0, translateKeyCode(e.getKeyCode()), '\0'); eventQueue.add(event); } } - public void keyReleased(KeyEvent e) - { - synchronized( eventQueue ) - { - Event event = freeEvents.get( freeEventIndex++ ); - event.set(EventType.KeyUp, 0, 0, translateKeyCode(e.getKeyCode()), '\0' ); + public void keyReleased (KeyEvent e) { + synchronized (eventQueue) { + Event event = freeEvents.get(freeEventIndex++); + event.set(EventType.KeyUp, 0, 0, translateKeyCode(e.getKeyCode()), '\0'); eventQueue.add(event); } } - public void keyTyped(KeyEvent e) - { - synchronized( eventQueue ) - { - Event event = freeEvents.get( freeEventIndex++ ); - event.set(EventType.KeyTyped, 0, 0, translateKeyCode(e.getKeyCode()), e.getKeyChar() ); + public void keyTyped (KeyEvent e) { + synchronized (eventQueue) { + Event event = freeEvents.get(freeEventIndex++); + event.set(EventType.KeyTyped, 0, 0, translateKeyCode(e.getKeyCode()), e.getKeyChar()); eventQueue.add(event); } } - @Override - public void mouseEntered(MouseEvent e) { + @Override public void mouseEntered (MouseEvent e) { // TODO Auto-generated method stub - + } - @Override - public void mouseExited(MouseEvent e) { + @Override public void mouseExited (MouseEvent e) { // TODO Auto-generated method stub - + } - @Override - public void mouseWheelMoved(MouseWheelEvent arg0) { + @Override public void mouseWheelMoved (MouseWheelEvent arg0) { // TODO Auto-generated method stub - + } - - protected static int translateKeyCode( int keyCode ) - { - if( keyCode == KeyEvent.VK_0 ) - return Input.Keys.KEYCODE_0; - if( keyCode == KeyEvent.VK_1 ) - return Input.Keys.KEYCODE_1; - if( keyCode == KeyEvent.VK_2 ) - return Input.Keys.KEYCODE_2; - if( keyCode == KeyEvent.VK_3 ) - return Input.Keys.KEYCODE_3; - if( keyCode == KeyEvent.VK_4 ) - return Input.Keys.KEYCODE_4; - if( keyCode == KeyEvent.VK_5 ) - return Input.Keys.KEYCODE_5; - if( keyCode == KeyEvent.VK_6 ) - return Input.Keys.KEYCODE_6; - if( keyCode == KeyEvent.VK_7 ) - return Input.Keys.KEYCODE_7; - if( keyCode == KeyEvent.VK_8 ) - return Input.Keys.KEYCODE_8; - if( keyCode == KeyEvent.VK_9 ) - return Input.Keys.KEYCODE_9; - if( keyCode == KeyEvent.VK_A ) - return Input.Keys.KEYCODE_A; - if( keyCode == KeyEvent.VK_B ) - return Input.Keys.KEYCODE_B; - if( keyCode == KeyEvent.VK_C ) - return Input.Keys.KEYCODE_C; - if( keyCode == KeyEvent.VK_D ) - return Input.Keys.KEYCODE_D; - if( keyCode == KeyEvent.VK_E ) - return Input.Keys.KEYCODE_E; - if( keyCode == KeyEvent.VK_F ) - return Input.Keys.KEYCODE_F; - if( keyCode == KeyEvent.VK_G ) - return Input.Keys.KEYCODE_G; - if( keyCode == KeyEvent.VK_H ) - return Input.Keys.KEYCODE_H; - if( keyCode == KeyEvent.VK_I ) - return Input.Keys.KEYCODE_I; - if( keyCode == KeyEvent.VK_J ) - return Input.Keys.KEYCODE_J; - if( keyCode == KeyEvent.VK_K ) - return Input.Keys.KEYCODE_K; - if( keyCode == KeyEvent.VK_L ) - return Input.Keys.KEYCODE_L; - if( keyCode == KeyEvent.VK_M ) - return Input.Keys.KEYCODE_M; - if( keyCode == KeyEvent.VK_N ) - return Input.Keys.KEYCODE_N; - if( keyCode == KeyEvent.VK_O ) - return Input.Keys.KEYCODE_O; - if( keyCode == KeyEvent.VK_P ) - return Input.Keys.KEYCODE_P; - if( keyCode == KeyEvent.VK_Q ) - return Input.Keys.KEYCODE_Q; - if( keyCode == KeyEvent.VK_R ) - return Input.Keys.KEYCODE_R; - if( keyCode == KeyEvent.VK_S ) - return Input.Keys.KEYCODE_S; - if( keyCode == KeyEvent.VK_T ) - return Input.Keys.KEYCODE_T; - if( keyCode == KeyEvent.VK_U ) - return Input.Keys.KEYCODE_U; - if( keyCode == KeyEvent.VK_V ) - return Input.Keys.KEYCODE_V; - if( keyCode == KeyEvent.VK_W ) - return Input.Keys.KEYCODE_W; - if( keyCode == KeyEvent.VK_X ) - return Input.Keys.KEYCODE_X; - if( keyCode == KeyEvent.VK_Y ) - return Input.Keys.KEYCODE_Y; - if( keyCode == KeyEvent.VK_Z ) - return Input.Keys.KEYCODE_Z; - if( keyCode == KeyEvent.VK_ALT ) - return Input.Keys.KEYCODE_ALT_LEFT; - if( keyCode == KeyEvent.VK_ALT_GRAPH ) - return Input.Keys.KEYCODE_ALT_RIGHT; - if( keyCode == KeyEvent.VK_BACK_SLASH ) - return Input.Keys.KEYCODE_BACKSLASH; - if( keyCode == KeyEvent.VK_COMMA ) - return Input.Keys.KEYCODE_COMMA; - if( keyCode == KeyEvent.VK_DELETE ) - return Input.Keys.KEYCODE_DEL; - if( keyCode == KeyEvent.VK_LEFT ) - return Input.Keys.KEYCODE_DPAD_LEFT; - if( keyCode == KeyEvent.VK_RIGHT ) - return Input.Keys.KEYCODE_DPAD_RIGHT; - if( keyCode == KeyEvent.VK_UP ) - return Input.Keys.KEYCODE_DPAD_UP; - if( keyCode == KeyEvent.VK_DOWN ) - return Input.Keys.KEYCODE_DPAD_DOWN; - if( keyCode == KeyEvent.VK_ENTER ) - return Input.Keys.KEYCODE_ENTER; - if( keyCode == KeyEvent.VK_HOME ) - return Input.Keys.KEYCODE_HOME; - if( keyCode == KeyEvent.VK_MINUS ) - return Input.Keys.KEYCODE_MINUS; - if( keyCode == KeyEvent.VK_PERIOD ) - return Input.Keys.KEYCODE_PERIOD; - if( keyCode == KeyEvent.VK_PLUS ) - return Input.Keys.KEYCODE_PLUS; - if( keyCode == KeyEvent.VK_SEMICOLON ) - return Input.Keys.KEYCODE_SEMICOLON; - if( keyCode == KeyEvent.VK_SHIFT ) - return Input.Keys.KEYCODE_SHIFT_LEFT; - if( keyCode == KeyEvent.VK_SLASH ) - return Input.Keys.KEYCODE_SLASH; - if( keyCode == KeyEvent.VK_SPACE ) - return Input.Keys.KEYCODE_SPACE; - if( keyCode == KeyEvent.VK_TAB ) - return Input.Keys.KEYCODE_TAB; - + + protected static int translateKeyCode (int keyCode) { + if (keyCode == KeyEvent.VK_0) return Input.Keys.KEYCODE_0; + if (keyCode == KeyEvent.VK_1) return Input.Keys.KEYCODE_1; + if (keyCode == KeyEvent.VK_2) return Input.Keys.KEYCODE_2; + if (keyCode == KeyEvent.VK_3) return Input.Keys.KEYCODE_3; + if (keyCode == KeyEvent.VK_4) return Input.Keys.KEYCODE_4; + if (keyCode == KeyEvent.VK_5) return Input.Keys.KEYCODE_5; + if (keyCode == KeyEvent.VK_6) return Input.Keys.KEYCODE_6; + if (keyCode == KeyEvent.VK_7) return Input.Keys.KEYCODE_7; + if (keyCode == KeyEvent.VK_8) return Input.Keys.KEYCODE_8; + if (keyCode == KeyEvent.VK_9) return Input.Keys.KEYCODE_9; + if (keyCode == KeyEvent.VK_A) return Input.Keys.KEYCODE_A; + if (keyCode == KeyEvent.VK_B) return Input.Keys.KEYCODE_B; + if (keyCode == KeyEvent.VK_C) return Input.Keys.KEYCODE_C; + if (keyCode == KeyEvent.VK_D) return Input.Keys.KEYCODE_D; + if (keyCode == KeyEvent.VK_E) return Input.Keys.KEYCODE_E; + if (keyCode == KeyEvent.VK_F) return Input.Keys.KEYCODE_F; + if (keyCode == KeyEvent.VK_G) return Input.Keys.KEYCODE_G; + if (keyCode == KeyEvent.VK_H) return Input.Keys.KEYCODE_H; + if (keyCode == KeyEvent.VK_I) return Input.Keys.KEYCODE_I; + if (keyCode == KeyEvent.VK_J) return Input.Keys.KEYCODE_J; + if (keyCode == KeyEvent.VK_K) return Input.Keys.KEYCODE_K; + if (keyCode == KeyEvent.VK_L) return Input.Keys.KEYCODE_L; + if (keyCode == KeyEvent.VK_M) return Input.Keys.KEYCODE_M; + if (keyCode == KeyEvent.VK_N) return Input.Keys.KEYCODE_N; + if (keyCode == KeyEvent.VK_O) return Input.Keys.KEYCODE_O; + if (keyCode == KeyEvent.VK_P) return Input.Keys.KEYCODE_P; + if (keyCode == KeyEvent.VK_Q) return Input.Keys.KEYCODE_Q; + if (keyCode == KeyEvent.VK_R) return Input.Keys.KEYCODE_R; + if (keyCode == KeyEvent.VK_S) return Input.Keys.KEYCODE_S; + if (keyCode == KeyEvent.VK_T) return Input.Keys.KEYCODE_T; + if (keyCode == KeyEvent.VK_U) return Input.Keys.KEYCODE_U; + if (keyCode == KeyEvent.VK_V) return Input.Keys.KEYCODE_V; + if (keyCode == KeyEvent.VK_W) return Input.Keys.KEYCODE_W; + if (keyCode == KeyEvent.VK_X) return Input.Keys.KEYCODE_X; + if (keyCode == KeyEvent.VK_Y) return Input.Keys.KEYCODE_Y; + if (keyCode == KeyEvent.VK_Z) return Input.Keys.KEYCODE_Z; + if (keyCode == KeyEvent.VK_ALT) return Input.Keys.KEYCODE_ALT_LEFT; + if (keyCode == KeyEvent.VK_ALT_GRAPH) return Input.Keys.KEYCODE_ALT_RIGHT; + if (keyCode == KeyEvent.VK_BACK_SLASH) return Input.Keys.KEYCODE_BACKSLASH; + if (keyCode == KeyEvent.VK_COMMA) return Input.Keys.KEYCODE_COMMA; + if (keyCode == KeyEvent.VK_DELETE) return Input.Keys.KEYCODE_DEL; + if (keyCode == KeyEvent.VK_LEFT) return Input.Keys.KEYCODE_DPAD_LEFT; + if (keyCode == KeyEvent.VK_RIGHT) return Input.Keys.KEYCODE_DPAD_RIGHT; + if (keyCode == KeyEvent.VK_UP) return Input.Keys.KEYCODE_DPAD_UP; + if (keyCode == KeyEvent.VK_DOWN) return Input.Keys.KEYCODE_DPAD_DOWN; + if (keyCode == KeyEvent.VK_ENTER) return Input.Keys.KEYCODE_ENTER; + if (keyCode == KeyEvent.VK_HOME) return Input.Keys.KEYCODE_HOME; + if (keyCode == KeyEvent.VK_MINUS) return Input.Keys.KEYCODE_MINUS; + if (keyCode == KeyEvent.VK_PERIOD) return Input.Keys.KEYCODE_PERIOD; + if (keyCode == KeyEvent.VK_PLUS) return Input.Keys.KEYCODE_PLUS; + if (keyCode == KeyEvent.VK_SEMICOLON) return Input.Keys.KEYCODE_SEMICOLON; + if (keyCode == KeyEvent.VK_SHIFT) return Input.Keys.KEYCODE_SHIFT_LEFT; + if (keyCode == KeyEvent.VK_SLASH) return Input.Keys.KEYCODE_SLASH; + if (keyCode == KeyEvent.VK_SPACE) return Input.Keys.KEYCODE_SPACE; + if (keyCode == KeyEvent.VK_TAB) return Input.Keys.KEYCODE_TAB; + return Input.Keys.KEYCODE_UNKNOWN; } } diff --git a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglMusic.java b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglMusic.java index 2bc197350..e995db152 100644 --- a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglMusic.java +++ b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglMusic.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.desktop; import java.io.File; @@ -28,15 +26,11 @@ import javax.sound.sampled.UnsupportedAudioFileException; import com.badlogic.gdx.audio.Music; -public class JoglMusic implements Music, Runnable -{ - private enum State - { - Playing, - Stopped, - Paused +public class JoglMusic implements Music, Runnable { + private enum State { + Playing, Stopped, Paused } - + private State state = State.Stopped; private final Thread thread; private final File file; @@ -45,182 +39,131 @@ public class JoglMusic implements Music, Runnable private final byte[] buffer; private boolean looping = false; private boolean disposed = false; - - public JoglMusic( JoglFileHandle handle ) throws UnsupportedAudioFileException, IOException, LineUnavailableException - { + + public JoglMusic (JoglFileHandle handle) throws UnsupportedAudioFileException, IOException, LineUnavailableException { this.file = handle.getFile(); - - openAudioInputStream(); - AudioFormat audioFormat = ain.getFormat(); - line = AudioSystem.getSourceDataLine( audioFormat ); - line.open(audioFormat); //FIXME reduce latency, gotta reimplement the playback thread. + + openAudioInputStream(); + AudioFormat audioFormat = ain.getFormat(); + line = AudioSystem.getSourceDataLine(audioFormat); + line.open(audioFormat); // FIXME reduce latency, gotta reimplement the playback thread. line.start(); - buffer = new byte[10000*ain.getFormat().getFrameSize()]; + buffer = new byte[10000 * ain.getFormat().getFrameSize()]; ain.close(); ain = null; - - - thread = new Thread( this ); + + thread = new Thread(this); thread.setDaemon(true); thread.start(); } - - private void openAudioInputStream( ) throws UnsupportedAudioFileException, IOException - { - ain = AudioSystem.getAudioInputStream(file); + + private void openAudioInputStream () throws UnsupportedAudioFileException, IOException { + ain = AudioSystem.getAudioInputStream(file); AudioFormat baseFormat = ain.getFormat(); - AudioFormat decodedFormat = new AudioFormat( - AudioFormat.Encoding.PCM_SIGNED, - baseFormat.getSampleRate(), - 16, - baseFormat.getChannels(), - baseFormat.getChannels() * 2, - baseFormat.getSampleRate(), - false); - - ain = AudioSystem.getAudioInputStream(decodedFormat, ain); + AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, + baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false); + + ain = AudioSystem.getAudioInputStream(decodedFormat, ain); } - - @Override - public void dispose() - { + + @Override public void dispose () { disposed = true; try { thread.join(); line.close(); ain.close(); - } catch (Exception e) - { + } catch (Exception e) { // nothing we can do here - } + } } - @Override - public boolean isLooping() - { + @Override public boolean isLooping () { return looping; } - @Override - public boolean isPlaying() - { + @Override public boolean isPlaying () { return state == State.Playing; } - @Override - public void pause() - { - synchronized( this ) - { - if( state == State.Playing ) - state = State.Paused; + @Override public void pause () { + synchronized (this) { + if (state == State.Playing) state = State.Paused; } } - @Override - public void play() - { - synchronized( this ) - { - if( state == State.Playing ) - return; - - if( state == State.Paused ) - { + @Override public void play () { + synchronized (this) { + if (state == State.Playing) return; + + if (state == State.Paused) { state = State.Playing; return; } - - try - { + + try { openAudioInputStream(); state = State.Playing; - } - catch (Exception e) - { + } catch (Exception e) { state = State.Stopped; - } + } } } - @Override - public void stop() - { - synchronized( this ) - { - if( state == State.Stopped ) - return; - + @Override public void stop () { + synchronized (this) { + if (state == State.Stopped) return; + state = State.Stopped; line.flush(); try { ain.close(); - } catch (IOException e) - { + } catch (IOException e) { e.printStackTrace(); } ain = null; } } - - @Override - public void setLooping(boolean isLooping) - { + + @Override public void setLooping (boolean isLooping) { looping = isLooping; } - @Override - public void setVolume(float volume) - { - try - { - volume = Math.min( 1, volume ); - volume = Math.max( 0, volume ); + @Override public void setVolume (float volume) { + try { + volume = Math.min(1, volume); + volume = Math.max(0, volume); FloatControl control = (FloatControl)line.getControl(FloatControl.Type.MASTER_GAIN); - control.setValue( -80 + volume * 80 ); - } - catch( IllegalArgumentException ex ) - { + control.setValue(-80 + volume * 80); + } catch (IllegalArgumentException ex) { ex.printStackTrace(); } } - @Override - public void run() - { - int readBytes = 0; + @Override public void run () { + int readBytes = 0; long readSamples = 0; - - while( !disposed ) - { - synchronized( this ) - { - if( state == State.Playing ) - { - try - { - - readBytes = ain.read( buffer ); - - if( readBytes != -1 ) - { - int writtenBytes = line.write( buffer, 0, readBytes ); - while( writtenBytes != readBytes ) - writtenBytes += line.write( buffer, writtenBytes, readBytes - writtenBytes ); + + while (!disposed) { + synchronized (this) { + if (state == State.Playing) { + try { + + readBytes = ain.read(buffer); + + if (readBytes != -1) { + int writtenBytes = line.write(buffer, 0, readBytes); + while (writtenBytes != readBytes) + writtenBytes += line.write(buffer, writtenBytes, readBytes - writtenBytes); readSamples += readBytes / ain.getFormat().getFrameSize(); - } - else - { - System.out.println( "samples: " + readSamples ); + } else { + System.out.println("samples: " + readSamples); ain.close(); - if( !isLooping() ) + if (!isLooping()) state = State.Stopped; - else - openAudioInputStream(); - } - } - catch( Exception ex ) - { + else + openAudioInputStream(); + } + } catch (Exception ex) { try { ain.close(); } catch (IOException e) { @@ -232,14 +175,14 @@ public class JoglMusic implements Music, Runnable return; } } - + try { - Thread.sleep( 10 ); + Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } - } + } } diff --git a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglPanel.java b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglPanel.java index d92c88138..b3a6d5c50 100644 --- a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglPanel.java +++ b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglPanel.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.desktop; import java.awt.BorderLayout; @@ -45,429 +43,367 @@ import com.sun.opengl.impl.NativeLibLoader; import com.sun.opengl.util.Animator; /** - * An OpenGL based graphics panel. Shares its context with all - * other GraphicPanels in the application. Has a continous render - * thread constantly invoking the paint method. Note that you have - * to dispose the panel before it is being removed from another + * An OpenGL based graphics panel. Shares its context with all other GraphicPanels in the application. Has a continous render + * thread constantly invoking the paint method. Note that you have to dispose the panel before it is being removed from another * gui component such as a JFrame. * * @author badlogicgames@gmail.com - * + * */ -final class JoglPanel extends JPanel implements GLEventListener, MouseMotionListener, MouseListener, KeyListener -{ +final class JoglPanel extends JPanel implements GLEventListener, MouseMotionListener, MouseListener, KeyListener { private static final long serialVersionUID = -3638194405409146221L; /** global flag used to check wheter the libraries are loaded already **/ private static boolean loaded = false; - + /** the context to be used by all GraphicPanels **/ - private static GLContext context = null; - + private static GLContext context = null; + /** the canvas object **/ private final GLCanvas canvas; - + /** animator for continous updates **/ - private final Animator animator; - + private final Animator animator; + /** vsynch flag **/ private boolean vSynch = true; - + /** last mouse position **/ - private final Point mousePosition = new Point( ); - + private final Point mousePosition = new Point(); + /** last mouse button states **/ - private final HashSet buttons = new HashSet( ); - + private final HashSet buttons = new HashSet(); + /** last key states **/ - private final HashSet keys = new HashSet( ); - + private final HashSet keys = new HashSet(); + /** listeners **/ - private final ArrayList listeners = new ArrayList( ); - + private final ArrayList listeners = new ArrayList(); + /** listeners **/ - private final ArrayList setupListeners = new ArrayList( ); - + private final ArrayList setupListeners = new ArrayList(); + /** start time of last frame **/ private long frameStart = System.nanoTime(); - + /** delta time between current and last frame **/ private float deltaTime = 0; - private WindowedMean mean = new WindowedMean(10); + private WindowedMean mean = new WindowedMean(10); private JoglInputMultiplexer multiplexer; - + /** * loads the necessary libraries depending on the operating system */ - private static void loadLibraries( ) - { - if( loaded ) - return; - - NativeLibLoader.disableLoading(); + private static void loadLibraries () { + if (loaded) return; + + NativeLibLoader.disableLoading(); com.sun.gluegen.runtime.NativeLibLoader.disableLoading(); - // By wkien: On some systems (read: mine) jogl_awt would not find its dependency jawt if not loaded before - System.loadLibrary("jawt"); - loadLibrary( "gluegen-rt" ); - loadLibrary( "jogl_awt" ); - loadLibrary( "jogl" ); - + // By wkien: On some systems (read: mine) jogl_awt would not find its dependency jawt if not loaded before + System.loadLibrary("jawt"); + loadLibrary("gluegen-rt"); + loadLibrary("jogl_awt"); + loadLibrary("jogl"); + loaded = true; } - - /** + + /** * helper method to load a specific library in an operation system dependant manner * @param resource the name of the resource */ - private static void loadLibrary( String resource ) - { + private static void loadLibrary (String resource) { String package_path = "/javax/media/"; String library = ""; - - String os = System.getProperty( "os.name" ); - String arch = System.getProperty( "os.arch" ); - - if( os.contains( "Windows" ) ) - { - if( !arch.equals( "amd64" ) ) + + String os = System.getProperty("os.name"); + String arch = System.getProperty("os.arch"); + + if (os.contains("Windows")) { + if (!arch.equals("amd64")) library = resource + "-win32.dll"; - else - { + else { library = resource + "-win64.dll"; } } - - if( os.contains( "Linux" ) ) - { - if( !arch.equals( "amd64" ) ) + + if (os.contains("Linux")) { + if (!arch.equals("amd64")) library = "lib" + resource + "-linux32.so"; - else - library = "lib" + resource + "-linux64.so"; + else + library = "lib" + resource + "-linux64.so"; } - - if( os.contains( "Mac" ) ) - { + + if (os.contains("Mac")) { library = "lib" + resource + ".jnilib"; } - - String so = System.getProperty( "java.io.tmpdir" ) + "/" + System.nanoTime() + library; - InputStream in = JoglPanel.class.getResourceAsStream( package_path + library ); - if( in == null ) - throw new RuntimeException( "couldn't find " + library + " in jar file." ); - - try - { - BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream( so ) ); - byte[] bytes = new byte[1024*4]; - while( true ) - { + + String so = System.getProperty("java.io.tmpdir") + "/" + System.nanoTime() + library; + InputStream in = JoglPanel.class.getResourceAsStream(package_path + library); + if (in == null) throw new RuntimeException("couldn't find " + library + " in jar file."); + + try { + BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(so)); + byte[] bytes = new byte[1024 * 4]; + while (true) { int read_bytes = in.read(bytes); - if( read_bytes == -1 ) - break; - - out.write( bytes, 0, read_bytes ); + if (read_bytes == -1) break; + + out.write(bytes, 0, read_bytes); } out.close(); in.close(); - System.load( so ); - } - catch (FileNotFoundException e) - { - throw new RuntimeException( "couldn't write " + library + " to temporary file " + so ); - } - catch (IOException e) - { - throw new RuntimeException( "couldn't write " + library + " to temporary file " + so ); - } - } - + System.load(so); + } catch (FileNotFoundException e) { + throw new RuntimeException("couldn't write " + library + " to temporary file " + so); + } catch (IOException e) { + throw new RuntimeException("couldn't write " + library + " to temporary file " + so); + } + } + /** - * Constructor loading the libraries if needed and creating/reusing a - * {@link GLContext}. A standard back/depth/stencil buffer combination is - * created (32-bit, 16-bit, 8-bit). Additionally an animator thread is - * created that is responsible for redrawing the panel as fast as possible in - * case the continous flag is set to true. - * Keyboard and Mouse events are processed by the panel so that a client - * can poll for specific states. + * Constructor loading the libraries if needed and creating/reusing a {@link GLContext}. A standard back/depth/stencil buffer + * combination is created (32-bit, 16-bit, 8-bit). Additionally an animator thread is created that is responsible for redrawing + * the panel as fast as possible in case the continous flag is set to true. Keyboard and Mouse events are processed by the + * panel so that a client can poll for specific states. */ - JoglPanel( Application application ) - { + JoglPanel (Application application) { super(); - loadLibraries(); - + loadLibraries(); + GLCapabilities caps = new GLCapabilities(); caps.setRedBits(8); - caps.setGreenBits(8); - caps.setBlueBits(8); - caps.setAlphaBits(8); - caps.setDepthBits(16); - caps.setStencilBits(8); - caps.setNumSamples(0); - caps.setSampleBuffers(false); - caps.setDoubleBuffered(true); - - if( context == null ) - { - canvas = new GLCanvas( caps ); - context = canvas.getContext(); - } - else - canvas = new GLCanvas( caps, null, context, null ); - - canvas.addGLEventListener(this); - this.setLayout( new BorderLayout() ); - add(canvas,BorderLayout.CENTER); - - animator = new Animator( canvas ); - animator.setRunAsFastAsPossible(true); - animator.start(); - - canvas.addMouseListener( this ); - canvas.addMouseMotionListener( this ); - canvas.addKeyListener( this ); - } - + caps.setGreenBits(8); + caps.setBlueBits(8); + caps.setAlphaBits(8); + caps.setDepthBits(16); + caps.setStencilBits(8); + caps.setNumSamples(0); + caps.setSampleBuffers(false); + caps.setDoubleBuffered(true); + + if (context == null) { + canvas = new GLCanvas(caps); + context = canvas.getContext(); + } else + canvas = new GLCanvas(caps, null, context, null); + + canvas.addGLEventListener(this); + this.setLayout(new BorderLayout()); + add(canvas, BorderLayout.CENTER); + + animator = new Animator(canvas); + animator.setRunAsFastAsPossible(true); + animator.start(); + + canvas.addMouseListener(this); + canvas.addMouseMotionListener(this); + canvas.addKeyListener(this); + } + /** * stops the animator thread and releases any resources */ - public void dispose( ) - { - if( animator != null ) - animator.stop(); + public void dispose () { + if (animator != null) animator.stop(); canvas.getContext().makeCurrent(); - for( RenderListener listener: listeners ) - listener.dispose( ); - remove(canvas); + for (RenderListener listener : listeners) + listener.dispose(); + remove(canvas); } - - + /** * @return the delta time between the current and last frame */ - public float getDeltaTime( ) - { - return mean.hasEnoughData()?mean.getMean():deltaTime; + public float getDeltaTime () { + return mean.hasEnoughData() ? mean.getMean() : deltaTime; } - + /** * @return the underlying GLCanvas */ - public GLCanvas getCanvas( ) - { + public GLCanvas getCanvas () { return canvas; } - + /** * sets wheter vsynch is enabled or disabled. true by default. * * @param v_synch */ - public void setVerticalSynch( boolean v_synch ) - { - this.vSynch = v_synch; - if( v_synch ) + public void setVerticalSynch (boolean v_synch) { + this.vSynch = v_synch; + if (v_synch) GLContext.getCurrent().getGL().setSwapInterval(1); else GLContext.getCurrent().getGL().setSwapInterval(0); } - + /** * @return wheter vsynch is on or not */ - public boolean getVerticalSynch( ) - { + public boolean getVerticalSynch () { return vSynch; - } - - public void mouseDragged(MouseEvent arg0) - { + } + + public void mouseDragged (MouseEvent arg0) { mousePosition.x = arg0.getX(); mousePosition.y = arg0.getY(); - + } - public void mouseMoved(MouseEvent arg0) - { + public void mouseMoved (MouseEvent arg0) { mousePosition.x = arg0.getX(); - mousePosition.y = arg0.getY(); + mousePosition.y = arg0.getY(); } - public int getMouseX( ) - { + public int getMouseX () { return mousePosition.x; } - - public int getMouseY( ) - { + + public int getMouseY () { return mousePosition.y; } - - public void mouseClicked(MouseEvent arg0) { + + public void mouseClicked (MouseEvent arg0) { // TODO Auto-generated method stub - + } - public void mouseEntered(MouseEvent arg0) { + public void mouseEntered (MouseEvent arg0) { // TODO Auto-generated method stub - + } - public void mouseExited(MouseEvent arg0) { + public void mouseExited (MouseEvent arg0) { // TODO Auto-generated method stub - + } - public void mousePressed(MouseEvent arg0) - { - buttons.add( arg0.getButton() ); + public void mousePressed (MouseEvent arg0) { + buttons.add(arg0.getButton()); } - public void mouseReleased(MouseEvent arg0) - { - buttons.remove( arg0.getButton() ); + public void mouseReleased (MouseEvent arg0) { + buttons.remove(arg0.getButton()); } - public void keyPressed(KeyEvent arg0) - { - keys.add( JoglInputMultiplexer.translateKeyCode(arg0.getKeyCode()) ); + public void keyPressed (KeyEvent arg0) { + keys.add(JoglInputMultiplexer.translateKeyCode(arg0.getKeyCode())); } - public void keyReleased(KeyEvent arg0) - { -// getCanvas().getContext().makeCurrent(); - keys.remove( JoglInputMultiplexer.translateKeyCode(arg0.getKeyCode()) ); + public void keyReleased (KeyEvent arg0) { +// getCanvas().getContext().makeCurrent(); + keys.remove(JoglInputMultiplexer.translateKeyCode(arg0.getKeyCode())); } - public void keyTyped(KeyEvent arg0) { - + public void keyTyped (KeyEvent arg0) { + } /** - * returns wheter the given mousebutton is down. use - * the constants in {@link MouseEvent}. + * returns wheter the given mousebutton is down. use the constants in {@link MouseEvent}. * * @param button the button in question * @return wheter the button is down or not */ - public boolean isButtonDown( int button ) - { + public boolean isButtonDown (int button) { return buttons.size() > 0; } - + /** - * returns wheter the given key is down. use the - * constants in {@link KeyEvent}. + * returns wheter the given key is down. use the constants in {@link KeyEvent}. * * @param key the key in question * @return wheter the key is down or not */ - public boolean isKeyDown( int key ) - { - return keys.contains( key ); + public boolean isKeyDown (int key) { + return keys.contains(key); } - - /** - * adds a new graphic listener + + /** + * adds a new graphic listener * @param listener the listener */ - public void addGraphicListener( RenderListener listener ) - { - synchronized( this ) - { - setupListeners.add( listener ); - } - } - + public void addGraphicListener (RenderListener listener) { + synchronized (this) { + setupListeners.add(listener); + } + } + /** - * removes a graphic listener + * removes a graphic listener * @param listener the listener */ - public void removeGraphicListener( RenderListener listener ) - { - synchronized( this ) - { + public void removeGraphicListener (RenderListener listener) { + synchronized (this) { setupListeners.remove(listener); - listeners.remove( listener ); - listener.dispose( ); + listeners.remove(listener); + listener.dispose(); } } - @Override - public void display(GLAutoDrawable arg0) - { - if( multiplexer != null ) - multiplexer.processEvents(); - deltaTime = (System.nanoTime() - frameStart ) / 1000000000.0f; + @Override public void display (GLAutoDrawable arg0) { + if (multiplexer != null) multiplexer.processEvents(); + deltaTime = (System.nanoTime() - frameStart) / 1000000000.0f; frameStart = System.nanoTime(); - mean.addValue( deltaTime ); - - synchronized( this ) - { - for( RenderListener listener: setupListeners ) - { - listener.surfaceCreated( ); - listener.surfaceChanged(this.getWidth(), this.getHeight() ); + mean.addValue(deltaTime); + + synchronized (this) { + for (RenderListener listener : setupListeners) { + listener.surfaceCreated(); + listener.surfaceChanged(this.getWidth(), this.getHeight()); } listeners.addAll(setupListeners); setupListeners.clear(); - - for( RenderListener listener: listeners ) - listener.render( ); + + for (RenderListener listener : listeners) + listener.render(); } - + } - @Override - public void displayChanged(GLAutoDrawable arg0, boolean arg1, boolean arg2) - { - deltaTime = (System.nanoTime() - frameStart ) / 1000000000.0f; + @Override public void displayChanged (GLAutoDrawable arg0, boolean arg1, boolean arg2) { + deltaTime = (System.nanoTime() - frameStart) / 1000000000.0f; frameStart = System.nanoTime(); - - for( RenderListener listener: listeners ) - listener.render( ); + + for (RenderListener listener : listeners) + listener.render(); } - @Override - public void init(GLAutoDrawable arg0) - { - for( RenderListener listener: listeners ) - listener.surfaceCreated( ); + @Override public void init (GLAutoDrawable arg0) { + for (RenderListener listener : listeners) + listener.surfaceCreated(); setVerticalSynch(true); } - @Override - public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4) - { - deltaTime = (System.nanoTime() - frameStart ) / 1000000000.0f; + @Override public void reshape (GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4) { + deltaTime = (System.nanoTime() - frameStart) / 1000000000.0f; frameStart = System.nanoTime(); - - for( RenderListener listener: listeners ) - { - listener.surfaceChanged( this.getWidth(), this.getHeight() ); - listener.render( ); + + for (RenderListener listener : listeners) { + listener.surfaceChanged(this.getWidth(), this.getHeight()); + listener.render(); } } - /** * @return the gl context this panel works on */ - public GL getGL( ) - { + public GL getGL () { return canvas.getGL(); } - public Point getLastMousePosition( ) - { + public Point getLastMousePosition () { return mousePosition; } - public void setInputMultiplexer(JoglInputMultiplexer inputMultiplexer) { + public void setInputMultiplexer (JoglInputMultiplexer inputMultiplexer) { multiplexer = inputMultiplexer; } - public boolean isAnyKeyDown() { + public boolean isAnyKeyDown () { return keys.size() > 0; } } diff --git a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglPixmap.java b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglPixmap.java index 1d20bdb11..4f7b27cac 100644 --- a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglPixmap.java +++ b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglPixmap.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.desktop; import java.awt.AlphaComposite; @@ -25,220 +23,187 @@ import java.awt.image.BufferedImage; import com.badlogic.gdx.graphics.Pixmap; - /** * An implementation of Pixmap based on the java graphics framework. * * @author badlogicgames@gmail.com - * + * */ -final class JoglPixmap implements Pixmap -{ +final class JoglPixmap implements Pixmap { BufferedImage pixmap; Composite composite; - Color color = new Color( 0 ); + Color color = new Color(0); int strokeWidth = 1; - JoglPixmap( int width, int height, Pixmap.Format format ) - { - int internalformat = getInternalFormat( format ); + JoglPixmap (int width, int height, Pixmap.Format format) { + int internalformat = getInternalFormat(format); pixmap = new BufferedImage(width, height, internalformat); composite = AlphaComposite.Src; } - - JoglPixmap(BufferedImage image) - { + + JoglPixmap (BufferedImage image) { if (image == null) throw new IllegalArgumentException("image cannot be null."); pixmap = image; } - private int getInternalFormat( Pixmap.Format format ) - { - if( format == Pixmap.Format.RGBA4444 || format == Pixmap.Format.RGBA8888 || format == Pixmap.Format.RGB565 ) + private int getInternalFormat (Pixmap.Format format) { + if (format == Pixmap.Format.RGBA4444 || format == Pixmap.Format.RGBA8888 || format == Pixmap.Format.RGB565) return BufferedImage.TYPE_4BYTE_ABGR; else return BufferedImage.TYPE_BYTE_GRAY; } - + /** * {@inheritDoc} */ - @Override - public void drawCircle(int x, int y, int radius) { + @Override public void drawCircle (int x, int y, int radius) { Graphics2D g = (Graphics2D)pixmap.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.setComposite( composite ); - g.setColor( color ); - g.setStroke( new BasicStroke( strokeWidth ) ); - g.drawRect(x, y, radius * 2, radius * 2); + g.setComposite(composite); + g.setColor(color); + g.setStroke(new BasicStroke(strokeWidth)); + g.drawRect(x, y, radius * 2, radius * 2); g.dispose(); - + } /** * {@inheritDoc} */ - @Override - public void drawLine(int x, int y, int x2, int y2) { - Graphics2D g = (Graphics2D)pixmap.getGraphics(); + @Override public void drawLine (int x, int y, int x2, int y2) { + Graphics2D g = (Graphics2D)pixmap.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.setComposite( composite ); - g.setColor( color ); - g.setStroke( new BasicStroke( strokeWidth ) ); - g.drawLine(x, y, x2, y2); + g.setComposite(composite); + g.setColor(color); + g.setStroke(new BasicStroke(strokeWidth)); + g.drawLine(x, y, x2, y2); g.dispose(); - + } /** * {@inheritDoc} */ - @Override - public void drawRectangle(int x, int y, int width, int height) { - Graphics2D g = (Graphics2D)pixmap.getGraphics(); + @Override public void drawRectangle (int x, int y, int width, int height) { + Graphics2D g = (Graphics2D)pixmap.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.setComposite( composite ); - g.setColor( color ); - g.setStroke( new BasicStroke( strokeWidth ) ); - g.drawRect(x, y, width, height); + g.setComposite(composite); + g.setColor(color); + g.setStroke(new BasicStroke(strokeWidth)); + g.drawRect(x, y, width, height); g.dispose(); } /** * {@inheritDoc} */ - @Override - public void fill() - { - Graphics2D g = (Graphics2D)pixmap.getGraphics(); + @Override public void fill () { + Graphics2D g = (Graphics2D)pixmap.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.setComposite( composite ); - g.setColor( color ); - g.fillRect( 0, 0, pixmap.getWidth(), pixmap.getHeight() ); + g.setComposite(composite); + g.setColor(color); + g.fillRect(0, 0, pixmap.getWidth(), pixmap.getHeight()); g.dispose(); } /** * {@inheritDoc} */ - @Override - public void fillCircle(int x, int y, int radius) - { - Graphics2D g = (Graphics2D)pixmap.getGraphics(); + @Override public void fillCircle (int x, int y, int radius) { + Graphics2D g = (Graphics2D)pixmap.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.setComposite( composite ); - g.setColor( color ); - g.fillOval( x, y, radius * 2, radius * 2); + g.setComposite(composite); + g.setColor(color); + g.fillOval(x, y, radius * 2, radius * 2); g.dispose(); } /** * {@inheritDoc} */ - @Override - public void fillRectangle(int x, int y, int width, int height) - { - Graphics2D g = (Graphics2D)pixmap.getGraphics(); + @Override public void fillRectangle (int x, int y, int width, int height) { + Graphics2D g = (Graphics2D)pixmap.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.setComposite( composite ); - g.setColor( color ); - g.fillRect( x, y, width, height ); + g.setComposite(composite); + g.setColor(color); + g.fillRect(x, y, width, height); g.dispose(); } /** * {@inheritDoc} */ - @Override - public Object getNativePixmap() - { + @Override public Object getNativePixmap () { return pixmap; } /** * {@inheritDoc} */ - @Override - public void setColor(float r, float g, float b, float a) - { - color = new Color( r, g, b, a ); + @Override public void setColor (float r, float g, float b, float a) { + color = new Color(r, g, b, a); } /** * {@inheritDoc} */ - @Override - public void setStrokeWidth(int width) - { + @Override public void setStrokeWidth (int width) { strokeWidth = width; } /** * {@inheritDoc} */ - @Override - public int getPixel(int x, int y) - { - if( x < 0 || x >= pixmap.getWidth() ) - return 0; - if( y < 0 || y >= pixmap.getHeight() ) - return 0; + @Override public int getPixel (int x, int y) { + if (x < 0 || x >= pixmap.getWidth()) return 0; + if (y < 0 || y >= pixmap.getHeight()) return 0; return pixmap.getRGB(x, y); } /** * {@inheritDoc} */ - @Override - public int getHeight() { + @Override public int getHeight () { return pixmap.getHeight(); } /** * {@inheritDoc} */ - @Override - public int getWidth() { + @Override public int getWidth () { return pixmap.getWidth(); } /** * {@inheritDoc} */ - @Override - public void drawPixmap(Pixmap pixmap, int x, int y, int srcx, int srcy, int width, int height) - { + @Override public void drawPixmap (Pixmap pixmap, int x, int y, int srcx, int srcy, int width, int height) { BufferedImage image = (BufferedImage)pixmap.getNativePixmap(); - + Graphics2D g = (Graphics2D)this.pixmap.getGraphics(); - g.setComposite( composite ); - g.drawImage(image, x, y, x + width, y + height, - srcx, srcy, srcx + width, srcy + height, null); + g.setComposite(composite); + g.drawImage(image, x, y, x + width, y + height, srcx, srcy, srcx + width, srcy + height, null); g.dispose(); - + } /** * {@inheritDoc} */ - @Override - public void dispose() { + @Override public void dispose () { // TODO Auto-generated method stub - + } /** * {@inheritDoc} */ - @Override - public void getPixelRow(int[] pixels, int y) - { - for( int x = 0; x < pixmap.getWidth(); x++ ) - { + @Override public void getPixelRow (int[] pixels, int y) { + for (int x = 0; x < pixmap.getWidth(); x++) { pixels[x] = pixmap.getRGB(x, y); } - + } - + } diff --git a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglSound.java b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglSound.java index deda5838b..e5e5a1ccd 100644 --- a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglSound.java +++ b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglSound.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.desktop; import java.io.BufferedInputStream; @@ -33,167 +31,129 @@ import javax.sound.sampled.UnsupportedAudioFileException; import com.badlogic.gdx.audio.Sound; /** - * Implements the {@link Sound} interface for the desktop - * using {@link Clip}s internally. + * Implements the {@link Sound} interface for the desktop using {@link Clip}s internally. * @author mzechner - * + * */ -public class JoglSound implements Sound -{ +public class JoglSound implements Sound { /** the audio format **/ private final AudioFormat format; - + /** the audio data **/ private final byte[] originalSamples; - + /** the float audio data **/ private float[] samples; - + /** the audio instance **/ private final JoglAudio audio; - - public JoglSound( JoglAudio audio, JoglFileHandle file ) throws UnsupportedAudioFileException, IOException - { + public JoglSound (JoglAudio audio, JoglFileHandle file) throws UnsupportedAudioFileException, IOException { this.audio = audio; - InputStream fin = new BufferedInputStream( new FileInputStream( file.getFile() ) ); - AudioInputStream ain = AudioSystem.getAudioInputStream( fin ); + InputStream fin = new BufferedInputStream(new FileInputStream(file.getFile())); + AudioInputStream ain = AudioSystem.getAudioInputStream(fin); AudioFormat baseFormat = ain.getFormat(); - AudioFormat decodedFormat = new AudioFormat( - AudioFormat.Encoding.PCM_SIGNED, - baseFormat.getSampleRate(), - 16, - baseFormat.getChannels(), - baseFormat.getChannels() * 2, - baseFormat.getSampleRate(), - false); - - ain = AudioSystem.getAudioInputStream(decodedFormat, ain); + AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, + baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false); + + ain = AudioSystem.getAudioInputStream(decodedFormat, ain); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - byte[] buffer = new byte[1024*10]; - int readBytes = ain.read( buffer ); - while( readBytes != -1 ) - { - bytes.write( buffer, 0, readBytes ); - readBytes = ain.read( buffer ); - } + byte[] buffer = new byte[1024 * 10]; + int readBytes = ain.read(buffer); + while (readBytes != -1) { + bytes.write(buffer, 0, readBytes); + readBytes = ain.read(buffer); + } ain.close(); System.out.println(decodedFormat); format = decodedFormat; - originalSamples = bytes.toByteArray(); - - ByteBuffer tmpBuffer = ByteBuffer.wrap( originalSamples ); + originalSamples = bytes.toByteArray(); + + ByteBuffer tmpBuffer = ByteBuffer.wrap(originalSamples); tmpBuffer.order(ByteOrder.LITTLE_ENDIAN); ShortBuffer shorts = tmpBuffer.asShortBuffer(); - samples = new float[originalSamples.length/2]; - for( int i = 0; i < samples.length; i++ ) - { + samples = new float[originalSamples.length / 2]; + for (int i = 0; i < samples.length; i++) { float value = shorts.get(i) / (float)Short.MAX_VALUE; - if( value < -1 ) - value = -1; - if( value > 1 ) - value = 1; + if (value < -1) value = -1; + if (value > 1) value = 1; samples[i] = value; } - - samples = resample( samples, decodedFormat.getSampleRate(), decodedFormat.getChannels() == 1 ); + + samples = resample(samples, decodedFormat.getSampleRate(), decodedFormat.getChannels() == 1); } - - private float[] resample( float[] samples, float sampleRate, boolean isMono ) - { - if( sampleRate == 44100 ) - return samples; - + + private float[] resample (float[] samples, float sampleRate, boolean isMono) { + if (sampleRate == 44100) return samples; + float idxInc = sampleRate / 44100; int numSamples = (int)((samples.length / (float)sampleRate) * 44100); - if( !isMono && numSamples % 2 != 0 ) - numSamples--; - + if (!isMono && numSamples % 2 != 0) numSamples--; + float[] newSamples = new float[numSamples]; - - if( isMono ) - { + + if (isMono) { float idx = 0; - for( int i = 0; i < newSamples.length; i++ ) - { - int intIdx = (int)idx; - if( intIdx >= samples.length - 1 ) - break; - - float value = samples[intIdx] + samples[intIdx+1]; + for (int i = 0; i < newSamples.length; i++) { + int intIdx = (int)idx; + if (intIdx >= samples.length - 1) break; + + float value = samples[intIdx] + samples[intIdx + 1]; value /= 2; - if( value > 1 ) - value = 1; - if( value < -1 ) - value = -1; + if (value > 1) value = 1; + if (value < -1) value = -1; newSamples[i] = value; idx += idxInc; } - } - else - { - float idx = 0; - for( int i = 0; i < newSamples.length; i+=2 ) - { - int intIdxL = (int)idx * 2; + } else { + float idx = 0; + for (int i = 0; i < newSamples.length; i += 2) { + int intIdxL = (int)idx * 2; int intIdxR = (int)idx * 2 + 1; - if( intIdxL >= samples.length - 2 ) - break; - - float value = samples[intIdxL] + samples[intIdxL+2]; + if (intIdxL >= samples.length - 2) break; + + float value = samples[intIdxL] + samples[intIdxL + 2]; value /= 2; - if( value > 1 ) - value = 1; - if( value < -1 ) - value = -1; + if (value > 1) value = 1; + if (value < -1) value = -1; newSamples[i] = value; - - value = samples[intIdxR] + samples[intIdxR+2]; + + value = samples[intIdxR] + samples[intIdxR + 2]; value /= 2; - if( value > 1 ) - value = 1; - if( value < -1 ) - value = -1; - newSamples[i+1] = value; - + if (value > 1) value = 1; + if (value < -1) value = -1; + newSamples[i + 1] = value; + idx += idxInc; } } - + return newSamples; } - - @Override - public void dispose() - { - + + @Override public void dispose () { + } - @Override - public void play() - { - audio.enqueueSound( this, 1 ); + @Override public void play () { + audio.enqueueSound(this, 1); } - - @Override - public void play( float volume ) - { - audio.enqueueSound( this, volume ); + + @Override public void play (float volume) { + audio.enqueueSound(this, volume); } /** * @return the {@link AudioFormat} of the audio data */ - public AudioFormat getAudioFormat() - { + public AudioFormat getAudioFormat () { return format; } /** * @return the audio samples in form of a byte array */ - public float[] getAudioData() - { + public float[] getAudioData () { return samples; } diff --git a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglTexture.java b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglTexture.java index 2cc9d984b..7f34169a4 100644 --- a/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglTexture.java +++ b/backends/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglTexture.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.desktop; import java.awt.image.BufferedImage; @@ -32,166 +30,149 @@ import com.sun.opengl.util.texture.TextureIO; * An implementation of {@link Texture} based on Jogl * * @author badlogicgames@gmail.com - * + * */ -final class JoglTexture implements Texture -{ +final class JoglTexture implements Texture { /** height in pixels of texture **/ private int texHeight; /** width in pixels of texture **/ - private int texWidth; + private int texWidth; /** texture wrapper **/ com.sun.opengl.util.texture.Texture texture; /** whether this textures i managed or not **/ private final boolean isManaged; - + /** global number of textures **/ public static int textures = 0; - + /** * Create a new texture - * + * * @param textureID The GL texture ID */ - JoglTexture(InputStream in, TextureFilter minFilter, TextureFilter maxFilter, TextureWrap uWrap, TextureWrap vWrap, boolean managed ) - { + JoglTexture (InputStream in, TextureFilter minFilter, TextureFilter maxFilter, TextureWrap uWrap, TextureWrap vWrap, + boolean managed) { this.isManaged = managed; - try - { - BufferedImage image = ImageIO.read(in); - texture = com.sun.opengl.util.texture.TextureIO.newTexture( image, minFilter == TextureFilter.MipMap?true:false ); - } - catch( Exception ex ) - { - throw new GdxRuntimeException( "Couldn load Texture", ex ); + try { + BufferedImage image = ImageIO.read(in); + texture = com.sun.opengl.util.texture.TextureIO.newTexture(image, minFilter == TextureFilter.MipMap ? true : false); + } catch (Exception ex) { + throw new GdxRuntimeException("Couldn load Texture", ex); } GL gl = GLContext.getCurrent().getGL(); - - bind(); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, getTextureFilter( minFilter ) ); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, getTextureFilter( maxFilter ) ); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, getTextureWrap( uWrap ) ); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, getTextureWrap( vWrap ) ); + + bind(); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, getTextureFilter(minFilter)); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, getTextureFilter(maxFilter)); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, getTextureWrap(uWrap)); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, getTextureWrap(vWrap)); this.texWidth = texture.getWidth(); this.texHeight = texture.getHeight(); textures++; - } - - JoglTexture(BufferedImage image, TextureFilter minFilter, TextureFilter maxFilter, TextureWrap uWrap, TextureWrap vWrap, boolean managed ) - { - this.isManaged = managed; - texture = com.sun.opengl.util.texture.TextureIO.newTexture( image, minFilter == TextureFilter.MipMap?true:false ); + } + + JoglTexture (BufferedImage image, TextureFilter minFilter, TextureFilter maxFilter, TextureWrap uWrap, TextureWrap vWrap, + boolean managed) { + this.isManaged = managed; + texture = com.sun.opengl.util.texture.TextureIO.newTexture(image, minFilter == TextureFilter.MipMap ? true : false); GL gl = GLContext.getCurrent().getGL(); - - bind(); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, getTextureFilter( minFilter ) ); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, getTextureFilter( maxFilter ) ); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, getTextureWrap( uWrap ) ); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, getTextureWrap( vWrap ) ); + + bind(); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, getTextureFilter(minFilter)); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, getTextureFilter(maxFilter)); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, getTextureWrap(uWrap)); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, getTextureWrap(vWrap)); this.texWidth = texture.getWidth(); this.texHeight = texture.getHeight(); textures++; - } - + } + /** * Create a new texture - * + * * @param textureID The GL texture ID */ - JoglTexture(int width, int height, int format, TextureFilter minFilter, TextureFilter maxFilter, TextureWrap uWrap, TextureWrap vWrap, boolean managed ) - { + JoglTexture (int width, int height, int format, TextureFilter minFilter, TextureFilter maxFilter, TextureWrap uWrap, + TextureWrap vWrap, boolean managed) { this.isManaged = managed; - BufferedImage image = new BufferedImage( width, height, format ); - texture = com.sun.opengl.util.texture.TextureIO.newTexture( image, minFilter == TextureFilter.MipMap?true:false ); - + BufferedImage image = new BufferedImage(width, height, format); + texture = com.sun.opengl.util.texture.TextureIO.newTexture(image, minFilter == TextureFilter.MipMap ? true : false); + GL gl = GLContext.getCurrent().getGL(); - - bind(); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, getTextureFilter( minFilter ) ); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, getTextureFilter( maxFilter ) ); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, getTextureWrap( uWrap ) ); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, getTextureWrap( vWrap ) ); + + bind(); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, getTextureFilter(minFilter)); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, getTextureFilter(maxFilter)); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, getTextureWrap(uWrap)); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, getTextureWrap(vWrap)); this.texWidth = texture.getWidth(); this.texHeight = texture.getHeight(); textures++; } - private int getTextureFilter( TextureFilter filter ) - { - if( filter == TextureFilter.Linear ) + private int getTextureFilter (TextureFilter filter) { + if (filter == TextureFilter.Linear) return GL.GL_LINEAR; - else - if( filter == TextureFilter.Nearest ) + else if (filter == TextureFilter.Nearest) return GL.GL_NEAREST; else return GL.GL_LINEAR_MIPMAP_LINEAR; } - - private int getTextureWrap( TextureWrap wrap ) - { - if( wrap == TextureWrap.ClampToEdge ) + + private int getTextureWrap (TextureWrap wrap) { + if (wrap == TextureWrap.ClampToEdge) return GL.GL_CLAMP_TO_EDGE; else return GL.GL_REPEAT; } - - public boolean isManaged( ) - { + + public boolean isManaged () { return isManaged; } - + /** * {@inheritDoc} */ - @Override - public void bind() - { + @Override public void bind () { texture.bind(); } /** * {@inheritDoc} */ - @Override - public void dispose() { - texture.dispose(); - textures--; + @Override public void dispose () { + texture.dispose(); + textures--; } /** * {@inheritDoc} */ - @Override - public int getHeight() { + @Override public int getHeight () { return texHeight; } /** * {@inheritDoc} */ - @Override - public int getWidth() { + @Override public int getWidth () { return texWidth; } /** * {@inheritDoc} */ - public void draw( Pixmap pixmap, int x, int y ) - { - if( isManaged ) - throw new GdxRuntimeException( "Can't draw to a managed texture" ); + public void draw (Pixmap pixmap, int x, int y) { + if (isManaged) throw new GdxRuntimeException("Can't draw to a managed texture"); TextureData data = TextureIO.newTextureData((BufferedImage)pixmap.getNativePixmap(), true); texture.bind(); - texture.updateSubImage( data, 0, x, y ); + texture.updateSubImage(data, 0, x, y); } /** * {@inheritDoc} */ - @Override - public int getTextureObjectHandle() - { + @Override public int getTextureObjectHandle () { return texture.getTextureObject(); } } diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/BitmapDecoder.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/BitmapDecoder.java index 8ceb84c9e..a32493ef6 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/BitmapDecoder.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/BitmapDecoder.java @@ -10,24 +10,19 @@ import java.awt.image.ComponentColorModel; import java.awt.image.DataBuffer; import java.awt.image.Raster; import java.awt.image.WritableRaster; -import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; -import java.nio.ByteOrder; import java.util.Hashtable; -import javax.imageio.ImageIO; - class BitmapDecoder { - private static final ColorModel rgbaColorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), new int[] { - 8, 8, 8, 8}, true, false, ComponentColorModel.TRANSLUCENT, DataBuffer.TYPE_BYTE); + private static final ColorModel rgbaColorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), + new int[] {8, 8, 8, 8}, true, false, ComponentColorModel.TRANSLUCENT, DataBuffer.TYPE_BYTE); private static int width, height; private static ByteBuffer buffer; private static BufferedImage tempImage; - @SuppressWarnings("unchecked") - public static ByteBuffer decode (BufferedImage image) throws IOException { + @SuppressWarnings("unchecked") public static ByteBuffer decode (BufferedImage image) throws IOException { if (image == null) throw new IOException("Invalid image."); width = image.getWidth(); @@ -45,7 +40,7 @@ class BitmapDecoder { g.fillRect(0, 0, width, height); g.setComposite(AlphaComposite.SrcOver); g.drawImage(image, 0, 0, null); - g.dispose(); + g.dispose(); int bufferSize = width * height * 4; if (buffer == null || buffer.capacity() < bufferSize) diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglApplication.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglApplication.java index 1473e06dc..748fa09e8 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglApplication.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglApplication.java @@ -25,92 +25,80 @@ import com.badlogic.gdx.Input; import com.badlogic.gdx.RenderListener; import com.badlogic.gdx.Version; -@SuppressWarnings("unchecked") -public class LwjglApplication implements Application { +@SuppressWarnings("unchecked") public class LwjglApplication implements Application { static { System.setProperty("org.lwjgl.input.Mouse.allowNegativeMouseCoords", "true"); Version.loadLibrary(); - - String os = System.getProperty( "os.name" ); - String arch = System.getProperty( "os.arch" ); + + String os = System.getProperty("os.name"); + String arch = System.getProperty("os.arch"); boolean is64Bit = false; - - if( arch.equals( "amd64" ) ) - is64Bit = true; - - if( os.contains( "Windows" ) ) - loadLibrariesWindows( is64Bit ); - if( os.contains( "Linux" ) ) - loadLibrariesLinux( is64Bit ); - if( os.contains( "Mac") ) - loadLibrariesMac( ); - - System.setProperty("org.lwjgl.librarypath", new File("").getAbsolutePath() ); + + if (arch.equals("amd64")) is64Bit = true; + + if (os.contains("Windows")) loadLibrariesWindows(is64Bit); + if (os.contains("Linux")) loadLibrariesLinux(is64Bit); + if (os.contains("Mac")) loadLibrariesMac(); + + System.setProperty("org.lwjgl.librarypath", new File("").getAbsolutePath()); } - - private static void loadLibrariesWindows( boolean is64Bit ) - { + + private static void loadLibrariesWindows (boolean is64Bit) { String[] libNames = null; - if( is64Bit ) - libNames = new String[]{ "OpenAL64.dll", "lwjgl64.dll", "jinput-raw_64.dll", "jinput-dx8_64.dll" }; + if (is64Bit) + libNames = new String[] {"OpenAL64.dll", "lwjgl64.dll", "jinput-raw_64.dll", "jinput-dx8_64.dll"}; else - libNames = new String[]{ "OpenAL32.dll", "lwjgl.dll", "jinput-raw.dll", "jinput-dx8.dll" }; - - for( String libName: libNames ) - loadLibrary( libName, "/native/windows/" ); + libNames = new String[] {"OpenAL32.dll", "lwjgl.dll", "jinput-raw.dll", "jinput-dx8.dll"}; + + for (String libName : libNames) + loadLibrary(libName, "/native/windows/"); } - - private static void loadLibrariesLinux( boolean is64Bit ) - { + + private static void loadLibrariesLinux (boolean is64Bit) { String[] libNames = null; - if( is64Bit ) - libNames = new String[]{ "libopenal64.so", "liblwjgl64.so", "jinput-linux64.so", }; + if (is64Bit) + libNames = new String[] {"libopenal64.so", "liblwjgl64.so", "jinput-linux64.so",}; else - libNames = new String[]{ "libopenal.so", "liblwjgl.so", "jinput-linux.so", }; - - for( String libName: libNames ) - loadLibrary( libName, "/native/linux/" ); + libNames = new String[] {"libopenal.so", "liblwjgl.so", "jinput-linux.so",}; + + for (String libName : libNames) + loadLibrary(libName, "/native/linux/"); } - - - private static void loadLibrariesMac( ) - { - throw new GdxRuntimeException( "loading native libs on Mac OS X not supported, mail contact@badlogicgames.com" ); + + private static void loadLibrariesMac () { + throw new GdxRuntimeException("loading native libs on Mac OS X not supported, mail contact@badlogicgames.com"); } - - private static void loadLibrary( String libName, String classPath ) - { + + private static void loadLibrary (String libName, String classPath) { InputStream in = null; BufferedOutputStream out = null; - - try - { - in = LwjglApplication.class.getResourceAsStream( classPath + libName ); - out = new BufferedOutputStream( new FileOutputStream( libName ) ); - byte[] bytes = new byte[1024*4]; - while( true ) - { + + try { + in = LwjglApplication.class.getResourceAsStream(classPath + libName); + out = new BufferedOutputStream(new FileOutputStream(libName)); + byte[] bytes = new byte[1024 * 4]; + while (true) { int read_bytes = in.read(bytes); - if( read_bytes == -1 ) - break; - - out.write( bytes, 0, read_bytes ); - } + if (read_bytes == -1) break; + + out.write(bytes, 0, read_bytes); + } out.close(); out = null; in.close(); in = null; - } - catch( Throwable t ) - { - new GdxRuntimeException( "Couldn't load lwjgl native, " + libName, t ); - } - finally - { - if( out != null ) - try{ out.close(); } catch( Exception ex ) { }; - if( in != null ) - try{ in.close(); } catch( Exception ex ) { } + } catch (Throwable t) { + new GdxRuntimeException("Couldn't load lwjgl native, " + libName, t); + } finally { + if (out != null) try { + out.close(); + } catch (Exception ex) { + } + ; + if (in != null) try { + in.close(); + } catch (Exception ex) { + } } } @@ -119,7 +107,7 @@ public class LwjglApplication implements Application { private final LwjglAudio audio; protected int width, height; - private String title = ""; + private String title = ""; private boolean mousePressed; private int mouseX, mouseY; private volatile boolean running = true; @@ -184,7 +172,7 @@ public class LwjglApplication implements Application { } for (RenderListener listener : listeners) listener.render(); - + while (running && !Display.isCloseRequested()) { if (Keyboard.isCreated()) { @@ -203,35 +191,32 @@ public class LwjglApplication implements Application { int y = height - Mouse.getY(); while (Mouse.next()) { if (isButtonPressed()) { - if( mousePressed == false ) - { + if (mousePressed == false) { mousePressed = true; mouseX = x; mouseY = y; input.fireTouchDown(x, y, 0); - } - else { - if(mouseX != x || mouseY != y) { + } else { + if (mouseX != x || mouseY != y) { input.fireTouchDragged(x, y, 0); mouseX = x; - mouseY = y; + mouseY = y; } } - } else { - if( mousePressed == true ) - { + } else { + if (mousePressed == true) { mousePressed = false; input.fireTouchUp(x, y, 0); } } - } + } } for (int i = 0, n = listeners.size(); i < n; i++) listeners.get(i).render(); - Display.update(); - Display.sync( 60 ); + Display.update(); + Display.sync(60); } if (appListener != null) appListener.pause(); @@ -244,14 +229,12 @@ public class LwjglApplication implements Application { if (appListener != null) appListener.destroy(); } - private boolean isButtonPressed( ) - { - for( int i = 0; i < Mouse.getButtonCount(); i++ ) - if( Mouse.isButtonDown( i ) ) - return true; + private boolean isButtonPressed () { + for (int i = 0; i < Mouse.getButtonCount(); i++) + if (Mouse.isButtonDown(i)) return true; return false; } - + public void stop () { running = false; try { @@ -300,10 +283,8 @@ public class LwjglApplication implements Application { public ApplicationType getType () { return ApplicationType.Desktop; } - - @Override - public int getVersion() - { + + @Override public int getVersion () { return 0; } } diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglGL10.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglGL10.java index 972d86c74..793174881 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglGL10.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglGL10.java @@ -35,7 +35,7 @@ import com.badlogic.gdx.graphics.GL10; * */ class LwjglGL10 implements GL10 { - + protected final float FIXED_TO_FLOAT = 1 / 65536.0f; private final FloatBuffer colorBuffer; private final FloatBuffer normalBuffer; @@ -187,31 +187,33 @@ class LwjglGL10 implements GL10 { if (type == GL10.GL_FIXED) { convertFixedToFloatbuffer(pointer, colorBuffer, stride); GL11.glColorPointer(size, stride, colorBuffer); - } else { - if( pointer instanceof FloatBuffer && type == GL10.GL_FLOAT ) - GL11.glColorPointer( size, stride,(FloatBuffer)pointer ); - else - if( pointer instanceof ByteBuffer && type == GL10.GL_FLOAT ) - GL11.glColorPointer( size, stride, ((ByteBuffer)pointer).asFloatBuffer() ); // FIXME yes, that's why it sucks... GC will be happy. - else - if( pointer instanceof ByteBuffer && type == GL10.GL_UNSIGNED_BYTE ) - GL11.glColorPointer( size, true, stride, (ByteBuffer)pointer ); + } else { + if (pointer instanceof FloatBuffer && type == GL10.GL_FLOAT) + GL11.glColorPointer(size, stride, (FloatBuffer)pointer); + else if (pointer instanceof ByteBuffer && type == GL10.GL_FLOAT) + GL11.glColorPointer(size, stride, ((ByteBuffer)pointer).asFloatBuffer()); // FIXME yes, that's why it sucks... GC will +// be happy. + else if (pointer instanceof ByteBuffer && type == GL10.GL_UNSIGNED_BYTE) + GL11.glColorPointer(size, true, stride, (ByteBuffer)pointer); else - throw new GdxRuntimeException( "Can't use " + pointer.getClass().getName() + " with this method, use FloatBuffer or ByteBuffer. blame LWJGL" ); + throw new GdxRuntimeException("Can't use " + pointer.getClass().getName() + + " with this method, use FloatBuffer or ByteBuffer. blame LWJGL"); } } public final void glCompressedTexImage2D (int target, int level, int internalformat, int width, int height, int border, int imageSize, Buffer data) { - if( !(data instanceof ByteBuffer) ) - throw new GdxRuntimeException( "Can't use " + data.getClass().getName() + " with this method. Use ByteBuffer. Blame LWJGL" ); + if (!(data instanceof ByteBuffer)) + throw new GdxRuntimeException("Can't use " + data.getClass().getName() + + " with this method. Use ByteBuffer. Blame LWJGL"); GL13.glCompressedTexImage2D(target, level, internalformat, width, height, border, (ByteBuffer)data); } public final void glCompressedTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, int format, int imageSize, Buffer data) { - if( !(data instanceof ByteBuffer) ) - throw new GdxRuntimeException( "Can't use " + data.getClass().getName() + " with this method. Use ByteBuffer. Blame LWJGL" ); + if (!(data instanceof ByteBuffer)) + throw new GdxRuntimeException("Can't use " + data.getClass().getName() + + " with this method. Use ByteBuffer. Blame LWJGL"); GL13.glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, (ByteBuffer)data); } @@ -259,17 +261,16 @@ class LwjglGL10 implements GL10 { GL11.glDrawArrays(mode, first, count); } - public final void glDrawElements (int mode, int count, int type, Buffer indices) { - if( indices instanceof ShortBuffer && type == GL10.GL_UNSIGNED_SHORT ) + public final void glDrawElements (int mode, int count, int type, Buffer indices) { + if (indices instanceof ShortBuffer && type == GL10.GL_UNSIGNED_SHORT) GL11.glDrawElements(mode, (ShortBuffer)indices); - else - if( indices instanceof ByteBuffer && type == GL10.GL_UNSIGNED_SHORT ) - GL11.glDrawElements(mode, ((ByteBuffer)indices).asShortBuffer() ); // FIXME yay... - else - if( indices instanceof ByteBuffer && type == GL10.GL_UNSIGNED_BYTE ) + else if (indices instanceof ByteBuffer && type == GL10.GL_UNSIGNED_SHORT) + GL11.glDrawElements(mode, ((ByteBuffer)indices).asShortBuffer()); // FIXME yay... + else if (indices instanceof ByteBuffer && type == GL10.GL_UNSIGNED_BYTE) GL11.glDrawElements(mode, (ByteBuffer)indices); else - throw new GdxRuntimeException( "Can't use " + indices.getClass().getName() + " with this method. Use ShortBuffer or ByteBuffer instead. Blame LWJGL" ); + throw new GdxRuntimeException("Can't use " + indices.getClass().getName() + + " with this method. Use ShortBuffer or ByteBuffer instead. Blame LWJGL"); } public final void glEnable (int cap) { @@ -466,16 +467,15 @@ class LwjglGL10 implements GL10 { convertFixedToFloatbuffer(pointer, normalBuffer, stride); GL11.glNormalPointer(stride, normalBuffer); } else { - if( pointer instanceof FloatBuffer && type == GL11.GL_FLOAT ) + if (pointer instanceof FloatBuffer && type == GL11.GL_FLOAT) GL11.glNormalPointer(stride, (FloatBuffer)pointer); - else - if( pointer instanceof ByteBuffer && type == GL11.GL_FLOAT ) + else if (pointer instanceof ByteBuffer && type == GL11.GL_FLOAT) GL11.glNormalPointer(stride, ((ByteBuffer)pointer).asFloatBuffer()); + else if (pointer instanceof ByteBuffer && type == GL11.GL_BYTE) + GL11.glNormalPointer(stride, (ByteBuffer)pointer); else - if( pointer instanceof ByteBuffer && type == GL11.GL_BYTE ) - GL11.glNormalPointer( stride, (ByteBuffer)pointer ); - else - throw new GdxRuntimeException( "Can't use " + pointer.getClass().getName() + " with this method. GL10.GL_SHORT not supported. Use FloatBuffer instead. Blame LWJGL" ); + throw new GdxRuntimeException("Can't use " + pointer.getClass().getName() + + " with this method. GL10.GL_SHORT not supported. Use FloatBuffer instead. Blame LWJGL"); } } @@ -517,19 +517,17 @@ class LwjglGL10 implements GL10 { } public final void glReadPixels (int x, int y, int width, int height, int format, int type, Buffer pixels) { - if( pixels instanceof ByteBuffer ) - GL11.glReadPixels(x, y, width, height, format, type, (ByteBuffer)pixels ); + if (pixels instanceof ByteBuffer) + GL11.glReadPixels(x, y, width, height, format, type, (ByteBuffer)pixels); + else if (pixels instanceof ShortBuffer) + GL11.glReadPixels(x, y, width, height, format, type, (ShortBuffer)pixels); + else if (pixels instanceof IntBuffer) + GL11.glReadPixels(x, y, width, height, format, type, (IntBuffer)pixels); + else if (pixels instanceof FloatBuffer) + GL11.glReadPixels(x, y, width, height, format, type, (FloatBuffer)pixels); else - if( pixels instanceof ShortBuffer ) - GL11.glReadPixels(x, y, width, height, format, type, (ShortBuffer)pixels ); - else - if( pixels instanceof IntBuffer ) - GL11.glReadPixels(x, y, width, height, format, type, (IntBuffer)pixels ); - else - if( pixels instanceof FloatBuffer ) - GL11.glReadPixels(x, y, width, height, format, type, (FloatBuffer)pixels ); - else - throw new GdxRuntimeException( "Can't use " + pixels.getClass().getName() + " with this method. Use ByteBuffer, ShortBuffer, IntBuffer or FloatBuffer instead. Blame LWJGL" ); + throw new GdxRuntimeException("Can't use " + pixels.getClass().getName() + + " with this method. Use ByteBuffer, ShortBuffer, IntBuffer or FloatBuffer instead. Blame LWJGL"); } public final void glRotatef (float angle, float x, float y, float z) { @@ -580,20 +578,19 @@ class LwjglGL10 implements GL10 { if (type == GL10.GL_FIXED) { convertFixedToFloatbuffer(pointer, texCoordBuffer[activeTexture], stride); GL11.glTexCoordPointer(size, stride, texCoordBuffer[activeTexture]); - } else - if( pointer instanceof ShortBuffer && type == GL10.GL_SHORT ) - GL11.glTexCoordPointer(size, stride,(ShortBuffer)pointer ); - else - if( pointer instanceof ByteBuffer && type == GL10.GL_SHORT ) - GL11.glTexCoordPointer( size, stride, ((ByteBuffer)pointer).asShortBuffer() ); - else - if( pointer instanceof FloatBuffer && type == GL10.GL_FLOAT ) - GL11.glTexCoordPointer( size, stride, (FloatBuffer)pointer); - else - if( pointer instanceof ByteBuffer && type == GL10.GL_FLOAT ) - GL11.glTexCoordPointer( size, stride, ((ByteBuffer)pointer).asFloatBuffer() ); - else - throw new GdxRuntimeException( "Can't use " + pointer.getClass().getName() + " with this method. Use ShortBuffer or FloatBuffer or ByteBuffer instead with GL_FLOAT or GL_SHORT. GL_BYTE is not supported. Blame LWJGL" ); + } else if (pointer instanceof ShortBuffer && type == GL10.GL_SHORT) + GL11.glTexCoordPointer(size, stride, (ShortBuffer)pointer); + else if (pointer instanceof ByteBuffer && type == GL10.GL_SHORT) + GL11.glTexCoordPointer(size, stride, ((ByteBuffer)pointer).asShortBuffer()); + else if (pointer instanceof FloatBuffer && type == GL10.GL_FLOAT) + GL11.glTexCoordPointer(size, stride, (FloatBuffer)pointer); + else if (pointer instanceof ByteBuffer && type == GL10.GL_FLOAT) + GL11.glTexCoordPointer(size, stride, ((ByteBuffer)pointer).asFloatBuffer()); + else + throw new GdxRuntimeException( + "Can't use " + + pointer.getClass().getName() + + " with this method. Use ShortBuffer or FloatBuffer or ByteBuffer instead with GL_FLOAT or GL_SHORT. GL_BYTE is not supported. Blame LWJGL"); } public final void glTexEnvf (int target, int pname, float param) { @@ -618,23 +615,20 @@ class LwjglGL10 implements GL10 { public final void glTexImage2D (int target, int level, int internalformat, int width, int height, int border, int format, int type, Buffer pixels) { - - if( pixels instanceof ByteBuffer ) + + if (pixels instanceof ByteBuffer) GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, (ByteBuffer)pixels); - else - if( pixels instanceof ShortBuffer ) + else if (pixels instanceof ShortBuffer) GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, (ShortBuffer)pixels); - else - if( pixels instanceof IntBuffer ) + else if (pixels instanceof IntBuffer) GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, (IntBuffer)pixels); - else - if( pixels instanceof FloatBuffer ) + else if (pixels instanceof FloatBuffer) GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, (FloatBuffer)pixels); - else - if( pixels instanceof DoubleBuffer ) + else if (pixels instanceof DoubleBuffer) GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, (DoubleBuffer)pixels); else - throw new GdxRuntimeException( "Can't use " + pixels.getClass().getName() + " with this method. Use ByteBuffer, ShortBuffer, IntBuffer, FloatBuffer or DoubleBuffer instead. Blame LWJGL" ); + throw new GdxRuntimeException("Can't use " + pixels.getClass().getName() + + " with this method. Use ByteBuffer, ShortBuffer, IntBuffer, FloatBuffer or DoubleBuffer instead. Blame LWJGL"); } public final void glTexParameterf (int target, int pname, float param) { @@ -647,23 +641,20 @@ class LwjglGL10 implements GL10 { public final void glTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, Buffer pixels) { - if( pixels instanceof ByteBuffer ) - GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, (ByteBuffer)pixels); - else - if( pixels instanceof ShortBuffer ) + if (pixels instanceof ByteBuffer) + GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, (ByteBuffer)pixels); + else if (pixels instanceof ShortBuffer) GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, (ShortBuffer)pixels); - else - if( pixels instanceof IntBuffer ) + else if (pixels instanceof IntBuffer) GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, (IntBuffer)pixels); - else - if( pixels instanceof FloatBuffer ) + else if (pixels instanceof FloatBuffer) GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, (FloatBuffer)pixels); - else - if( pixels instanceof DoubleBuffer ) + else if (pixels instanceof DoubleBuffer) GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, (DoubleBuffer)pixels); else - throw new GdxRuntimeException( "Can't use " + pixels.getClass().getName() + " with this method. Use ByteBuffer, ShortBuffer, IntBuffer, FloatBuffer or DoubleBuffer instead. Blame LWJGL" ); - + throw new GdxRuntimeException("Can't use " + pixels.getClass().getName() + + " with this method. Use ByteBuffer, ShortBuffer, IntBuffer, FloatBuffer or DoubleBuffer instead. Blame LWJGL"); + } public final void glTranslatef (float x, float y, float z) { @@ -678,14 +669,13 @@ class LwjglGL10 implements GL10 { if (type == GL10.GL_FIXED) { convertFixedToFloatbuffer(pointer, vertexBuffer, stride); GL11.glVertexPointer(size, stride, vertexBuffer); - } else - if( pointer instanceof FloatBuffer && type == GL10.GL_FLOAT ) - GL11.glVertexPointer(size, stride, ((FloatBuffer)pointer)); - else - if( pointer instanceof ByteBuffer && type == GL10.GL_FLOAT ) - GL11.glVertexPointer(size, stride, ((ByteBuffer)pointer).asFloatBuffer()); - else - throw new GdxRuntimeException( "Can't use " + pointer.getClass().getName() + " with this method. Use FloatBuffer or ByteBuffers with GL10.GL_FLOAT instead. Blame LWJGL" ); + } else if (pointer instanceof FloatBuffer && type == GL10.GL_FLOAT) + GL11.glVertexPointer(size, stride, ((FloatBuffer)pointer)); + else if (pointer instanceof ByteBuffer && type == GL10.GL_FLOAT) + GL11.glVertexPointer(size, stride, ((ByteBuffer)pointer).asFloatBuffer()); + else + throw new GdxRuntimeException("Can't use " + pointer.getClass().getName() + + " with this method. Use FloatBuffer or ByteBuffers with GL10.GL_FLOAT instead. Blame LWJGL"); } public final void glViewport (int x, int y, int width, int height) { @@ -707,9 +697,8 @@ class LwjglGL10 implements GL10 { glFogfv(pname, tmp, 0); } - public final void glGenTextures (int n, int[] textures, int offset) - { - for( int i = offset; i < offset + n; i++ ) + public final void glGenTextures (int n, int[] textures, int offset) { + for (int i = offset; i < offset + n; i++) textures[i] = GL11.glGenTextures(); } diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglGL11.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglGL11.java index 6bc602777..48a5c382f 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglGL11.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglGL11.java @@ -83,13 +83,13 @@ public final class LwjglGL11 extends LwjglGL10 implements com.badlogic.gdx.graph public void glBufferData (int target, int size, Buffer data, int usage) { if (data instanceof ByteBuffer) - GL15.glBufferData(target,(ByteBuffer)data, usage); + GL15.glBufferData(target, (ByteBuffer)data, usage); else if (data instanceof IntBuffer) - GL15.glBufferData(target,(IntBuffer)data, usage); + GL15.glBufferData(target, (IntBuffer)data, usage); else if (data instanceof FloatBuffer) GL15.glBufferData(target, (FloatBuffer)data, usage); else if (data instanceof DoubleBuffer) - GL15.glBufferData(target,(DoubleBuffer)data, usage); + GL15.glBufferData(target, (DoubleBuffer)data, usage); else if (data instanceof ShortBuffer) // GL15.glBufferData(target, (ShortBuffer)data, usage); } @@ -136,7 +136,7 @@ public final class LwjglGL11 extends LwjglGL10 implements com.badlogic.gdx.graph } public void glGenBuffers (int n, int[] buffers, int offset) { - for( int i = offset; i < offset + n; i++ ) + for (int i = offset; i < offset + n; i++) buffers[offset] = GL15.glGenBuffers(); } @@ -153,7 +153,8 @@ public final class LwjglGL11 extends LwjglGL10 implements com.badlogic.gdx.graph } public void glGetBufferParameteriv (int target, int pname, int[] params, int offset) { - throw new UnsupportedOperationException("not implemented"); } + throw new UnsupportedOperationException("not implemented"); + } public void glGetBufferParameteriv (int target, int pname, IntBuffer params) { GL15.glGetBufferParameter(target, pname, params); diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglGL20.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglGL20.java index 8f89a87de..c3a809670 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglGL20.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglGL20.java @@ -143,12 +143,12 @@ final class LwjglGL20 implements com.badlogic.gdx.graphics.GL20 { public void glCompressedTexImage2D (int target, int level, int internalformat, int width, int height, int border, int imageSize, Buffer data) { - throw new GdxRuntimeException( "not implemented" ); + throw new GdxRuntimeException("not implemented"); } public void glCompressedTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, int format, int imageSize, Buffer data) { - throw new GdxRuntimeException( "not implemented" ); + throw new GdxRuntimeException("not implemented"); } public void glCopyTexImage2D (int target, int level, int internalformat, int x, int y, int width, int height, int border) { @@ -224,16 +224,15 @@ final class LwjglGL20 implements com.badlogic.gdx.graphics.GL20 { } public void glDrawElements (int mode, int count, int type, Buffer indices) { - if( indices instanceof ShortBuffer && type == GL10.GL_UNSIGNED_SHORT ) + if (indices instanceof ShortBuffer && type == GL10.GL_UNSIGNED_SHORT) GL11.glDrawElements(mode, (ShortBuffer)indices); - else - if( indices instanceof ByteBuffer && type == GL10.GL_UNSIGNED_SHORT ) - GL11.glDrawElements(mode, ((ByteBuffer)indices).asShortBuffer() ); // FIXME yay... - else - if( indices instanceof ByteBuffer && type == GL10.GL_UNSIGNED_BYTE ) + else if (indices instanceof ByteBuffer && type == GL10.GL_UNSIGNED_SHORT) + GL11.glDrawElements(mode, ((ByteBuffer)indices).asShortBuffer()); // FIXME yay... + else if (indices instanceof ByteBuffer && type == GL10.GL_UNSIGNED_BYTE) GL11.glDrawElements(mode, (ByteBuffer)indices); else - throw new GdxRuntimeException( "Can't use " + indices.getClass().getName() + " with this method. Use ShortBuffer or ByteBuffer instead. Blame LWJGL" ); + throw new GdxRuntimeException("Can't use " + indices.getClass().getName() + + " with this method. Use ShortBuffer or ByteBuffer instead. Blame LWJGL"); } public void glEnable (int cap) { @@ -457,19 +456,17 @@ final class LwjglGL20 implements com.badlogic.gdx.graphics.GL20 { } public void glReadPixels (int x, int y, int width, int height, int format, int type, Buffer pixels) { - if( pixels instanceof ByteBuffer ) - GL11.glReadPixels(x, y, width, height, format, type, (ByteBuffer)pixels ); - else - if( pixels instanceof ShortBuffer ) - GL11.glReadPixels(x, y, width, height, format, type, (ShortBuffer)pixels ); - else - if( pixels instanceof IntBuffer ) - GL11.glReadPixels(x, y, width, height, format, type, (IntBuffer)pixels ); + if (pixels instanceof ByteBuffer) + GL11.glReadPixels(x, y, width, height, format, type, (ByteBuffer)pixels); + else if (pixels instanceof ShortBuffer) + GL11.glReadPixels(x, y, width, height, format, type, (ShortBuffer)pixels); + else if (pixels instanceof IntBuffer) + GL11.glReadPixels(x, y, width, height, format, type, (IntBuffer)pixels); + else if (pixels instanceof FloatBuffer) + GL11.glReadPixels(x, y, width, height, format, type, (FloatBuffer)pixels); else - if( pixels instanceof FloatBuffer ) - GL11.glReadPixels(x, y, width, height, format, type, (FloatBuffer)pixels ); - else - throw new GdxRuntimeException( "Can't use " + pixels.getClass().getName() + " with this method. Use ByteBuffer, ShortBuffer, IntBuffer or FloatBuffer instead. Blame LWJGL" ); + throw new GdxRuntimeException("Can't use " + pixels.getClass().getName() + + " with this method. Use ByteBuffer, ShortBuffer, IntBuffer or FloatBuffer instead. Blame LWJGL"); } public void glReleaseShaderCompiler () { @@ -522,22 +519,19 @@ final class LwjglGL20 implements com.badlogic.gdx.graphics.GL20 { public void glTexImage2D (int target, int level, int internalformat, int width, int height, int border, int format, int type, Buffer pixels) { - if( pixels instanceof ByteBuffer ) + if (pixels instanceof ByteBuffer) GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, (ByteBuffer)pixels); - else - if( pixels instanceof ShortBuffer ) + else if (pixels instanceof ShortBuffer) GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, (ShortBuffer)pixels); - else - if( pixels instanceof IntBuffer ) + else if (pixels instanceof IntBuffer) GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, (IntBuffer)pixels); - else - if( pixels instanceof FloatBuffer ) + else if (pixels instanceof FloatBuffer) GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, (FloatBuffer)pixels); - else - if( pixels instanceof DoubleBuffer ) + else if (pixels instanceof DoubleBuffer) GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, (DoubleBuffer)pixels); else - throw new GdxRuntimeException( "Can't use " + pixels.getClass().getName() + " with this method. Use ByteBuffer, ShortBuffer, IntBuffer, FloatBuffer or DoubleBuffer instead. Blame LWJGL" ); + throw new GdxRuntimeException("Can't use " + pixels.getClass().getName() + + " with this method. Use ByteBuffer, ShortBuffer, IntBuffer, FloatBuffer or DoubleBuffer instead. Blame LWJGL"); } public void glTexParameterf (int target, int pname, float param) { @@ -558,22 +552,19 @@ final class LwjglGL20 implements com.badlogic.gdx.graphics.GL20 { public void glTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, Buffer pixels) { - if( pixels instanceof ByteBuffer ) - GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, (ByteBuffer)pixels); - else - if( pixels instanceof ShortBuffer ) + if (pixels instanceof ByteBuffer) + GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, (ByteBuffer)pixels); + else if (pixels instanceof ShortBuffer) GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, (ShortBuffer)pixels); - else - if( pixels instanceof IntBuffer ) + else if (pixels instanceof IntBuffer) GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, (IntBuffer)pixels); - else - if( pixels instanceof FloatBuffer ) + else if (pixels instanceof FloatBuffer) GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, (FloatBuffer)pixels); - else - if( pixels instanceof DoubleBuffer ) + else if (pixels instanceof DoubleBuffer) GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, (DoubleBuffer)pixels); else - throw new GdxRuntimeException( "Can't use " + pixels.getClass().getName() + " with this method. Use ByteBuffer, ShortBuffer, IntBuffer, FloatBuffer or DoubleBuffer instead. Blame LWJGL" ); + throw new GdxRuntimeException("Can't use " + pixels.getClass().getName() + + " with this method. Use ByteBuffer, ShortBuffer, IntBuffer, FloatBuffer or DoubleBuffer instead. Blame LWJGL"); } public void glUniform1f (int location, float x) { @@ -693,8 +684,8 @@ final class LwjglGL20 implements com.badlogic.gdx.graphics.GL20 { } public void glVertexAttribPointer (int indx, int size, int type, boolean normalized, int stride, Buffer ptr) { -// GL20.glVertexAttribPointer(indx, size, type, normalized, stride, BufferUtils.getOffset(ptr)); - throw new GdxRuntimeException( "not implemented" ); +// GL20.glVertexAttribPointer(indx, size, type, normalized, stride, BufferUtils.getOffset(ptr)); + throw new GdxRuntimeException("not implemented"); } public void glViewport (int x, int y, int width, int height) { diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglGraphics.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglGraphics.java index 753283c97..350213f66 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglGraphics.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglGraphics.java @@ -24,14 +24,14 @@ import com.badlogic.gdx.Graphics; import com.badlogic.gdx.RenderListener; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Font; +import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.GL11; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.GLCommon; import com.badlogic.gdx.graphics.Pixmap; -import com.badlogic.gdx.graphics.Texture; -import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.Pixmap.Format; +import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; @@ -174,7 +174,7 @@ public final class LwjglGraphics implements Graphics, RenderListener { deltaTime = (time - lastTime) / 1000000000.0f; lastTime = time; - if (time - frameStart >= 1000000000 ) { + if (time - frameStart >= 1000000000) { fps = frames; frames = 0; frameStart = time; @@ -219,8 +219,7 @@ public final class LwjglGraphics implements Graphics, RenderListener { return fps; } - @Override - public GLCommon getGLCommon() { + @Override public GLCommon getGLCommon () { return gl; } } diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglInput.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglInput.java index 771ce4d19..65b098a3e 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglInput.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglInput.java @@ -35,8 +35,7 @@ import com.badlogic.gdx.RenderListener; final class LwjglInput implements Input, RenderListener { String text; TextInputListener textListener; - @SuppressWarnings("unchecked") - private final ArrayList listeners = new ArrayList(); + @SuppressWarnings("unchecked") private final ArrayList listeners = new ArrayList(); public void addInputListener (InputListener listener) { listeners.add(listener); @@ -76,13 +75,12 @@ final class LwjglInput implements Input, RenderListener { } public boolean isKeyPressed (int key) { - return Keyboard.isKeyDown(getKeyCodeReverse( key )); + return Keyboard.isKeyDown(getKeyCodeReverse(key)); } public boolean isTouched () { boolean button = Mouse.isButtonDown(0) || Mouse.isButtonDown(1) || Mouse.isButtonDown(2); - if( button ) - System.out.println( "button!!"); + if (button) System.out.println("button!!"); return button; } @@ -166,7 +164,7 @@ final class LwjglInput implements Input, RenderListener { if (listeners.get(i).touchDragged(x, y, pointer)) return; } - public static int getKeyCode(int keyCode) { + public static int getKeyCode (int keyCode) { if (keyCode == Keyboard.KEY_0) return Input.Keys.KEYCODE_0; if (keyCode == Keyboard.KEY_1) return Input.Keys.KEYCODE_1; if (keyCode == Keyboard.KEY_2) return Input.Keys.KEYCODE_2; @@ -225,8 +223,8 @@ final class LwjglInput implements Input, RenderListener { if (keyCode == Keyboard.KEY_TAB) return Input.Keys.KEYCODE_TAB; return Input.Keys.KEYCODE_UNKNOWN; } - - public static int getKeyCodeReverse(int keyCode) { + + public static int getKeyCodeReverse (int keyCode) { if (keyCode == Input.Keys.KEYCODE_0) return Keyboard.KEY_0; if (keyCode == Input.Keys.KEYCODE_1) return Keyboard.KEY_1; if (keyCode == Input.Keys.KEYCODE_2) return Keyboard.KEY_2; @@ -268,7 +266,7 @@ final class LwjglInput implements Input, RenderListener { if (keyCode == Input.Keys.KEYCODE_BACKSLASH) return Keyboard.KEY_BACKSLASH; if (keyCode == Input.Keys.KEYCODE_COMMA) return Keyboard.KEY_COMMA; if (keyCode == Input.Keys.KEYCODE_DEL) return Keyboard.KEY_DELETE; - if (keyCode == Input.Keys.KEYCODE_DPAD_LEFT)return Keyboard.KEY_LEFT; + if (keyCode == Input.Keys.KEYCODE_DPAD_LEFT) return Keyboard.KEY_LEFT; if (keyCode == Input.Keys.KEYCODE_DPAD_RIGHT) return Keyboard.KEY_RIGHT; if (keyCode == Input.Keys.KEYCODE_DPAD_UP) return Keyboard.KEY_UP; if (keyCode == Input.Keys.KEYCODE_DPAD_DOWN) return Keyboard.KEY_DOWN; diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglPixmap.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglPixmap.java index 236b1d9d3..1099dbe6c 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglPixmap.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglPixmap.java @@ -20,10 +20,6 @@ import java.awt.Composite; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; - -import javax.imageio.ImageIO; import com.badlogic.gdx.graphics.Pixmap; @@ -42,35 +38,34 @@ final class LwjglPixmap implements Pixmap { LwjglPixmap (int width, int height, Pixmap.Format format) { int internalformat = getInternalFormat(format); pixmap = new BufferedImage(width, height, internalformat); - Graphics2D g = pixmap.createGraphics(); + Graphics2D g = pixmap.createGraphics(); g.setComposite(AlphaComposite.Clear); - g.setColor( new Color( 0, 0, 0, 0 ) ); + g.setColor(new Color(0, 0, 0, 0)); g.fillRect(0, 0, pixmap.getWidth(), pixmap.getHeight()); g.dispose(); composite = AlphaComposite.SrcOver; } LwjglPixmap (BufferedImage image) { - pixmap = convert( image ); + pixmap = convert(image); } - private BufferedImage convert( BufferedImage image ) - { - BufferedImage out = new BufferedImage( image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE ); - Graphics2D g = out.createGraphics(); + private BufferedImage convert (BufferedImage image) { + BufferedImage out = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE); + Graphics2D g = out.createGraphics(); g.setComposite(AlphaComposite.Clear); g.fillRect(0, 0, image.getWidth(), image.getHeight()); g.setComposite(AlphaComposite.SrcOver); g.drawImage(image, 0, 0, null); - g.dispose(); + g.dispose(); return out; } - + private int getInternalFormat (Pixmap.Format format) { -// if (format == Pixmap.Format.RGBA4444 || format == Pixmap.Format.RGBA8888 || format == Pixmap.Format.RGB565) - return BufferedImage.TYPE_4BYTE_ABGR; -// else -// return BufferedImage.TYPE_BYTE_GRAY; +// if (format == Pixmap.Format.RGBA4444 || format == Pixmap.Format.RGBA8888 || format == Pixmap.Format.RGB565) + return BufferedImage.TYPE_4BYTE_ABGR; +// else +// return BufferedImage.TYPE_BYTE_GRAY; } public void drawCircle (int x, int y, int radius) { diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglTexture.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglTexture.java index db02b21a7..7530656c4 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglTexture.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/LwjglTexture.java @@ -13,13 +13,11 @@ package com.badlogic.gdx.backends.desktop; -import java.awt.AlphaComposite; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; -import java.nio.ByteOrder; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; @@ -31,8 +29,8 @@ import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; /** - * I apologize for this class. It is a big fucking mess which can be attributed to the late hour - * i created this piece of shit in. Please take my apologize. It is slow. It is ugly. It is aids. + * I apologize for this class. It is a big fucking mess which can be attributed to the late hour i created this piece of shit in. + * Please take my apologize. It is slow. It is ugly. It is aids. * * @author badlogicgames@gmail.com * @@ -51,7 +49,7 @@ final class LwjglTexture implements Texture { public static int textures = 0; static private ByteBuffer imageBuffer; - + /** * Create a new texture */ @@ -59,8 +57,8 @@ final class LwjglTexture implements Texture { TextureWrap vWrap, boolean managed) { this.isManaged = managed; this.isMipMapped = minFilter == TextureFilter.MipMap; - BufferedImage image = (BufferedImage)Gdx.graphics.newPixmap( file ).getNativePixmap(); - loadMipMap( image ); + BufferedImage image = (BufferedImage)Gdx.graphics.newPixmap(file).getNativePixmap(); + loadMipMap(image); bind(); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, getTextureFilter(minFilter)); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, getTextureFilter(maxFilter)); @@ -73,9 +71,9 @@ final class LwjglTexture implements Texture { boolean managed) { this.isManaged = managed; this.isMipMapped = minFilter == TextureFilter.MipMap; - BufferedImage img = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_4BYTE_ABGR ); + BufferedImage img = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_4BYTE_ABGR); loadMipMap(img); - this.draw( Gdx.graphics.newPixmap(image), 0, 0 ); + this.draw(Gdx.graphics.newPixmap(image), 0, 0); bind(); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, getTextureFilter(minFilter)); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, getTextureFilter(maxFilter)); @@ -101,54 +99,49 @@ final class LwjglTexture implements Texture { textures++; } - private ByteBuffer toByteBuffer( BufferedImage image ) - { + private ByteBuffer toByteBuffer (BufferedImage image) { try { - imageBuffer = BitmapDecoder.decode( image ); + imageBuffer = BitmapDecoder.decode(image); return imageBuffer; - } catch (IOException e) - { - throw new GdxRuntimeException( "Couldn't decode image", e ); + } catch (IOException e) { + throw new GdxRuntimeException("Couldn't decode image", e); } } - - private BufferedImage scaleDown( BufferedImage image ) - { - BufferedImage scaled = new BufferedImage( image.getWidth() / 2, image.getHeight() / 2, BufferedImage.TYPE_4BYTE_ABGR_PRE ); + + private BufferedImage scaleDown (BufferedImage image) { + BufferedImage scaled = new BufferedImage(image.getWidth() / 2, image.getHeight() / 2, BufferedImage.TYPE_4BYTE_ABGR_PRE); Graphics2D g = scaled.createGraphics(); - g.drawImage( image, 0, 0, scaled.getWidth(), scaled.getHeight(), null ); //FIXME replace with something that looks actually like a scaled image... + g.drawImage(image, 0, 0, scaled.getWidth(), scaled.getHeight(), null); // FIXME replace with something that looks actually +// like a scaled image... g.dispose(); return scaled; } - - private void loadMipMap( BufferedImage image ) - { + + private void loadMipMap (BufferedImage image) { int level = 0; int height = image.getHeight(); int width = image.getWidth(); texWidth = width; texHeight = height; textureID = GL11.glGenTextures(); - GL11.glBindTexture( GL11.GL_TEXTURE_2D, textureID ); + GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID); - while(height >= 1 || width >= 1 && level < 4 ) { - ByteBuffer imageBuffer = toByteBuffer( image ); - GL11.glTexImage2D(GL11.GL_TEXTURE_2D, level, GL11.GL_RGBA8, width, height, 0, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE, imageBuffer); - if(height == 1 || width == 1 || isMipMapped == false ) - { + while (height >= 1 || width >= 1 && level < 4) { + ByteBuffer imageBuffer = toByteBuffer(image); + GL11.glTexImage2D(GL11.GL_TEXTURE_2D, level, GL11.GL_RGBA8, width, height, 0, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE, + imageBuffer); + if (height == 1 || width == 1 || isMipMapped == false) { break; } level++; - if( height > 1 ) - height /= 2; - if( width > 1 ) - width /= 2; + if (height > 1) height /= 2; + if (width > 1) width /= 2; - image = scaleDown( image ); - } + image = scaleDown(image); + } } - + private int getTextureFilter (TextureFilter filter) { if (filter == TextureFilter.Linear) return GL11.GL_LINEAR; @@ -189,29 +182,24 @@ final class LwjglTexture implements Texture { public void draw (Pixmap pixmap, int x, int y) { if (isManaged) throw new GdxRuntimeException("Can't draw to a managed texture"); BufferedImage image = (BufferedImage)pixmap.getNativePixmap(); - + int level = 0; int height = image.getHeight(); int width = image.getWidth(); bind(); - while(height >= 1 || width >= 1 && level < 4 ) { - ByteBuffer imageBuffer = toByteBuffer( image ); - GL11.glTexSubImage2D(GL11.GL_TEXTURE_2D, level, x, y, width, height, GL11.GL_RGBA, - GL11.GL_UNSIGNED_BYTE, imageBuffer); - if(height == 1 || width == 1 || isMipMapped == false ) - { + while (height >= 1 || width >= 1 && level < 4) { + ByteBuffer imageBuffer = toByteBuffer(image); + GL11.glTexSubImage2D(GL11.GL_TEXTURE_2D, level, x, y, width, height, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, imageBuffer); + if (height == 1 || width == 1 || isMipMapped == false) { break; } level++; - if( height > 1 ) - height /= 2; - if( width > 1 ) - width /= 2; - - image = scaleDown( image ); - } - + if (height > 1) height /= 2; + if (width > 1) width /= 2; + + image = scaleDown(image); + } } diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/PNGDecoder.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/PNGDecoder.java index 5e4687f98..11f4753be 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/PNGDecoder.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/PNGDecoder.java @@ -64,8 +64,7 @@ class PNGDecoder { private static final int PLTE = 0x504C5445; private static final int tRNS = 0x74524E53; private static final int IDAT = 0x49444154; - @SuppressWarnings("unused") - private static final int IEND = 0x49454E44; + @SuppressWarnings("unused") private static final int IEND = 0x49454E44; private static final byte COLOR_GREYSCALE = 0; private static final byte COLOR_TRUECOLOR = 2; @@ -546,7 +545,7 @@ class PNGDecoder { } } - private void unfilterUp (byte[] curLine, byte[] prevLine) { + private void unfilterUp (byte[] curLine, byte[] prevLine) { for (int i = 1, n = curLine.length; i < n; ++i) { curLine[i] += prevLine[i]; } diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/TextureDataSource.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/TextureDataSource.java index 43829adf6..57d3b0f11 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/TextureDataSource.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/desktop/TextureDataSource.java @@ -1,32 +1,25 @@ /* * Copyright (c) 2008-2010, Matthias Mann - * + * * 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 Matthias Mann 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. + * + * 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 Matthias Mann nor + * the names of its contributors may be used to endorse or promote products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, + * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.badlogic.gdx.backends.desktop; import java.awt.image.BufferedImage; @@ -39,49 +32,49 @@ import java.nio.ByteOrder; import java.nio.IntBuffer; /** - * + * * @author Matthias Mann */ public class TextureDataSource { - private final BufferedImage img; + private final BufferedImage img; + + public TextureDataSource (BufferedImage img) { + this.img = img; + } - public TextureDataSource(BufferedImage img) { - this.img = img; - } + public int getWidth () { + return img.getWidth(); + } - public int getWidth() { - return img.getWidth(); - } + public int getHeight () { + return img.getHeight(); + } - public int getHeight() { - return img.getHeight(); - } + public void decode (ByteBuffer buffer) throws IOException { + int imgWidth = img.getWidth(); + int imgHeight = img.getHeight(); - public void decode(ByteBuffer buffer) throws IOException { - int imgWidth = img.getWidth(); - int imgHeight = img.getHeight(); + ByteBuffer bb = buffer.slice(); + bb.order(ByteOrder.LITTLE_ENDIAN); + IntBuffer ib = bb.asIntBuffer(); - ByteBuffer bb = buffer.slice(); - bb.order(ByteOrder.LITTLE_ENDIAN); - IntBuffer ib = bb.asIntBuffer(); + Raster r = img.getRaster(); + if (img.getType() == BufferedImage.TYPE_INT_ARGB) { + ib.put(((DataBufferInt)r.getDataBuffer()).getData(), 0, imgWidth * imgHeight); + } else { + // same as image.getRGB() without allocating a large int[] + ColorModel cm = img.getColorModel(); + Object data = r.getDataElements(0, 0, null); + for (int y = 0; y < imgHeight; y++) { + for (int x = 0; x < imgWidth; x++) { + int color = cm.getRGB(r.getDataElements(x, y, data)); + ib.put(color); + } + } + } - Raster r = img.getRaster(); - if(img.getType() == BufferedImage.TYPE_INT_ARGB) { - ib.put(((DataBufferInt)r.getDataBuffer()).getData(), 0, imgWidth*imgHeight); - } else { - // same as image.getRGB() without allocating a large int[] - ColorModel cm = img.getColorModel(); - Object data = r.getDataElements(0, 0, null); - for(int y=0 ; y * @version $Revision$ */ package com.badlogic.gdx.backends.desktop; +import static org.lwjgl.opengl.ARBBufferObject.*; +import static org.lwjgl.opengl.ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB; +import static org.lwjgl.opengl.GL11.*; + import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; @@ -52,27 +46,21 @@ import org.lwjgl.opengl.Display; import org.lwjgl.opengl.DisplayMode; import org.lwjgl.opengl.GLContext; -import static org.lwjgl.opengl.ARBBufferObject.*; -import static org.lwjgl.opengl.ARBVertexBufferObject.*; -import static org.lwjgl.opengl.GL11.*; - public final class VBOTest { static { try { - //find first display mode that allows us 640*480*16 + // find first display mode that allows us 640*480*16 int mode = -1; DisplayMode[] modes = Display.getAvailableDisplayModes(); - for ( int i = 0; i < modes.length; i++ ) { - if ( modes[i].getWidth() == 640 - && modes[i].getHeight() == 480 - && modes[i].getBitsPerPixel() >= 16 ) { + for (int i = 0; i < modes.length; i++) { + if (modes[i].getWidth() == 640 && modes[i].getHeight() == 480 && modes[i].getBitsPerPixel() >= 16) { mode = i; break; } } - if ( mode != -1 ) { - //select above found displaymode + if (mode != -1) { + // select above found displaymode System.out.println("Setting display mode to " + modes[mode]); Display.setDisplayMode(modes[mode]); System.out.println("Created display."); @@ -106,16 +94,15 @@ public final class VBOTest { private static ByteBuffer mapped_buffer; private static FloatBuffer mapped_float_buffer; - public static void main(String[] arguments) { + public static void main (String[] arguments) { try { init(); - while ( !finished ) { + while (!finished) { Display.update(); - if ( !Display.isVisible() ) + if (!Display.isVisible()) Thread.sleep(200); - else if ( Display.isCloseRequested() ) - System.exit(0); + else if (Display.isCloseRequested()) System.exit(0); mainLoop(); render(); @@ -131,23 +118,19 @@ public final class VBOTest { /** * All calculations are done in here */ - private static void mainLoop() { + private static void mainLoop () { angle += 1f; - if ( angle > 360.0f ) - angle = 0.0f; + if (angle > 360.0f) angle = 0.0f; - if ( Mouse.getDX() != 0 || Mouse.getDY() != 0 || Mouse.getDWheel() != 0 ) + if (Mouse.getDX() != 0 || Mouse.getDY() != 0 || Mouse.getDWheel() != 0) System.out.println("Mouse moved " + Mouse.getDX() + " " + Mouse.getDY() + " " + Mouse.getDWheel()); - for ( int i = 0; i < Mouse.getButtonCount(); i++ ) - if ( Mouse.isButtonDown(i) ) - System.out.println("Button " + i + " down"); - if ( Keyboard.isKeyDown(Keyboard.KEY_ESCAPE) ) - finished = true; - for ( int i = 0; i < Keyboard.getNumKeyboardEvents(); i++ ) { + for (int i = 0; i < Mouse.getButtonCount(); i++) + if (Mouse.isButtonDown(i)) System.out.println("Button " + i + " down"); + if (Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) finished = true; + for (int i = 0; i < Keyboard.getNumKeyboardEvents(); i++) { Keyboard.next(); - if ( Keyboard.getEventKey() == Keyboard.KEY_ESCAPE && Keyboard.getEventKeyState() ) - finished = true; - if ( Keyboard.getEventKey() == Keyboard.KEY_T && Keyboard.getEventKeyState() ) + if (Keyboard.getEventKey() == Keyboard.KEY_ESCAPE && Keyboard.getEventKeyState()) finished = true; + if (Keyboard.getEventKey() == Keyboard.KEY_T && Keyboard.getEventKeyState()) System.out.println("Current time: " + Sys.getTime()); } } @@ -155,39 +138,36 @@ public final class VBOTest { /** * All rendering is done in here */ - private static void render() { + private static void render () { glClear(GL_COLOR_BUFFER_BIT); glPushMatrix(); glTranslatef(Display.getDisplayMode().getWidth() / 2, Display.getDisplayMode().getHeight() / 2, 0.0f); glRotatef(angle, 0, 0, 1.0f); - ByteBuffer new_mapped_buffer = glMapBufferARB(GL_ARRAY_BUFFER_ARB, - GL_WRITE_ONLY_ARB, - mapped_buffer); - if ( new_mapped_buffer != mapped_buffer ) + ByteBuffer new_mapped_buffer = glMapBufferARB(GL_ARRAY_BUFFER_ARB, GL_WRITE_ONLY_ARB, mapped_buffer); + if (new_mapped_buffer != mapped_buffer) mapped_float_buffer = new_mapped_buffer.order(ByteOrder.nativeOrder()).asFloatBuffer(); mapped_buffer = new_mapped_buffer; mapped_float_buffer.rewind(); vertices.rewind(); mapped_float_buffer.put(vertices); - if ( glUnmapBufferARB(GL_ARRAY_BUFFER_ARB) ) - glDrawArrays(GL_QUADS, 0, 4); + if (glUnmapBufferARB(GL_ARRAY_BUFFER_ARB)) glDrawArrays(GL_QUADS, 0, 4); glPopMatrix(); } /** * Initialize */ - private static void init() throws Exception { + private static void init () throws Exception { System.out.println("Timer resolution: " + Sys.getTimerResolution()); // Go into orthographic projection mode. glMatrixMode(GL_PROJECTION); glLoadIdentity(); - glOrtho( 0, Display.getDisplayMode().getWidth(), 0, Display.getDisplayMode().getHeight(), -1, 1 ); -// GLU.gluOrtho2D(0, Display.getDisplayMode().getWidth(), 0, Display.getDisplayMode().getHeight()); + glOrtho(0, Display.getDisplayMode().getWidth(), 0, Display.getDisplayMode().getHeight(), -1, 1); +// GLU.gluOrtho2D(0, Display.getDisplayMode().getWidth(), 0, Display.getDisplayMode().getHeight()); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glViewport(0, 0, Display.getDisplayMode().getWidth(), Display.getDisplayMode().getHeight()); - if ( !GLContext.getCapabilities().GL_ARB_vertex_buffer_object ) { + if (!GLContext.getCapabilities().GL_ARB_vertex_buffer_object) { System.out.println("ARB VBO not supported!"); System.exit(1); } @@ -203,7 +183,7 @@ public final class VBOTest { /** * Cleanup */ - private static void cleanup() { + private static void cleanup () { glDeleteBuffersARB(buffer_id); Display.destroy(); } diff --git a/demos/helloworld/gdx-helloworld-android/src/com/badlogic/gdx/GDXHelloWorld.java b/demos/helloworld/gdx-helloworld-android/src/com/badlogic/gdx/GDXHelloWorld.java index d0784b7a6..a8585fce9 100644 --- a/demos/helloworld/gdx-helloworld-android/src/com/badlogic/gdx/GDXHelloWorld.java +++ b/demos/helloworld/gdx-helloworld-android/src/com/badlogic/gdx/GDXHelloWorld.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; @@ -20,12 +18,10 @@ import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; import com.badlogic.gdx.helloworld.HelloWorld; -public class GDXHelloWorld extends AndroidApplication -{ - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - initialize( false ); - getGraphics().setRenderListener( new HelloWorld() ); - } +public class GDXHelloWorld extends AndroidApplication { + @Override public void onCreate (Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + initialize(false); + getGraphics().setRenderListener(new HelloWorld()); + } } diff --git a/demos/helloworld/gdx-helloworld/src/com/badlogic/gdx/helloworld/HelloWorld.java b/demos/helloworld/gdx-helloworld/src/com/badlogic/gdx/helloworld/HelloWorld.java index 76b02fb70..cf19f4051 100644 --- a/demos/helloworld/gdx-helloworld/src/com/badlogic/gdx/helloworld/HelloWorld.java +++ b/demos/helloworld/gdx-helloworld/src/com/badlogic/gdx/helloworld/HelloWorld.java @@ -1,84 +1,71 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.helloworld; +import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.RenderListener; -import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Font; +import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.SpriteBatch; import com.badlogic.gdx.graphics.Texture; -import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; import com.badlogic.gdx.math.Vector2; - -public class HelloWorld implements RenderListener -{ +public class HelloWorld implements RenderListener { boolean initialized = false; SpriteBatch spriteBatch; Texture texture; Font font; - Vector2 textPosition = new Vector2( 100, 100); - Vector2 textDirection = new Vector2( 1, 1 ); + Vector2 textPosition = new Vector2(100, 100); + Vector2 textDirection = new Vector2(1, 1); + + @Override public void dispose () { - @Override - public void dispose( ) - { - } - @Override - public void render( ) - { + @Override public void render () { int centerX = Gdx.graphics.getWidth() / 2; int centerY = Gdx.graphics.getHeight() / 2; - - Gdx.graphics.getGL10().glClear( GL10.GL_COLOR_BUFFER_BIT ); - - if( textPosition.x < 0 || textPosition.x > Gdx.graphics.getWidth() ) - textDirection.x = -textDirection.x; - if( textPosition.y < 0 || textPosition.y > Gdx.graphics.getHeight() ) - textDirection.y = -textDirection.y; - - textPosition.add( textDirection.tmp().mul( Gdx.graphics.getDeltaTime() ).mul(60) ); - - spriteBatch.begin(); - spriteBatch.draw( texture, centerX - texture.getWidth() / 2, centerY + texture.getHeight() / 2, 0, 0, texture.getWidth(), texture.getHeight(), Color.WHITE ); - spriteBatch.drawText( font, "Hello World!", (int)textPosition.x, (int)textPosition.y, Color.RED ); + + Gdx.graphics.getGL10().glClear(GL10.GL_COLOR_BUFFER_BIT); + + if (textPosition.x < 0 || textPosition.x > Gdx.graphics.getWidth()) textDirection.x = -textDirection.x; + if (textPosition.y < 0 || textPosition.y > Gdx.graphics.getHeight()) textDirection.y = -textDirection.y; + + textPosition.add(textDirection.tmp().mul(Gdx.graphics.getDeltaTime()).mul(60)); + + spriteBatch.begin(); + spriteBatch.draw(texture, centerX - texture.getWidth() / 2, centerY + texture.getHeight() / 2, 0, 0, texture.getWidth(), + texture.getHeight(), Color.WHITE); + spriteBatch.drawText(font, "Hello World!", (int)textPosition.x, (int)textPosition.y, Color.RED); spriteBatch.end(); } - @Override - public void surfaceChanged(int width, int height) - { - + @Override public void surfaceChanged (int width, int height) { + } - @Override - public void surfaceCreated( ) - { - if( !initialized ) - { - font = Gdx.graphics.newFont( "Arial", 32, FontStyle.Plain); - texture = Gdx.graphics.newTexture( Gdx.files.getFileHandle( "data/badlogic.jpg", FileType.Internal ), TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); - spriteBatch = new SpriteBatch( ); + @Override public void surfaceCreated () { + if (!initialized) { + font = Gdx.graphics.newFont("Arial", 32, FontStyle.Plain); + texture = Gdx.graphics.newTexture(Gdx.files.getFileHandle("data/badlogic.jpg", FileType.Internal), TextureFilter.MipMap, + TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); + spriteBatch = new SpriteBatch(); } - } + } } diff --git a/demos/helloworld/gdx-helloworld/src/com/badlogic/gdx/helloworld/HelloWorldDesktop.java b/demos/helloworld/gdx-helloworld/src/com/badlogic/gdx/helloworld/HelloWorldDesktop.java index 3ec03bf22..adc595560 100644 --- a/demos/helloworld/gdx-helloworld/src/com/badlogic/gdx/helloworld/HelloWorldDesktop.java +++ b/demos/helloworld/gdx-helloworld/src/com/badlogic/gdx/helloworld/HelloWorldDesktop.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.helloworld; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class HelloWorldDesktop -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Hello World", 480, 320, false ); - app.getGraphics().setRenderListener( new HelloWorld() ); +public class HelloWorldDesktop { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Hello World", 480, 320, false); + app.getGraphics().setRenderListener(new HelloWorld()); } } diff --git a/demos/invaders/gdx-invaders-android/src/com/badlogic/gdxinvaders/GdxInvadersAndroid.java b/demos/invaders/gdx-invaders-android/src/com/badlogic/gdxinvaders/GdxInvadersAndroid.java index a39363a2c..65b2a2d80 100644 --- a/demos/invaders/gdx-invaders-android/src/com/badlogic/gdxinvaders/GdxInvadersAndroid.java +++ b/demos/invaders/gdx-invaders-android/src/com/badlogic/gdxinvaders/GdxInvadersAndroid.java @@ -1,3 +1,4 @@ + package com.badlogic.gdxinvaders; import android.content.pm.ActivityInfo; @@ -6,13 +7,11 @@ import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; public class GdxInvadersAndroid extends AndroidApplication { - /** Called when the activity is first created. */ - @Override - public void onCreate(Bundle savedInstanceState) - { - super.onCreate(savedInstanceState); - setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); - initialize(false, 20); - getGraphics().setRenderListener(new GdxInvaders()); - } -} \ No newline at end of file + /** Called when the activity is first created. */ + @Override public void onCreate (Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); + initialize(false, 20); + getGraphics().setRenderListener(new GdxInvaders()); + } +} diff --git a/demos/invaders/gdx-invaders-applet/src/com/badlogic/gdxinvaders/GdxInvadersApplet.java b/demos/invaders/gdx-invaders-applet/src/com/badlogic/gdxinvaders/GdxInvadersApplet.java index 33704ebfd..94ee7fd21 100644 --- a/demos/invaders/gdx-invaders-applet/src/com/badlogic/gdxinvaders/GdxInvadersApplet.java +++ b/demos/invaders/gdx-invaders-applet/src/com/badlogic/gdxinvaders/GdxInvadersApplet.java @@ -1,31 +1,27 @@ /******************************************************************************* - * Copyright 2010 Mario Zechner (contact@badlogicgames.com) + * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdxinvaders; import java.applet.Applet; import com.badlogic.gdx.backends.applet.AppletApplication; -public class GdxInvadersApplet extends Applet -{ +public class GdxInvadersApplet extends Applet { private static final long serialVersionUID = -2444740109586326922L; - public void init() - { - AppletApplication app = new AppletApplication( this, false, false ); - app.getGraphics().setRenderListener( new GdxInvaders() ); + public void init () { + AppletApplication app = new AppletApplication(this, false, false); + app.getGraphics().setRenderListener(new GdxInvaders()); } } diff --git a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/GdxInvaders.java b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/GdxInvaders.java index 2d816385d..ec8779431 100644 --- a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/GdxInvaders.java +++ b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/GdxInvaders.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdxinvaders; import com.badlogic.gdx.Application; @@ -25,68 +23,56 @@ import com.badlogic.gdxinvaders.screens.GameOver; import com.badlogic.gdxinvaders.screens.MainMenu; import com.badlogic.gdxinvaders.screens.Screen; -public class GdxInvaders implements RenderListener -{ +public class GdxInvaders implements RenderListener { /** flag indicating whether we were initialized already **/ private boolean isInitialized = false; - + /** the current screen **/ private Screen screen; - - @Override - public void dispose() - { + + @Override public void dispose () { } - @Override - public void render() - { + @Override public void render () { Application app = Gdx.app; - + // update the screen screen.update(app); - + // render the screen screen.render(app); - - // when the screen is done we change to the + + // when the screen is done we change to the // next screen - if( screen.isDone() ) - { + if (screen.isDone()) { // dispose the current screen screen.dispose(); - + // if this screen is a main menu screen we switch to // the game loop - if( screen instanceof MainMenu ) - screen = new GameLoop( app ); + if (screen instanceof MainMenu) + screen = new GameLoop(app); else // if this screen is a game loop screen we switch to the // game over screen - if( screen instanceof GameLoop ) - screen = new GameOver( app ); - else + if (screen instanceof GameLoop) + screen = new GameOver(app); + else // if this screen is a game over screen we switch to the // main menu screen - if( screen instanceof GameOver ) - screen = new MainMenu(app); + if (screen instanceof GameOver) screen = new MainMenu(app); } } - @Override - public void surfaceChanged(int width, int height) - { + @Override public void surfaceChanged (int width, int height) { } - @Override - public void surfaceCreated( ) - { - if( !isInitialized ) - { + @Override public void surfaceCreated () { + if (!isInitialized) { screen = new MainMenu(Gdx.app); - Music music = Gdx.audio.newMusic( Gdx.files.getFileHandle( "data/8.12.mp3", FileType.Internal ) ); + Music music = Gdx.audio.newMusic(Gdx.files.getFileHandle("data/8.12.mp3", FileType.Internal)); music.setLooping(true); music.play(); isInitialized = true; diff --git a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/GdxInvadersDesktop.java b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/GdxInvadersDesktop.java index edeaf4fec..6e63b1242 100644 --- a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/GdxInvadersDesktop.java +++ b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/GdxInvadersDesktop.java @@ -1,33 +1,28 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdxinvaders; import com.badlogic.gdx.backends.desktop.JoglApplication; /** - * Entry point for desktop version of Gdx Invaders. Constructs a JoglApplication - * and registers the renderer. + * Entry point for desktop version of Gdx Invaders. Constructs a JoglApplication and registers the renderer. * @author mzechner - * + * */ -public class GdxInvadersDesktop -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Gdx Invaders", 480, 320, false ); - app.getGraphics().setRenderListener( new GdxInvaders() ); +public class GdxInvadersDesktop { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Gdx Invaders", 480, 320, false); + app.getGraphics().setRenderListener(new GdxInvaders()); } } diff --git a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/Renderer.java b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/Renderer.java index 6cbdb0b68..5a892d769 100644 --- a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/Renderer.java +++ b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/Renderer.java @@ -1,38 +1,36 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdxinvaders; import java.io.InputStream; import java.util.ArrayList; import com.badlogic.gdx.Application; -import com.badlogic.gdx.Graphics; import com.badlogic.gdx.Files.FileType; +import com.badlogic.gdx.Graphics; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Font; +import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.ModelLoader; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.SpriteBatch; import com.badlogic.gdx.graphics.Texture; -import com.badlogic.gdx.graphics.VertexAttribute; -import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; +import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; @@ -46,10 +44,9 @@ import com.badlogic.gdxinvaders.simulation.Simulation; /** * The renderer receives a simulation and renders it. * @author mzechner - * + * */ -public class Renderer -{ +public class Renderer { /** sprite batch to draw text **/ private SpriteBatch spriteBatch; /** the ship mesh **/ @@ -71,267 +68,249 @@ public class Renderer /** the explosion texture **/ private Texture explosionTexture; /** the font **/ - private Font font; + private Font font; /** the rotation angle of all invaders around y **/ - private float invaderAngle = 0; + private float invaderAngle = 0; /** status string **/ - private String status = ""; - /** keeping track of the last score so we don't constantly construct a new string **/ + private String status = ""; + /** keeping track of the last score so we don't constantly construct a new string **/ private int lastScore = 0; private int lastLives = 0; private int lastWave = 0; - + /** view and transform matrix for text rendering **/ private Matrix4 viewMatrix = new Matrix4(); private Matrix4 transformMatrix = new Matrix4(); - + /** perspective camera **/ private PerspectiveCamera camera; - - public Renderer( Application app ) - { - try - { + + public Renderer (Application app) { + try { spriteBatch = new SpriteBatch(); - - InputStream in = app.getFiles().readFile( "data/ship.obj", FileType.Internal ); - shipMesh = ModelLoader.loadObj( in, true ); + + InputStream in = app.getFiles().readFile("data/ship.obj", FileType.Internal); + shipMesh = ModelLoader.loadObj(in, true); in.close(); - - in = app.getFiles().readFile( "data/invader.obj", FileType.Internal ); - invaderMesh = ModelLoader.loadObj( in, true ); + + in = app.getFiles().readFile("data/invader.obj", FileType.Internal); + invaderMesh = ModelLoader.loadObj(in, true); in.close(); - - in = app.getFiles().readFile( "data/block.obj", FileType.Internal ); - blockMesh = ModelLoader.loadObj( in, true ); + + in = app.getFiles().readFile("data/block.obj", FileType.Internal); + blockMesh = ModelLoader.loadObj(in, true); in.close(); - - in = app.getFiles().readFile( "data/shot.obj", FileType.Internal ); - shotMesh = ModelLoader.loadObj( in, true ); + + in = app.getFiles().readFile("data/shot.obj", FileType.Internal); + shotMesh = ModelLoader.loadObj(in, true); in.close(); - - shipTexture = app.getGraphics().newTexture( app.getFiles().getFileHandle( "data/ship.png", FileType.Internal ), TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); - invaderTexture = app.getGraphics().newTexture( app.getFiles().getFileHandle( "data/invader.png", FileType.Internal ), TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); - backgroundTexture = app.getGraphics().newTexture( app.getFiles().getFileHandle( "data/planet.jpg", FileType.Internal ) , TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); - explosionTexture = app.getGraphics().newTexture( app.getFiles().getFileHandle( "data/explode.png", FileType.Internal ), TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); - - explosionMesh = new Mesh( true, false, 4 * 16, 0, - new VertexAttribute( Usage.Position, 3, "a_position"), - new VertexAttribute( Usage.TextureCoordinates, 2, "a_texCoord") ); - - float[] vertices = new float[4*16*(3+2)]; + + shipTexture = app.getGraphics().newTexture(app.getFiles().getFileHandle("data/ship.png", FileType.Internal), + TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); + invaderTexture = app.getGraphics().newTexture(app.getFiles().getFileHandle("data/invader.png", FileType.Internal), + TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); + backgroundTexture = app.getGraphics().newTexture(app.getFiles().getFileHandle("data/planet.jpg", FileType.Internal), + TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); + explosionTexture = app.getGraphics().newTexture(app.getFiles().getFileHandle("data/explode.png", FileType.Internal), + TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); + + explosionMesh = new Mesh(true, false, 4 * 16, 0, new VertexAttribute(Usage.Position, 3, "a_position"), + new VertexAttribute(Usage.TextureCoordinates, 2, "a_texCoord")); + + float[] vertices = new float[4 * 16 * (3 + 2)]; int idx = 0; - for( int row = 0; row < 4; row++ ) - { - for( int column = 0; column < 4; column++ ) - { + for (int row = 0; row < 4; row++) { + for (int column = 0; column < 4; column++) { vertices[idx++] = 1; vertices[idx++] = 1; vertices[idx++] = 0; vertices[idx++] = 0.25f + column * 0.25f; vertices[idx++] = 0 + row * 0.25f; - + vertices[idx++] = -1; vertices[idx++] = 1; vertices[idx++] = 0; vertices[idx++] = 0 + column * 0.25f; vertices[idx++] = 0 + row * 0.25f; - + vertices[idx++] = -1; vertices[idx++] = -1; vertices[idx++] = 0; vertices[idx++] = 0f + column * 0.25f; vertices[idx++] = 0.25f + row * 0.25f; - + vertices[idx++] = 1; vertices[idx++] = -1; vertices[idx++] = 0; vertices[idx++] = 0.25f + column * 0.25f; - vertices[idx++] = 0.25f + row * 0.25f; + vertices[idx++] = 0.25f + row * 0.25f; } - } - + } + explosionMesh.setVertices(vertices); - - font = app.getGraphics().newFont( app.getFiles().getFileHandle( "data/font.ttf", FileType.Internal), 10, FontStyle.Plain ); - + + font = app.getGraphics().newFont(app.getFiles().getFileHandle("data/font.ttf", FileType.Internal), 10, FontStyle.Plain); + camera = new PerspectiveCamera(); camera.setFov(67); - camera.setViewport( 480, 320 ); - } - catch( Exception ex ) - { + camera.setViewport(480, 320); + } catch (Exception ex) { ex.printStackTrace(); } } - - public void render( Application app, Simulation simulation ) - { + + public void render (Application app, Simulation simulation) { GL10 gl = app.getGraphics().getGL10(); - gl.glClear( GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT ); - gl.glViewport( 0, 0, app.getGraphics().getWidth(), app.getGraphics().getHeight() ); - - renderBackground( gl ); - - gl.glDisable( GL10.GL_DITHER ); - gl.glEnable( GL10.GL_DEPTH_TEST ); - gl.glEnable( GL10.GL_CULL_FACE ); - - setProjectionAndCamera( app.getGraphics(), simulation.ship, app ); - setLighting( gl ); - - gl.glEnable( GL10.GL_TEXTURE_2D ); - - renderShip( gl, simulation.ship, app ); - renderInvaders( gl, simulation.invaders ); - - gl.glDisable( GL10.GL_TEXTURE_2D ); - renderBlocks( gl, simulation.blocks ); - - gl.glDisable( GL10.GL_LIGHTING ); - renderShots( gl, simulation.shots ); - - gl.glEnable( GL10.GL_TEXTURE_2D ); - renderExplosions( gl, simulation.explosions ); - - gl.glDisable( GL10.GL_CULL_FACE ); - gl.glDisable( GL10.GL_DEPTH_TEST ); - + gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); + gl.glViewport(0, 0, app.getGraphics().getWidth(), app.getGraphics().getHeight()); + + renderBackground(gl); + + gl.glDisable(GL10.GL_DITHER); + gl.glEnable(GL10.GL_DEPTH_TEST); + gl.glEnable(GL10.GL_CULL_FACE); + + setProjectionAndCamera(app.getGraphics(), simulation.ship, app); + setLighting(gl); + + gl.glEnable(GL10.GL_TEXTURE_2D); + + renderShip(gl, simulation.ship, app); + renderInvaders(gl, simulation.invaders); + + gl.glDisable(GL10.GL_TEXTURE_2D); + renderBlocks(gl, simulation.blocks); + + gl.glDisable(GL10.GL_LIGHTING); + renderShots(gl, simulation.shots); + + gl.glEnable(GL10.GL_TEXTURE_2D); + renderExplosions(gl, simulation.explosions); + + gl.glDisable(GL10.GL_CULL_FACE); + gl.glDisable(GL10.GL_DEPTH_TEST); + spriteBatch.begin(viewMatrix, transformMatrix); - if( simulation.ship.lives != lastLives || simulation.score != lastScore || simulation.wave != lastWave ) - { + if (simulation.ship.lives != lastLives || simulation.score != lastScore || simulation.wave != lastWave) { status = "lives: " + simulation.ship.lives + " wave: " + simulation.wave + " score: " + simulation.score; lastLives = simulation.ship.lives; lastScore = simulation.score; lastWave = simulation.wave; } - spriteBatch.drawText( font, status, 0, 320, Color.WHITE ); + spriteBatch.drawText(font, status, 0, 320, Color.WHITE); spriteBatch.end(); - - invaderAngle+=app.getGraphics().getDeltaTime() * 90; - if( invaderAngle > 360 ) - invaderAngle -= 360; - } - - private void renderBackground( GL10 gl ) - { - viewMatrix.setToOrtho2D(0, 0, 400, 320 ); - spriteBatch.begin(viewMatrix, transformMatrix ); + + invaderAngle += app.getGraphics().getDeltaTime() * 90; + if (invaderAngle > 360) invaderAngle -= 360; + } + + private void renderBackground (GL10 gl) { + viewMatrix.setToOrtho2D(0, 0, 400, 320); + spriteBatch.begin(viewMatrix, transformMatrix); spriteBatch.disableBlending(); - spriteBatch.draw( backgroundTexture, 0, 320, 480, 320, 0, 0, 512, 512, Color.WHITE, false, false ); + spriteBatch.draw(backgroundTexture, 0, 320, 480, 320, 0, 0, 512, 512, Color.WHITE, false, false); spriteBatch.end(); } - - final Vector3 dir = new Vector3( ); - private void setProjectionAndCamera( Graphics graphics, Ship ship, Application app ) - { + + final Vector3 dir = new Vector3(); + + private void setProjectionAndCamera (Graphics graphics, Ship ship, Application app) { camera.getPosition().set(ship.position.x, 6, 2); - dir.set( ship.position.x, 0, -4 ).sub( camera.getPosition() ).nor(); + dir.set(ship.position.x, 0, -4).sub(camera.getPosition()).nor(); camera.getDirection().set(dir); - camera.update(); + camera.update(); GL10 gl = graphics.getGL10(); - gl.glMatrixMode( GL10.GL_PROJECTION ); - gl.glLoadMatrixf( camera.getCombinedMatrix().val, 0 ); - gl.glMatrixMode( GL10.GL_MODELVIEW ); - gl.glLoadIdentity(); + gl.glMatrixMode(GL10.GL_PROJECTION); + gl.glLoadMatrixf(camera.getCombinedMatrix().val, 0); + gl.glMatrixMode(GL10.GL_MODELVIEW); + gl.glLoadIdentity(); } - - float[] direction = { 1, 0.5f, 0, 0 }; - private void setLighting( GL10 gl ) - { - gl.glEnable( GL10.GL_LIGHTING ); - gl.glEnable( GL10.GL_LIGHT0 ); - gl.glLightfv( GL10.GL_LIGHT0, GL10.GL_POSITION, direction, 0 ); - gl.glEnable( GL10.GL_COLOR_MATERIAL ); + + float[] direction = {1, 0.5f, 0, 0}; + + private void setLighting (GL10 gl) { + gl.glEnable(GL10.GL_LIGHTING); + gl.glEnable(GL10.GL_LIGHT0); + gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, direction, 0); + gl.glEnable(GL10.GL_COLOR_MATERIAL); } - - private void renderShip( GL10 gl, Ship ship, Application app) - { - if( ship.isExploding ) - return; - + + private void renderShip (GL10 gl, Ship ship, Application app) { + if (ship.isExploding) return; + shipTexture.bind(); gl.glPushMatrix(); - gl.glTranslatef( ship.position.x, ship.position.y, ship.position.z ); - gl.glRotatef( 45 * (-app.getInput().getAccelerometerY() / 5), 0, 0, 1 ); - gl.glRotatef( 180, 0, 1, 0 ); + gl.glTranslatef(ship.position.x, ship.position.y, ship.position.z); + gl.glRotatef(45 * (-app.getInput().getAccelerometerY() / 5), 0, 0, 1); + gl.glRotatef(180, 0, 1, 0); shipMesh.render(GL10.GL_TRIANGLES); gl.glPopMatrix(); } - - private void renderInvaders( GL10 gl, ArrayList invaders ) - { + + private void renderInvaders (GL10 gl, ArrayList invaders) { invaderTexture.bind(); - for( int i = 0; i < invaders.size(); i++ ) - { + for (int i = 0; i < invaders.size(); i++) { Invader invader = invaders.get(i); gl.glPushMatrix(); - gl.glTranslatef( invader.position.x, invader.position.y, invader.position.z ); - gl.glRotatef( invaderAngle, 0, 1, 0 ); + gl.glTranslatef(invader.position.x, invader.position.y, invader.position.z); + gl.glRotatef(invaderAngle, 0, 1, 0); invaderMesh.render(GL10.GL_TRIANGLES); gl.glPopMatrix(); } } - - private void renderBlocks( GL10 gl, ArrayList blocks ) - { - gl.glEnable( GL10.GL_BLEND ); - gl.glBlendFunc( GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA ); - gl.glColor4f( 0.2f, 0.2f, 1, 0.7f ); - for( int i = 0; i < blocks.size(); i++ ) - { + + private void renderBlocks (GL10 gl, ArrayList blocks) { + gl.glEnable(GL10.GL_BLEND); + gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); + gl.glColor4f(0.2f, 0.2f, 1, 0.7f); + for (int i = 0; i < blocks.size(); i++) { Block block = blocks.get(i); gl.glPushMatrix(); - gl.glTranslatef( block.position.x, block.position.y, block.position.z ); + gl.glTranslatef(block.position.x, block.position.y, block.position.z); blockMesh.render(GL10.GL_TRIANGLES); gl.glPopMatrix(); } - gl.glColor4f( 1, 1, 1, 1 ); - gl.glDisable( GL10.GL_BLEND ); + gl.glColor4f(1, 1, 1, 1); + gl.glDisable(GL10.GL_BLEND); } - - private void renderShots( GL10 gl, ArrayList shots ) - { - gl.glColor4f( 1, 1, 0, 1 ); - for( int i = 0; i < shots.size(); i++ ) - { + + private void renderShots (GL10 gl, ArrayList shots) { + gl.glColor4f(1, 1, 0, 1); + for (int i = 0; i < shots.size(); i++) { Shot shot = shots.get(i); gl.glPushMatrix(); - gl.glTranslatef( shot.position.x, shot.position.y, shot.position.z ); + gl.glTranslatef(shot.position.x, shot.position.y, shot.position.z); shotMesh.render(GL10.GL_TRIANGLES); gl.glPopMatrix(); - } - gl.glColor4f( 1, 1, 1, 1 ); + } + gl.glColor4f(1, 1, 1, 1); } - - private void renderExplosions(GL10 gl, ArrayList explosions) - { - gl.glEnable( GL10.GL_BLEND ); - gl.glBlendFunc( GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA ); + + private void renderExplosions (GL10 gl, ArrayList explosions) { + gl.glEnable(GL10.GL_BLEND); + gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); explosionTexture.bind(); - for( int i = 0; i < explosions.size(); i++ ) - { + for (int i = 0; i < explosions.size(); i++) { Explosion explosion = explosions.get(i); gl.glPushMatrix(); - gl.glTranslatef( explosion.position.x, explosion.position.y, explosion.position.z ); + gl.glTranslatef(explosion.position.x, explosion.position.y, explosion.position.z); explosionMesh.render(GL10.GL_TRIANGLE_FAN, (int)((explosion.aliveTime / Explosion.EXPLOSION_LIVE_TIME) * 15) * 4, 4); gl.glPopMatrix(); - } - gl.glDisable( GL10.GL_BLEND ); + } + gl.glDisable(GL10.GL_BLEND); } - - public void dispose( ) - { + + public void dispose () { spriteBatch.dispose(); shipTexture.dispose(); invaderTexture.dispose(); backgroundTexture.dispose(); explosionTexture.dispose(); - font.dispose(); + font.dispose(); explosionMesh.dispose(); shipMesh.dispose(); invaderMesh.dispose(); shotMesh.dispose(); - blockMesh.dispose(); + blockMesh.dispose(); } } diff --git a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/screens/GameLoop.java b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/screens/GameLoop.java index d9611d41a..1b3953f75 100644 --- a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/screens/GameLoop.java +++ b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/screens/GameLoop.java @@ -1,23 +1,21 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdxinvaders.screens; import com.badlogic.gdx.Application; -import com.badlogic.gdx.Input; import com.badlogic.gdx.Files.FileType; +import com.badlogic.gdx.Input; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.GL10; @@ -25,8 +23,7 @@ import com.badlogic.gdxinvaders.Renderer; import com.badlogic.gdxinvaders.simulation.Simulation; import com.badlogic.gdxinvaders.simulation.SimulationListener; -public class GameLoop implements Screen, SimulationListener -{ +public class GameLoop implements Screen, SimulationListener { /** the simulation **/ private final Simulation simulation; /** the renderer **/ @@ -35,67 +32,50 @@ public class GameLoop implements Screen, SimulationListener private final Sound explosion; /** shot sound **/ private final Sound shot; - - public GameLoop( Application app ) - { - simulation = new Simulation( ); + + public GameLoop (Application app) { + simulation = new Simulation(); simulation.listener = this; - renderer = new Renderer( app ); - explosion = app.getAudio().newSound( app.getFiles().getFileHandle( "data/explosion.ogg", FileType.Internal ) ); - shot = app.getAudio().newSound( app.getFiles().getFileHandle( "data/shot.ogg", FileType.Internal ) ); + renderer = new Renderer(app); + explosion = app.getAudio().newSound(app.getFiles().getFileHandle("data/explosion.ogg", FileType.Internal)); + shot = app.getAudio().newSound(app.getFiles().getFileHandle("data/shot.ogg", FileType.Internal)); } - - @Override - public void dispose() - { + + @Override public void dispose () { renderer.dispose(); shot.dispose(); explosion.dispose(); } - @Override - public boolean isDone() - { + @Override public boolean isDone () { return simulation.ship.lives == 0; } - @Override - public void render(Application app) - { - app.getGraphics().getGL10().glClear( GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT ); - renderer.render( app, simulation ); + @Override public void render (Application app) { + app.getGraphics().getGL10().glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); + renderer.render(app, simulation); } - @Override - public void update(Application app) - { - simulation.update( app.getGraphics().getDeltaTime() ); - + @Override public void update (Application app) { + simulation.update(app.getGraphics().getDeltaTime()); + Input input = app.getInput(); - if( input.getAccelerometerY() < 0 ) - simulation.moveShipLeft( app.getGraphics().getDeltaTime(), Math.abs(input.getAccelerometerY()) / 10 ); + if (input.getAccelerometerY() < 0) + simulation.moveShipLeft(app.getGraphics().getDeltaTime(), Math.abs(input.getAccelerometerY()) / 10); else - simulation.moveShipRight( app.getGraphics().getDeltaTime(), Math.abs(input.getAccelerometerY()) / 10 ); - - if( input.isKeyPressed( Keys.KEYCODE_DPAD_LEFT ) ) - simulation.moveShipLeft( app.getGraphics().getDeltaTime(), 0.5f ); - if( input.isKeyPressed( Keys.KEYCODE_DPAD_RIGHT ) ) - simulation.moveShipRight( app.getGraphics().getDeltaTime(), 0.5f ); - - - if( input.isTouched() || input.isKeyPressed(Keys.KEYCODE_SPACE ) ) - simulation.shot(); + simulation.moveShipRight(app.getGraphics().getDeltaTime(), Math.abs(input.getAccelerometerY()) / 10); + + if (input.isKeyPressed(Keys.KEYCODE_DPAD_LEFT)) simulation.moveShipLeft(app.getGraphics().getDeltaTime(), 0.5f); + if (input.isKeyPressed(Keys.KEYCODE_DPAD_RIGHT)) simulation.moveShipRight(app.getGraphics().getDeltaTime(), 0.5f); + + if (input.isTouched() || input.isKeyPressed(Keys.KEYCODE_SPACE)) simulation.shot(); } - @Override - public void explosion() - { + @Override public void explosion () { explosion.play(); } - @Override - public void shot() - { + @Override public void shot () { shot.play(); } } diff --git a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/screens/GameOver.java b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/screens/GameOver.java index ea789cd29..436fb39ac 100644 --- a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/screens/GameOver.java +++ b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/screens/GameOver.java @@ -1,42 +1,38 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdxinvaders.screens; import com.badlogic.gdx.Application; import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Font; +import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.SpriteBatch; import com.badlogic.gdx.graphics.Texture; -import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; import com.badlogic.gdx.math.Matrix4; /** - * The game over screen displays the final score and a game over - * text and waits for the user to touch the screen in which case it + * The game over screen displays the final score and a game over text and waits for the user to touch the screen in which case it * will signal that it is done to the orchestrating GdxInvaders class. * * @author mzechner - * + * */ -public class GameOver implements Screen -{ +public class GameOver implements Screen { /** the SpriteBatch used to draw the background, logo and text **/ private final SpriteBatch spriteBatch; /** the background texture **/ @@ -48,58 +44,50 @@ public class GameOver implements Screen /** is done flag **/ private boolean isDone = false; /** view & transform matrix **/ - private final Matrix4 viewMatrix = new Matrix4( ); - private final Matrix4 transformMatrix = new Matrix4( ); - - public GameOver( Application app ) - { + private final Matrix4 viewMatrix = new Matrix4(); + private final Matrix4 transformMatrix = new Matrix4(); + + public GameOver (Application app) { spriteBatch = new SpriteBatch(); - background = app.getGraphics().newTexture( app.getFiles().getFileHandle( "data/planet.jpg", FileType.Internal ), TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); - - - logo = app.getGraphics().newTexture( app.getFiles().getFileHandle( "data/title.png", FileType.Internal ), TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); - - font = app.getGraphics().newFont( app.getFiles().getFileHandle( "data/font.ttf", FileType.Internal), 16, FontStyle.Plain ); + background = app.getGraphics().newTexture(app.getFiles().getFileHandle("data/planet.jpg", FileType.Internal), + TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); + + logo = app.getGraphics().newTexture(app.getFiles().getFileHandle("data/title.png", FileType.Internal), + TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); + + font = app.getGraphics().newFont(app.getFiles().getFileHandle("data/font.ttf", FileType.Internal), 16, FontStyle.Plain); } - - @Override - public void dispose() - { + + @Override public void dispose () { spriteBatch.dispose(); background.dispose(); logo.dispose(); font.dispose(); } - @Override - public boolean isDone() - { + @Override public boolean isDone () { return isDone; } - @Override - public void render(Application app) - { - app.getGraphics().getGL10().glClear( GL10.GL_COLOR_BUFFER_BIT ); - - viewMatrix.setToOrtho2D(0, 0, 480, 320 ); - spriteBatch.begin(viewMatrix, transformMatrix ); + @Override public void render (Application app) { + app.getGraphics().getGL10().glClear(GL10.GL_COLOR_BUFFER_BIT); + + viewMatrix.setToOrtho2D(0, 0, 480, 320); + spriteBatch.begin(viewMatrix, transformMatrix); spriteBatch.disableBlending(); - spriteBatch.draw( background, 0, 320, 480, 320, 0, 0, 512, 512, Color.WHITE, false, false ); + spriteBatch.draw(background, 0, 320, 480, 320, 0, 0, 512, 512, Color.WHITE, false, false); spriteBatch.enableBlending(); - spriteBatch.draw( logo, 0, 280, 480, 128, 0, 256, 512, 256, Color.WHITE, false, false ); + spriteBatch.draw(logo, 0, 280, 480, 128, 0, 256, 512, 256, Color.WHITE, false, false); String text = "It's the end my friend."; - float width = font.getStringWidth( text ); - spriteBatch.drawText( font, text, 240 - width / 2, 128, Color.WHITE ); + float width = font.getStringWidth(text); + spriteBatch.drawText(font, text, 240 - width / 2, 128, Color.WHITE); text = "Touch to continue!"; - width = font.getStringWidth( text ); - spriteBatch.drawText( font, text, 240 - width / 2, 100, Color.WHITE ); + width = font.getStringWidth(text); + spriteBatch.drawText(font, text, 240 - width / 2, 100, Color.WHITE); spriteBatch.end(); } - @Override - public void update(Application app) - { + @Override public void update (Application app) { isDone = app.getInput().isTouched(); } diff --git a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/screens/MainMenu.java b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/screens/MainMenu.java index 938561522..ca0f05740 100644 --- a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/screens/MainMenu.java +++ b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/screens/MainMenu.java @@ -1,42 +1,38 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdxinvaders.screens; import com.badlogic.gdx.Application; import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Font; +import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.SpriteBatch; import com.badlogic.gdx.graphics.Texture; -import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; import com.badlogic.gdx.math.Matrix4; /** - * The main menu screen showing a background, the logo of the game - * and a label telling the user to touch the screen to start the game. - * Waits for the touch and returns isDone() == true when it's done so that - * the ochestrating GdxInvaders class can switch to the next screen. + * The main menu screen showing a background, the logo of the game and a label telling the user to touch the screen to start the + * game. Waits for the touch and returns isDone() == true when it's done so that the ochestrating GdxInvaders class can switch to + * the next screen. * @author mzechner - * + * */ -public class MainMenu implements Screen -{ +public class MainMenu implements Screen { /** the SpriteBatch used to draw the background, logo and text **/ private final SpriteBatch spriteBatch; /** the background texture **/ @@ -48,51 +44,44 @@ public class MainMenu implements Screen /** is done flag **/ private boolean isDone = false; /** view & transform matrix **/ - private final Matrix4 viewMatrix = new Matrix4( ); - private final Matrix4 transformMatrix = new Matrix4( ); - - public MainMenu( Application app ) - { + private final Matrix4 viewMatrix = new Matrix4(); + private final Matrix4 transformMatrix = new Matrix4(); + + public MainMenu (Application app) { spriteBatch = new SpriteBatch(); - background = app.getGraphics().newTexture( app.getFiles().getFileHandle( "data/planet.jpg", FileType.Internal ), TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); - - logo = app.getGraphics().newTexture( app.getFiles().getFileHandle( "data/title.png", FileType.Internal ), TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); - - font = app.getGraphics().newFont( app.getFiles().getFileHandle( "data/font.ttf", FileType.Internal), 16, FontStyle.Plain); - } + background = app.getGraphics().newTexture(app.getFiles().getFileHandle("data/planet.jpg", FileType.Internal), + TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); - @Override - public void render(Application app) - { - app.getGraphics().getGL10().glClear( GL10.GL_COLOR_BUFFER_BIT ); - - viewMatrix.setToOrtho2D(0, 0, 480, 320 ); - spriteBatch.begin(viewMatrix, transformMatrix ); + logo = app.getGraphics().newTexture(app.getFiles().getFileHandle("data/title.png", FileType.Internal), + TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); + + font = app.getGraphics().newFont(app.getFiles().getFileHandle("data/font.ttf", FileType.Internal), 16, FontStyle.Plain); + } + + @Override public void render (Application app) { + app.getGraphics().getGL10().glClear(GL10.GL_COLOR_BUFFER_BIT); + + viewMatrix.setToOrtho2D(0, 0, 480, 320); + spriteBatch.begin(viewMatrix, transformMatrix); spriteBatch.disableBlending(); - spriteBatch.draw( background, 0, 320, 480, 320, 0, 0, 512, 512, Color.WHITE, false, false ); + spriteBatch.draw(background, 0, 320, 480, 320, 0, 0, 512, 512, Color.WHITE, false, false); spriteBatch.enableBlending(); - spriteBatch.draw( logo, 0, 280, 480, 128, 0, 0, 512, 256, Color.WHITE, false, false ); + spriteBatch.draw(logo, 0, 280, 480, 128, 0, 0, 512, 256, Color.WHITE, false, false); String text = "Touch screen to start!"; - float width = font.getStringWidth( text ); - spriteBatch.drawText( font, text, 240 - width / 2, 128, Color.WHITE ); + float width = font.getStringWidth(text); + spriteBatch.drawText(font, text, 240 - width / 2, 128, Color.WHITE); spriteBatch.end(); } - @Override - public void update(Application app) - { - isDone = app.getInput().isTouched(); + @Override public void update (Application app) { + isDone = app.getInput().isTouched(); } - @Override - public boolean isDone() - { + @Override public boolean isDone () { return isDone; } - - @Override - public void dispose() - { + + @Override public void dispose () { spriteBatch.dispose(); background.dispose(); logo.dispose(); diff --git a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/screens/Screen.java b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/screens/Screen.java index 2097972d2..978222ccb 100644 --- a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/screens/Screen.java +++ b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/screens/Screen.java @@ -1,53 +1,48 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdxinvaders.screens; import com.badlogic.gdx.Application; /** - * Interface for a game screen, e.g. main menu, game loop, - * game over screen and so on. + * Interface for a game screen, e.g. main menu, game loop, game over screen and so on. * @author mzechner - * + * */ -public interface Screen -{ +public interface Screen { /** - * Called when the screen should update itself, e.g. continue a - * simulation etc. + * Called when the screen should update itself, e.g. continue a simulation etc. * * @param app the Application */ - public void update( Application app ); - + public void update (Application app); + /** * Called when a screen should render itself * @param app */ - public void render( Application app ); - + public void render (Application app); + /** * Called by GdxInvaders to check whether the screen is done. * * @return true when the screen is done, false otherwise */ - public boolean isDone( ); - + public boolean isDone (); + /** * Cleans up all resources of the screen, e.g. meshes, textures etc. */ - public void dispose( ); + public void dispose (); } diff --git a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/Block.java b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/Block.java index 5817aef2b..c60814f57 100644 --- a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/Block.java +++ b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/Block.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdxinvaders.simulation; import com.badlogic.gdx.math.Vector3; -public class Block -{ +public class Block { public final static float BLOCK_RADIUS = 0.5f; - - public Vector3 position = new Vector3( ); - - public Block(Vector3 position) - { - this.position.set( position ); + + public Vector3 position = new Vector3(); + + public Block (Vector3 position) { + this.position.set(position); } } diff --git a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/Explosion.java b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/Explosion.java index 9d2153a8e..416983428 100644 --- a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/Explosion.java +++ b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/Explosion.java @@ -1,35 +1,30 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdxinvaders.simulation; import com.badlogic.gdx.math.Vector3; -public class Explosion -{ +public class Explosion { public static final float EXPLOSION_LIVE_TIME = 1; public float aliveTime = 0; - public final Vector3 position = new Vector3( ); - - public Explosion( Vector3 position ) - { - this.position.set( position ); + public final Vector3 position = new Vector3(); + + public Explosion (Vector3 position) { + this.position.set(position); } - - public void update( float delta ) - { + + public void update (float delta) { aliveTime += delta; - } + } } diff --git a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/Invader.java b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/Invader.java index 678d003aa..7c8721795 100644 --- a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/Invader.java +++ b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/Invader.java @@ -1,75 +1,64 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdxinvaders.simulation; import com.badlogic.gdx.math.Vector3; -public class Invader -{ +public class Invader { public static float INVADER_RADIUS = 0.75f; public static float INVADER_VELOCITY = 1; public static int INVADER_POINTS = 40; public final static int STATE_MOVE_LEFT = 0; public final static int STATE_MOVE_DOWN = 1; public final static int STATE_MOVE_RIGHT = 2; - + public final Vector3 position = new Vector3(); public int state = STATE_MOVE_LEFT; public boolean wasLastStateLeft = true; - public float movedDistance = Simulation.PLAYFIELD_MAX_X / 2;; - - public Invader( Vector3 position ) - { - this.position.set( position ); - } - - public void update(float delta, float speedMultiplier) - { + public float movedDistance = Simulation.PLAYFIELD_MAX_X / 2;; + + public Invader (Vector3 position) { + this.position.set(position); + } + + public void update (float delta, float speedMultiplier) { movedDistance += delta * INVADER_VELOCITY * speedMultiplier; - if( state == STATE_MOVE_LEFT ) - { + if (state == STATE_MOVE_LEFT) { position.x -= delta * INVADER_VELOCITY * speedMultiplier; - if( movedDistance > Simulation.PLAYFIELD_MAX_X ) - { + if (movedDistance > Simulation.PLAYFIELD_MAX_X) { state = STATE_MOVE_DOWN; movedDistance = 0; wasLastStateLeft = true; } } - if( state == STATE_MOVE_RIGHT ) - { + if (state == STATE_MOVE_RIGHT) { position.x += delta * INVADER_VELOCITY * speedMultiplier; - if( movedDistance > Simulation.PLAYFIELD_MAX_X ) - { + if (movedDistance > Simulation.PLAYFIELD_MAX_X) { state = STATE_MOVE_DOWN; movedDistance = 0; wasLastStateLeft = false; } } - if( state == STATE_MOVE_DOWN ) - { + if (state == STATE_MOVE_DOWN) { position.z += delta * INVADER_VELOCITY * speedMultiplier; - if( movedDistance > 1 ) - { - if( wasLastStateLeft ) + if (movedDistance > 1) { + if (wasLastStateLeft) state = STATE_MOVE_RIGHT; else state = STATE_MOVE_LEFT; movedDistance = 0; } - } + } } } diff --git a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/Ship.java b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/Ship.java index a2c99a4fa..057435001 100644 --- a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/Ship.java +++ b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/Ship.java @@ -1,38 +1,32 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdxinvaders.simulation; import com.badlogic.gdx.math.Vector3; -public class Ship -{ +public class Ship { public static final float SHIP_RADIUS = 1; public static final float SHIP_VELOCITY = 20; - public final Vector3 position = new Vector3( 0, 0, 0 ); + public final Vector3 position = new Vector3(0, 0, 0); public int lives = 3; public boolean isExploding = false; - public float explodeTime = 0; - - public void update( float delta ) - { - if( isExploding ) - { + public float explodeTime = 0; + + public void update (float delta) { + if (isExploding) { explodeTime += delta; - if( explodeTime > Explosion.EXPLOSION_LIVE_TIME ) - { + if (explodeTime > Explosion.EXPLOSION_LIVE_TIME) { isExploding = false; explodeTime = 0; } diff --git a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/Shot.java b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/Shot.java index def3108ab..8ac782422 100644 --- a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/Shot.java +++ b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/Shot.java @@ -1,45 +1,38 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdxinvaders.simulation; import com.badlogic.gdx.math.Vector3; -public class Shot -{ +public class Shot { public static float SHOT_VELOCITY = 10; public final Vector3 position = new Vector3(); public boolean isInvaderShot; public boolean hasLeftField = false; - public Shot( Vector3 position, boolean isInvaderShot ) - { - this.position.set( position ); + public Shot (Vector3 position, boolean isInvaderShot) { + this.position.set(position); this.isInvaderShot = isInvaderShot; } - - public void update(float delta) - { - if( isInvaderShot ) + + public void update (float delta) { + if (isInvaderShot) position.z += SHOT_VELOCITY * delta; else position.z -= SHOT_VELOCITY * delta; - - if( position.z > Simulation.PLAYFIELD_MAX_Z ) - hasLeftField = true; - if( position.z < Simulation.PLAYFIELD_MIN_Z ) - hasLeftField = true; + + if (position.z > Simulation.PLAYFIELD_MAX_Z) hasLeftField = true; + if (position.z < Simulation.PLAYFIELD_MIN_Z) hasLeftField = true; } } diff --git a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/Simulation.java b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/Simulation.java index 971695c61..a51223093 100644 --- a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/Simulation.java +++ b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/Simulation.java @@ -1,233 +1,193 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdxinvaders.simulation; import java.util.ArrayList; import com.badlogic.gdx.math.Vector3; -public class Simulation -{ +public class Simulation { public final static float PLAYFIELD_MIN_X = -14; public final static float PLAYFIELD_MAX_X = 14; public final static float PLAYFIELD_MIN_Z = -15; public final static float PLAYFIELD_MAX_Z = 2; - + public ArrayList invaders = new ArrayList(); - public ArrayList blocks = new ArrayList( ); - public ArrayList shots = new ArrayList( ); - public ArrayList explosions = new ArrayList( ); + public ArrayList blocks = new ArrayList(); + public ArrayList shots = new ArrayList(); + public ArrayList explosions = new ArrayList(); public Ship ship; public Shot shipShot = null; public transient SimulationListener listener; public float multiplier = 1; public int score; public int wave = 1; - + private ArrayList removedShots = new ArrayList(); - private ArrayList removedExplosions = new ArrayList( ); - - public Simulation( ) - { - populate( ); + private ArrayList removedExplosions = new ArrayList(); + + public Simulation () { + populate(); } - - private void populate( ) - { - ship = new Ship(); - - for( int row = 0; row < 4; row++ ) - { - for( int column = 0; column < 8; column++ ) - { - Invader invader = new Invader( new Vector3( -PLAYFIELD_MAX_X / 2 + column * 2f, 0, PLAYFIELD_MIN_Z + row * 2f )); - invaders.add( invader ); + + private void populate () { + ship = new Ship(); + + for (int row = 0; row < 4; row++) { + for (int column = 0; column < 8; column++) { + Invader invader = new Invader(new Vector3(-PLAYFIELD_MAX_X / 2 + column * 2f, 0, PLAYFIELD_MIN_Z + row * 2f)); + invaders.add(invader); } } - - for( int shield = 0; shield < 3; shield++ ) - { - blocks.add( new Block( new Vector3( -10 + shield * 10 -1, 0, -2) ) ); - blocks.add( new Block( new Vector3( -10 + shield * 10 -1, 0, -3) ) ); - blocks.add( new Block( new Vector3( -10 + shield * 10 + 0, 0, -3) ) ); - blocks.add( new Block( new Vector3( -10 + shield * 10 + 1, 0, -3) ) ); - blocks.add( new Block( new Vector3( -10 + shield * 10 + 1, 0, -2 ) ) ); + + for (int shield = 0; shield < 3; shield++) { + blocks.add(new Block(new Vector3(-10 + shield * 10 - 1, 0, -2))); + blocks.add(new Block(new Vector3(-10 + shield * 10 - 1, 0, -3))); + blocks.add(new Block(new Vector3(-10 + shield * 10 + 0, 0, -3))); + blocks.add(new Block(new Vector3(-10 + shield * 10 + 1, 0, -3))); + blocks.add(new Block(new Vector3(-10 + shield * 10 + 1, 0, -2))); } } - - public void update( float delta ) - { - ship.update( delta ); - updateInvaders( delta ); - updateShots( delta ); + + public void update (float delta) { + ship.update(delta); + updateInvaders(delta); + updateShots(delta); updateExplosions(delta); - checkShipCollision( ); - checkInvaderCollision( ); - checkBlockCollision( ); - checkNextLevel( ); + checkShipCollision(); + checkInvaderCollision(); + checkBlockCollision(); + checkNextLevel(); } - - private void updateInvaders( float delta ) - { - for( int i = 0; i < invaders.size(); i++ ) - { + + private void updateInvaders (float delta) { + for (int i = 0; i < invaders.size(); i++) { Invader invader = invaders.get(i); - invader.update( delta, multiplier ); + invader.update(delta, multiplier); } } - - private void updateShots( float delta ) - { + + private void updateShots (float delta) { removedShots.clear(); - for( int i = 0; i < shots.size(); i++ ) - { + for (int i = 0; i < shots.size(); i++) { Shot shot = shots.get(i); shot.update(delta); - if( shot.hasLeftField ) - removedShots.add(shot); + if (shot.hasLeftField) removedShots.add(shot); } - - for( int i = 0; i < removedShots.size(); i++ ) - shots.remove( removedShots.get(i) ); - - if( shipShot != null && shipShot.hasLeftField ) - shipShot = null; - - if( Math.random() < 0.01 * multiplier && invaders.size() > 0 ) - { + + for (int i = 0; i < removedShots.size(); i++) + shots.remove(removedShots.get(i)); + + if (shipShot != null && shipShot.hasLeftField) shipShot = null; + + if (Math.random() < 0.01 * multiplier && invaders.size() > 0) { int index = (int)(Math.random() * (invaders.size() - 1)); - Shot shot = new Shot( invaders.get(index).position, true ); - shots.add( shot ); - if( listener != null ) - listener.shot(); - } + Shot shot = new Shot(invaders.get(index).position, true); + shots.add(shot); + if (listener != null) listener.shot(); + } } - - public void updateExplosions( float delta ) - { + + public void updateExplosions (float delta) { removedExplosions.clear(); - for( int i = 0; i < explosions.size(); i++ ) - { + for (int i = 0; i < explosions.size(); i++) { Explosion explosion = explosions.get(i); - explosion.update( delta ); - if( explosion.aliveTime > Explosion.EXPLOSION_LIVE_TIME ) - removedExplosions.add( explosion ); + explosion.update(delta); + if (explosion.aliveTime > Explosion.EXPLOSION_LIVE_TIME) removedExplosions.add(explosion); } - - for( int i = 0; i < removedExplosions.size(); i++ ) - explosions.remove( removedExplosions.get(i) ); + + for (int i = 0; i < removedExplosions.size(); i++) + explosions.remove(removedExplosions.get(i)); } - - private void checkInvaderCollision() - { - if( shipShot == null ) - return; - - for( int j = 0; j < invaders.size(); j++ ) - { + + private void checkInvaderCollision () { + if (shipShot == null) return; + + for (int j = 0; j < invaders.size(); j++) { Invader invader = invaders.get(j); - if( invader.position.dst(shipShot.position) < Invader.INVADER_RADIUS ) - { - shots.remove( shipShot ); + if (invader.position.dst(shipShot.position) < Invader.INVADER_RADIUS) { + shots.remove(shipShot); shipShot = null; invaders.remove(invader); - explosions.add( new Explosion( invader.position ) ); - if( listener != null ) - listener.explosion(); + explosions.add(new Explosion(invader.position)); + if (listener != null) listener.explosion(); score += Invader.INVADER_POINTS; break; } - } + } } - private void checkShipCollision() - { + private void checkShipCollision () { removedShots.clear(); - - if( !ship.isExploding ) - { - for( int i = 0; i < shots.size(); i++ ) - { + + if (!ship.isExploding) { + for (int i = 0; i < shots.size(); i++) { Shot shot = shots.get(i); - if( !shot.isInvaderShot ) - continue; - - if( ship.position.dst(shot.position) < Ship.SHIP_RADIUS ) - { - removedShots.add( shot ); + if (!shot.isInvaderShot) continue; + + if (ship.position.dst(shot.position) < Ship.SHIP_RADIUS) { + removedShots.add(shot); shot.hasLeftField = true; ship.lives--; ship.isExploding = true; - explosions.add( new Explosion( ship.position ) ); - if( listener != null ) - listener.explosion(); + explosions.add(new Explosion(ship.position)); + if (listener != null) listener.explosion(); break; - } + } } - - for( int i = 0; i < removedShots.size(); i++ ) - shots.remove( removedShots.get(i) ); + + for (int i = 0; i < removedShots.size(); i++) + shots.remove(removedShots.get(i)); } - - for( int i = 0; i < invaders.size(); i++ ) - { + + for (int i = 0; i < invaders.size(); i++) { Invader invader = invaders.get(i); - if( invader.position.dst(ship.position) < Ship.SHIP_RADIUS ) - { + if (invader.position.dst(ship.position) < Ship.SHIP_RADIUS) { ship.lives--; invaders.remove(invader); ship.isExploding = true; - explosions.add( new Explosion( invader.position ) ); - explosions.add( new Explosion( ship.position ) ); - if( listener != null ) - listener.explosion(); + explosions.add(new Explosion(invader.position)); + explosions.add(new Explosion(ship.position)); + if (listener != null) listener.explosion(); break; } } } - private void checkBlockCollision( ) - { + private void checkBlockCollision () { removedShots.clear(); - - for( int i = 0; i < shots.size(); i++ ) - { - Shot shot = shots.get(i); - - for( int j = 0; j < blocks.size(); j++ ) - { + + for (int i = 0; i < shots.size(); i++) { + Shot shot = shots.get(i); + + for (int j = 0; j < blocks.size(); j++) { Block block = blocks.get(j); - if( block.position.dst(shot.position) < Block.BLOCK_RADIUS ) - { - removedShots.add( shot ); + if (block.position.dst(shot.position) < Block.BLOCK_RADIUS) { + removedShots.add(shot); shot.hasLeftField = true; blocks.remove(block); break; } - } + } } - - for( int i = 0; i < removedShots.size(); i++ ) - shots.remove( removedShots.get(i) ); + + for (int i = 0; i < removedShots.size(); i++) + shots.remove(removedShots.get(i)); } - - private void checkNextLevel( ) - { - if( invaders.size() == 0 && ship.lives > 0 ) - { + + private void checkNextLevel () { + if (invaders.size() == 0 && ship.lives > 0) { blocks.clear(); shots.clear(); shipShot = null; @@ -240,35 +200,26 @@ public class Simulation wave++; } } - - public void moveShipLeft(float delta, float scale) - { - if( ship.isExploding ) - return; - + + public void moveShipLeft (float delta, float scale) { + if (ship.isExploding) return; + ship.position.x -= delta * Ship.SHIP_VELOCITY * scale; - if( ship.position.x < PLAYFIELD_MIN_X ) - ship.position.x = PLAYFIELD_MIN_X; + if (ship.position.x < PLAYFIELD_MIN_X) ship.position.x = PLAYFIELD_MIN_X; } - public void moveShipRight(float delta, float scale ) - { - if( ship.isExploding ) - return; - + public void moveShipRight (float delta, float scale) { + if (ship.isExploding) return; + ship.position.x += delta * Ship.SHIP_VELOCITY * scale; - if( ship.position.x > PLAYFIELD_MAX_X ) - ship.position.x = PLAYFIELD_MAX_X; + if (ship.position.x > PLAYFIELD_MAX_X) ship.position.x = PLAYFIELD_MAX_X; } - public void shot() - { - if( shipShot == null && !ship.isExploding ) - { - shipShot = new Shot( ship.position, false ); - shots.add( shipShot ); - if( listener != null ) - listener.shot(); + public void shot () { + if (shipShot == null && !ship.isExploding) { + shipShot = new Shot(ship.position, false); + shots.add(shipShot); + if (listener != null) listener.shot(); } - } + } } diff --git a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/SimulationListener.java b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/SimulationListener.java index 6477c4cfb..741428fb0 100644 --- a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/SimulationListener.java +++ b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/simulation/SimulationListener.java @@ -1,22 +1,20 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdxinvaders.simulation; -public interface SimulationListener -{ - public void explosion( ); - public void shot( ); +public interface SimulationListener { + public void explosion (); + + public void shot (); } diff --git a/extensions/twl/gdx-twl-tests-android/src/com/badlogic/gdx/twl/TextAreaTest.java b/extensions/twl/gdx-twl-tests-android/src/com/badlogic/gdx/twl/TextAreaTest.java index 343384957..beb13e283 100644 --- a/extensions/twl/gdx-twl-tests-android/src/com/badlogic/gdx/twl/TextAreaTest.java +++ b/extensions/twl/gdx-twl-tests-android/src/com/badlogic/gdx/twl/TextAreaTest.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.twl; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class TextAreaTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { +public class TextAreaTest extends AndroidApplication { + public void onCreate (Bundle bundle) { super.onCreate(bundle); - initialize( false ); - getGraphics().setRenderListener( new com.badlogic.gdx.twl.tests.TextAreaTest() ); + initialize(false); + getGraphics().setRenderListener(new com.badlogic.gdx.twl.tests.TextAreaTest()); } } diff --git a/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/renderer/GdxFont.java b/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/renderer/GdxFont.java index e389acfae..3fa8256cc 100644 --- a/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/renderer/GdxFont.java +++ b/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/renderer/GdxFont.java @@ -31,7 +31,6 @@ import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.BitmapFont; import com.badlogic.gdx.graphics.BitmapFont.HAlignment; import com.badlogic.gdx.graphics.BitmapFontCache; -import com.badlogic.gdx.graphics.Texture; import de.matthiasmann.twl.Color; import de.matthiasmann.twl.renderer.AnimationState; diff --git a/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/renderer/GdxTexture.java b/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/renderer/GdxTexture.java index 89d2ad766..df86b69d4 100644 --- a/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/renderer/GdxTexture.java +++ b/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/renderer/GdxTexture.java @@ -22,8 +22,8 @@ package com.badlogic.gdx.twl.renderer; -import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Files.FileType; +import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; @@ -70,7 +70,7 @@ class GdxTexture implements Texture, Resource { // BOZO boolean bind (Color color) { texture.bind(); - //renderer.tintStack.setColor(color); + // renderer.tintStack.setColor(color); return true; } diff --git a/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/renderer/TextureArea.java b/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/renderer/TextureArea.java index 17e635a0e..d9b43cae6 100644 --- a/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/renderer/TextureArea.java +++ b/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/renderer/TextureArea.java @@ -7,7 +7,6 @@ import java.nio.FloatBuffer; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL10; -import com.badlogic.gdx.graphics.GL11; import de.matthiasmann.twl.Color; import de.matthiasmann.twl.renderer.AnimationState; diff --git a/gdx/src/com/badlogic/gdx/Application.java b/gdx/src/com/badlogic/gdx/Application.java index 750ce7c0e..8117d01b1 100644 --- a/gdx/src/com/badlogic/gdx/Application.java +++ b/gdx/src/com/badlogic/gdx/Application.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; /** @@ -20,53 +18,47 @@ package com.badlogic.gdx; * An Application is the main class of your project. It manages the different * aspects of your application, namely {@link Graphics}, {@link Audio}, {@link Input} * and {@link Files}. - *

+ *

* *

- * An application can either be a desktop application ({@link JoglApplication}), an - * applet ({@link AppletApplication} or and Android application ({@link AndroidApplication}). - * Each application class has it's own startup and initialization methods. Please refer to - * their documentation for more information. - *

+ * An application can either be a desktop application ({@link JoglApplication}), an applet ({@link AppletApplication} or and + * Android application ({@link AndroidApplication}). Each application class has it's own startup and initialization methods. + * Please refer to their documentation for more information. + *

* *

- * {@link Graphics} offers you various methods to output visuals to the screen. This is - * achieved via OpenGL ES 1.0, 1.1 or 2.0 depending on what's available an the platform. - * On the desktop the features of OpenGL ES 2.0 are - * emulated via Jogl. On Android the functionality of the Java OpenGL ES bindings - * is used. The Graphics object allows you to register a {@link RenderListener} which will - * be called each time a new frame has to be drawn. This RenderListener usually + * {@link Graphics} offers you various methods to output visuals to the screen. This is achieved via OpenGL ES 1.0, 1.1 or 2.0 + * depending on what's available an the platform. On the desktop the features of OpenGL ES 2.0 are emulated via Jogl. On Android + * the functionality of the Java OpenGL ES bindings is used. The Graphics object allows you to register a {@link RenderListener} + * which will be called each time a new frame has to be drawn. This RenderListener usually * houses you application logic. *

* *

- * {@link Audio} offers you various methods to output and record sound and music. This is achieved - * via the Java Sound API on the desktop. On Android the Android media framework is used. + * {@link Audio} offers you various methods to output and record sound and music. This is achieved via the Java Sound API on the + * desktop. On Android the Android media framework is used. *

* *

- * {@link Input} offers you various methods to poll user input from the keyboard, touch screen, - * mouse and accelerometer. Additionally you can register an {@link InputListener} - * which allows for event based input processing. The InputListener will be called - * in the rendering thread which will also call your RenderListener. This way you - * don't have to care about thread synchronization when you process input events. + * {@link Input} offers you various methods to poll user input from the keyboard, touch screen, mouse and accelerometer. + * Additionally you can register an {@link InputListener} which allows for event based input processing. The + * InputListener will be called in the rendering thread which will also call your RenderListener. This + * way you don't have to care about thread synchronization when you process input events. *

* *

- * {@link Files} offers you various methods to access internal and external files. - * An internal file is a file that is stored near your application. On Android internal - * file are equivalent to assets. On the desktop the root directory of your application - * is where internal files will be looked up. Internal files are read only. External - * files are resources you create in your application and write to an external storage. - * On Android external files reside on the SD-card, on the desktop external files - * are written to a users home directory. If you know what you do you can also specify - * absolute file names. This is not portable, so take great care when using this feature. - *

+ * {@link Files} offers you various methods to access internal and external files. An internal file is a file that is stored near + * your application. On Android internal file are equivalent to assets. On the desktop the root directory of your application is + * where internal files will be looked up. Internal files are read only. External files are resources you create in your + * application and write to an external storage. On Android external files reside on the SD-card, on the desktop external files + * are written to a users home directory. If you know what you do you can also specify absolute file names. This is not portable, + * so take great care when using this feature. + *

* *

- * Additionally an Application allows to set a {@link ApplicationListener} which will be invoked - * when the Application is paused, resumed or closing. This can be used to save any state that needs saving. - * Note that the ApplicationListener will not be called in the rendering thread. + * Additionally an Application allows to set a {@link ApplicationListener} which will be invoked when the + * Application is paused, resumed or closing. This can be used to save any state that needs saving. Note that the + * ApplicationListener will not be called in the rendering thread. * *

* Generally you will have two projects for your application. The first one will be the @@ -78,74 +70,68 @@ package com.badlogic.gdx; *

* *

- * The Application also has a set of methods that you can use to query specific - * information such as the operating system the application is currently running on and so forth. - * This allows you to have operating system dependent code paths. It is however not recommended - * to use this facilities. + * The Application also has a set of methods that you can use to query specific information such as the operating + * system the application is currently running on and so forth. This allows you to have operating system dependent code paths. It + * is however not recommended to use this facilities. *

* *

- * The Application also has a simple logging method which will print to standard out - * on the desktop and to logcat on Android. + * The Application also has a simple logging method which will print to standard out on the desktop and to logcat on + * Android. *

* * @author mzechner - * + * */ -public interface Application -{ +public interface Application { /** * Enumeration of possible {@link Application} types * @author mzechner - * + * */ - public enum ApplicationType - { - Android, - Desktop, - Applet + public enum ApplicationType { + Android, Desktop, Applet } - + /** * @return the {@link Graphics} instance */ - public Graphics getGraphics( ); - + public Graphics getGraphics (); + /** * @return the {@link Audio} instance */ - public Audio getAudio( ); - + public Audio getAudio (); + /** * @return the {@link Input} instance */ - public Input getInput( ); - + public Input getInput (); + /** * @return the {@link Files} instance */ - public Files getFiles( ); - + public Files getFiles (); + /** * Logs a message to the console or logcat */ - public void log( String tag, String message ); - + public void log (String tag, String message); + /** * @return what {@link ApplicationType} this application has, e.g. Android or Desktop */ - public ApplicationType getType( ); - + public ApplicationType getType (); + /** * @return the Android API level on Android or 0 on the desktop. */ - public int getVersion( ); - + public int getVersion (); + /** - * Sets the {@link ApplicationListener} that is called - * when the {@link Application} is paused, resumed or closing. + * Sets the {@link ApplicationListener} that is called when the {@link Application} is paused, resumed or closing. * - * @param listener the ApplicationListener + * @param listener the ApplicationListener */ - public void setApplicationListener( ApplicationListener listener ); + public void setApplicationListener (ApplicationListener listener); } diff --git a/gdx/src/com/badlogic/gdx/ApplicationListener.java b/gdx/src/com/badlogic/gdx/ApplicationListener.java index 7bf544aef..92ce4bc98 100644 --- a/gdx/src/com/badlogic/gdx/ApplicationListener.java +++ b/gdx/src/com/badlogic/gdx/ApplicationListener.java @@ -1,59 +1,49 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; /** - *

An ApplicationListener is called when the {@link Application} - * is resumed, paused and destroyed. This allows you to save any states you want - * to save. The methods are not called from within - * the rendering thread so care has to be taken. Do not load or unload any Graphics - * related resources in the provided by this interface!

+ *

+ * An ApplicationListener is called when the {@link Application} is resumed, paused and destroyed. This allows you to + * save any states you want to save. The methods are not called from within the rendering thread so care has to be taken. Do not + * load or unload any Graphics related resources in the provided by this interface! + *

* - *

The ApplicationListener interface follows - * the standard Android activity life-cycle and is emulated on - * the desktop accordingly. The pause method will be called after the rendering - * thread has been paused. The resume method will be called before the rendering - * thread has been started. + *

+ * The ApplicationListener interface follows the standard Android activity life-cycle and is emulated on the desktop + * accordingly. The pause method will be called after the rendering thread has been paused. The resume method will be called + * before the rendering thread has been started. * * @author mzechner - * + * */ -public interface ApplicationListener -{ +public interface ApplicationListener { /** - * Called when the {@link Application} is paused. An - * Application is paused before it is destroyed or - * when a user pressed the Home button on Android. - * This will not be called in the rendering thread. Instead - * the rendering thread will be paused before this method is called. + * Called when the {@link Application} is paused. An Application is paused before it is destroyed or when a user pressed the + * Home button on Android. This will not be called in the rendering thread. Instead the rendering thread will be paused before + * this method is called. */ - public void pause( ); - + public void pause (); + /** - * Called when the {@link Application} is resumed - * from a paused state or the Application was just - * created. This will not be called in the rendering thread. - * Instead this callback will be first called, then the - * rendering thread will be resumed. + * Called when the {@link Application} is resumed from a paused state or the Application was just created. This will not be + * called in the rendering thread. Instead this callback will be first called, then the rendering thread will be resumed. */ - public void resume( ); - + public void resume (); + /** - * Called when the {@link Application} is destroyed. This - * will not be called in the rendering thread. + * Called when the {@link Application} is destroyed. This will not be called in the rendering thread. */ - public void destroy( ); + public void destroy (); } diff --git a/gdx/src/com/badlogic/gdx/Audio.java b/gdx/src/com/badlogic/gdx/Audio.java index 7750aa047..5bf16ba18 100644 --- a/gdx/src/com/badlogic/gdx/Audio.java +++ b/gdx/src/com/badlogic/gdx/Audio.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import com.badlogic.gdx.audio.AudioDevice; @@ -22,36 +20,31 @@ import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.files.FileHandle; /** - * This interface encapsulates the creation and managment of audio resources. - * It allows you to create direct access links to the audio hardware via - * the {@link AudioDevice} and {@link AudioRecorder} interfaces, create sound effects via the {@link Sound} + * This interface encapsulates the creation and managment of audio resources. It allows you to create direct access links to the + * audio hardware via the {@link AudioDevice} and {@link AudioRecorder} interfaces, create sound effects via the {@link Sound} * interface and play music streams via the {@link Music} interface. * *

- * All resources created via this interface have to be disposed as soon as they - * are no longer used. + * All resources created via this interface have to be disposed as soon as they are no longer used. *

* * @author mzechner - * + * */ -public interface Audio -{ +public interface Audio { /** - * Creates a new {@link AudioDevice} either in 44.1khz mono - * or stereo mode. The AudioDevice has to be disposed via its - * {@link AudioDevice.dispose()} method when it is no longer used. + * Creates a new {@link AudioDevice} either in 44.1khz mono or stereo mode. The AudioDevice has to be disposed via its {@link + * AudioDevice.dispose()} method when it is no longer used. * * @param isMono whether the AudioDevice should be in mono or stereo mode * @return the AudioDevice * * @throws GdxRuntimeException in case the device could not be created */ - public AudioDevice newAudioDevice( boolean isMono ); - + public AudioDevice newAudioDevice (boolean isMono); + /** - * Creates a new {@link AudioRecorder}. The AudioRecorder has to be disposed - * after it is no longer used. + * Creates a new {@link AudioRecorder}. The AudioRecorder has to be disposed after it is no longer used. * * @param samplingRate the sampling rate in Herz * @param isMono whether the recorder records in mono or stereo @@ -59,15 +52,13 @@ public interface Audio * * @throws GdxRuntimeException in case the recorder could not be created */ - public AudioRecorder newAudioRecoder( int samplingRate, boolean isMono ); - + public AudioRecorder newAudioRecoder (int samplingRate, boolean isMono); + /** *

- * Creates a new {@link Sound} which is used to play back audio effects such - * as gun shots or explosions. The Sound's audio data is retrieved from the - * file specified via the {@link FileHandle}. Note that the complete audio - * data is loaded into RAM. You should therefore not load big audio files - * with this methods. The current upper limit for decoded audio is 1 MB. + * Creates a new {@link Sound} which is used to play back audio effects such as gun shots or explosions. The Sound's audio data + * is retrieved from the file specified via the {@link FileHandle}. Note that the complete audio data is loaded into RAM. You + * should therefore not load big audio files with this methods. The current upper limit for decoded audio is 1 MB. *

* *

@@ -75,25 +66,22 @@ public interface Audio *

* *

- * The Sound has to be disposed if it is no longer used via the {@link Sound.dispose()} - * method. + * The Sound has to be disposed if it is no longer used via the {@link Sound.dispose()} method. *

* * @param file the FileHandle to the audio file * @return the new Sound or null if the Sound could not be loaded * @throws GdxRuntimeException in case the sound could not be loaded */ - public Sound newSound( FileHandle fileHandle ); - + public Sound newSound (FileHandle fileHandle); + /** - * Creates a new {@link Music} instance which is used to playback a music - * stream from a file. Currently supported formats are WAV, MP3 and OGG. - * The Music instance has to be disposed if it is no longer used via the {@link Music.dispose()} - * method. + * Creates a new {@link Music} instance which is used to playback a music stream from a file. Currently supported formats are + * WAV, MP3 and OGG. The Music instance has to be disposed if it is no longer used via the {@link Music.dispose()} method. * - * @param file the FileHandle + * @param file the FileHandle * @return the new Music or null if the Music could not be loaded * @throws GdxRuntimeException in case the music could not be loaded */ - public Music newMusic( FileHandle file ); + public Music newMusic (FileHandle file); } diff --git a/gdx/src/com/badlogic/gdx/Files.java b/gdx/src/com/badlogic/gdx/Files.java index 1699d538f..75a7c9aac 100644 --- a/gdx/src/com/badlogic/gdx/Files.java +++ b/gdx/src/com/badlogic/gdx/Files.java @@ -1,140 +1,114 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import java.io.InputStream; import java.io.OutputStream; +import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.files.FileHandle; /** - * This interface encapsulates the access of internal, external and absolute files. - * Internal files are read-only and come with the application when deployed. - * On Android assets are internal files, on the desktop anything in the applications - * root directory is considered to be a an internal file. External files can be read and - * written to. On Android they are relative to the SD-card, on the desktop they are - * relative to the user home directory. Absolute files are just that, fully qualified - * filenames. To ensure portability across platforms use absolute files only when absolutely - * necessary. + * This interface encapsulates the access of internal, external and absolute files. Internal files are read-only and come with the + * application when deployed. On Android assets are internal files, on the desktop anything in the applications root directory is + * considered to be a an internal file. External files can be read and written to. On Android they are relative to the SD-card, on + * the desktop they are relative to the user home directory. Absolute files are just that, fully qualified filenames. To ensure + * portability across platforms use absolute files only when absolutely necessary. * * @author mzechner - * + * */ -public interface Files -{ +public interface Files { /** - * Enum describing the three file types, internal, external - * and absolute. Internal files are located in the asset directory - * on Android and are relative to the applications root directory - * on the desktop. External files are relative to the SD-card on Android - * and relative to the home directory of the current user on the Desktop. - * Absolute files are just that, absolute files that can point anywhere. + * Enum describing the three file types, internal, external and absolute. Internal files are located in the asset directory on + * Android and are relative to the applications root directory on the desktop. External files are relative to the SD-card on + * Android and relative to the home directory of the current user on the Desktop. Absolute files are just that, absolute files + * that can point anywhere. * @author mzechner - * + * */ - public enum FileType - { - Internal, - External, - Absolut + public enum FileType { + Internal, External, Absolut } - + /** - * Returns an {@link InputStream} to the given file. If type is equal - * to {@link FileType.Internal} an internal file will be opened. On Android - * this is relative to the assets directory, on the desktop it is - * relative to the applications root directory. If type is equal to - * {@link FileType.External} an external file will be opened. On Android this - * is relative to the SD-card, on the desktop it is relative to the - * current user's home directory. If type is equal to {@link FileType.Absolut} - * the filename is interpreted as an absolute filename. + * Returns an {@link InputStream} to the given file. If type is equal to {@link FileType.Internal} an internal file will be + * opened. On Android this is relative to the assets directory, on the desktop it is relative to the applications root + * directory. If type is equal to {@link FileType.External} an external file will be opened. On Android this is relative to the + * SD-card, on the desktop it is relative to the current user's home directory. If type is equal to {@link FileType.Absolut} + * the filename is interpreted as an absolute filename. * * @param fileName the name of the file to open. * @param type the type of file to open. * @return the InputStream * @throws GDXRuntimeException in case the file could not be opened. */ - public InputStream readFile( String fileName, FileType type ); - + public InputStream readFile (String fileName, FileType type); + /** - * Returns and {@link OutputStream} to the given file. If - * the file does not exist it is created. If the file - * exists it will be overwritten. If type is equal - * to {@link FileType.Internal} null will be returned as on Android assets can not be written. If type is equal to - * {@link FileType.External} an external file will be opened. On Android this - * is relative to the SD-card, on the desktop it is relative to the - * current user's home directory. If type is equal to {@link FileType.Absolut} - * the filename is interpreted as an absolut filename. + * Returns and {@link OutputStream} to the given file. If the file does not exist it is created. If the file exists it will be + * overwritten. If type is equal to {@link FileType.Internal} null will be returned as on Android assets can not be written. If + * type is equal to {@link FileType.External} an external file will be opened. On Android this is relative to the SD-card, on + * the desktop it is relative to the current user's home directory. If type is equal to {@link FileType.Absolut} the filename + * is interpreted as an absolut filename. * * @param filename the name of the file to open * @param type the type of the file to open * @return the OutputStream * @throws GdxRuntimeException in case the file could not be opened */ - public OutputStream writeFile( String filename, FileType type ); - + public OutputStream writeFile (String filename, FileType type); + /** - * Creates a new directory or directory hierarchy on the external - * storage. If the directory parameter contains sub folders and - * the parent folders don't exist yet they will be created. If type is equal - * to {@link FileType.Internal} false will be returned as on Android new directories in the asset directory can not be created. If type is equal to - * {@link FileType.External} an external directory will be created. On Android this - * is relative to the SD-card, on the desktop it is relative to the - * current user's home directory. If type is equal to {@link FileType.Absolut} - * the directory is interpreted as an absolute directory name. + * Creates a new directory or directory hierarchy on the external storage. If the directory parameter contains sub folders and + * the parent folders don't exist yet they will be created. If type is equal to {@link FileType.Internal} false will be + * returned as on Android new directories in the asset directory can not be created. If type is equal to + * {@link FileType.External} an external directory will be created. On Android this is relative to the SD-card, on the desktop + * it is relative to the current user's home directory. If type is equal to {@link FileType.Absolut} the directory is + * interpreted as an absolute directory name. * * @param directory the directory * @param type the type of the directory * @return true in case the directory could be created, false otherwise */ - public boolean makeDirectory( String directory, FileType type ); - - + public boolean makeDirectory (String directory, FileType type); + /** - * Lists the files and directories in the given directory. If type is equal - * to {@link FileType.Internal} an internal directory will be listed. On Android - * this is relative to the assets directory, on the desktop it is - * relative to the applications root directory. If type is equal to - * {@link FileType.External} an external directory will be listed. On Android this - * is relative to the SD-card, on the desktop it is relative to the - * current user's home directory. If type is equal to {@link FileType.Absolut} - * the filename is interpreted as an absolut directory. - * + * Lists the files and directories in the given directory. If type is equal to {@link FileType.Internal} an internal directory + * will be listed. On Android this is relative to the assets directory, on the desktop it is relative to the applications root + * directory. If type is equal to {@link FileType.External} an external directory will be listed. On Android this is relative + * to the SD-card, on the desktop it is relative to the current user's home directory. If type is equal to + * {@link FileType.Absolut} the filename is interpreted as an absolut directory. + * * @param directory the directory * @param type the type of the directory * @return the files and directories in the given directory * @throws GDXRuntimeException if the directory does not exist */ - public String[] listDirectory( String directory, FileType type ); - - + public String[] listDirectory (String directory, FileType type); + /** - * Returns a {@link FileHandle} object for a file. If type is equal - * to {@link FileType.Internal} an internal file will be opened. On Android - * this is relative to the assets directory, on the desktop it is - * relative to the applications root directory. If type is equal to - * {@link FileType.External} an external file will be opened. On Android this - * is relative to the SD-card, on the desktop it is relative to the - * current user's home directory. If type is equal to {@link FileType.Absolut} - * the filename is interpreted as an absolute filename. - * + * Returns a {@link FileHandle} object for a file. If type is equal to {@link FileType.Internal} an internal file will be + * opened. On Android this is relative to the assets directory, on the desktop it is relative to the applications root + * directory. If type is equal to {@link FileType.External} an external file will be opened. On Android this is relative to the + * SD-card, on the desktop it is relative to the current user's home directory. If type is equal to {@link FileType.Absolut} + * the filename is interpreted as an absolute filename. + * * @param filename the name of the file * @param type the type of the file * @return the FileDescriptor or null if the descriptor could not be created * @throws GdxRuntimeException if the file does not exist */ - public FileHandle getFileHandle( String filename, FileType type ); + public FileHandle getFileHandle (String filename, FileType type); } diff --git a/gdx/src/com/badlogic/gdx/Gdx.java b/gdx/src/com/badlogic/gdx/Gdx.java index e62410a33..52c2959dd 100644 --- a/gdx/src/com/badlogic/gdx/Gdx.java +++ b/gdx/src/com/badlogic/gdx/Gdx.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import com.badlogic.gdx.graphics.GL10; @@ -21,28 +19,31 @@ import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.GLCommon; /** - *

Environment class holding references to the Application, Graphics, Audio, - * Files and Input instances. The references are held in public static fields. - * Do not mess with this! This essentially allows you static access to all sub - * systems. It is your responsiblity to keep things thread safe. Don't use Graphics - * in a thread that is not the rendering thread or things will go crazy. Really.

+ *

+ * Environment class holding references to the Application, Graphics, Audio, Files and Input instances. The references are held in + * public static fields. Do not mess with this! This essentially allows you static access to all sub systems. It is your + * responsiblity to keep things thread safe. Don't use Graphics in a thread that is not the rendering thread or things will go + * crazy. Really. + *

* - *

There's also references to GLCommon, GL10, GL11 and GL20. The same rules as above - * apply. Don't mess with this or things will break!

+ *

+ * There's also references to GLCommon, GL10, GL11 and GL20. The same rules as above apply. Don't mess with this or things will + * break! + *

* - *

This is kind of messy but better than throwing around Graphics and similar instances. - * I'm aware of the design faux pas

+ *

+ * This is kind of messy but better than throwing around Graphics and similar instances. I'm aware of the design faux pas + *

* @author mzechner - * + * */ -public class Gdx -{ +public class Gdx { public static Application app; public static Graphics graphics; public static Audio audio; public static Input input; public static Files files; - + public static GLCommon gl; public static GL10 gl10; public static GL11 gl11; diff --git a/gdx/src/com/badlogic/gdx/GdxRuntimeException.java b/gdx/src/com/badlogic/gdx/GdxRuntimeException.java index f2146c112..4072dd38d 100644 --- a/gdx/src/com/badlogic/gdx/GdxRuntimeException.java +++ b/gdx/src/com/badlogic/gdx/GdxRuntimeException.java @@ -1,42 +1,36 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; /** * Typed runtime exception used throughout libgdx * * @author mzechner - * + * */ -public class GdxRuntimeException extends RuntimeException -{ +public class GdxRuntimeException extends RuntimeException { private static final long serialVersionUID = 6735854402467673117L; - - public GdxRuntimeException( String message ) - { - super( message ); + + public GdxRuntimeException (String message) { + super(message); } - - public GdxRuntimeException( Throwable t ) - { - super( t ); + + public GdxRuntimeException (Throwable t) { + super(t); } - - public GdxRuntimeException( String message, Throwable t ) - { - super( message, t ); + + public GdxRuntimeException (String message, Throwable t) { + super(message, t); } } diff --git a/gdx/src/com/badlogic/gdx/Graphics.java b/gdx/src/com/badlogic/gdx/Graphics.java index b594e0b4c..b68c2ceaf 100644 --- a/gdx/src/com/badlogic/gdx/Graphics.java +++ b/gdx/src/com/badlogic/gdx/Graphics.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import java.io.InputStream; @@ -29,136 +27,119 @@ import com.badlogic.gdx.graphics.Texture; /** *

- * This interface encapsulates the communication with the graphics processor. - * It allows to retrieve {@link GL10}, {@link GL11} and {@link GL20} instances - * depending on the available hardware and configuration of the {@link Application}. - * Additionally it features methods to generate {@link Pixmap}s, {@link Font}s and - * {@link Texture}s. - * Note that ShaderPrograms only work when OpenGL ES 2.0 is available and the - * Application was configured to use OpenGL ES 2.0. + * This interface encapsulates the communication with the graphics processor. It allows to retrieve {@link GL10}, {@link GL11} and + * {@link GL20} instances depending on the available hardware and configuration of the {@link Application}. Additionally it + * features methods to generate {@link Pixmap}s, {@link Font}s and {@link Texture}s. Note that ShaderPrograms only work when + * OpenGL ES 2.0 is available and the Application was configured to use OpenGL ES 2.0. *

* - *

- * {@link Font}s and {@link Texture}s can be either managed or not managed. Managed - * Fonts and Textures will be restored when the OpenGL context is lost. An OpenGL ES - * context loss happens when a user pauses the Application and switches to another - * application on Android. On the desktop there is no concept of context loss for - * OpenGL. If an OpenGL context is lost all the textures (and Fonts are essentially just - * textures) and meshes uploaded to the GPU will get invalidated and have to be reloaded. - * Creating a Font or Texture with the managed feature means that the Graphics - * backend will take care of reloading these resources as soon as the Application is resumed. - * You don't have to do this manually in this case. The drawback: the mechanism needs additional - * memory to store the original resources for the reloading process in memory. Use this feature - * only if you know that you have enough memory! Future versions might introduce a disk cache - * for when a Texture was created from a Pixmap which was created programmatically or use - * the reference to the original file from which a texture was created. + *

+ * {@link Font}s and {@link Texture}s can be either managed or not managed. Managed Fonts and Textures will be restored when the + * OpenGL context is lost. An OpenGL ES context loss happens when a user pauses the Application and switches to another + * application on Android. On the desktop there is no concept of context loss for OpenGL. If an OpenGL context is lost all the + * textures (and Fonts are essentially just textures) and meshes uploaded to the GPU will get invalidated and have to be reloaded. + * Creating a Font or Texture with the managed feature means that the Graphics backend will take care of reloading + * these resources as soon as the Application is resumed. You don't have to do this manually in this case. The drawback: the + * mechanism needs additional memory to store the original resources for the reloading process in memory. Use this feature only if + * you know that you have enough memory! Future versions might introduce a disk cache for when a Texture was created from a Pixmap + * which was created programmatically or use the reference to the original file from which a texture was created. *

* *

- * Note that you don't have to reload managed Textures and Fonts. Doing so will effectively double - * the memory consumption as those Textures and Fonts will be in memory twice. + * Note that you don't have to reload managed Textures and Fonts. Doing so will effectively double the memory consumption as those + * Textures and Fonts will be in memory twice. *

* * @author mzechner - * + * */ -public interface Graphics -{ +public interface Graphics { /** - * Enumeration describing different types of - * {@link Graphics} implementations. Might be - * extended by say LWJGL. + * Enumeration describing different types of {@link Graphics} implementations. Might be extended by say LWJGL. * @author mzechner - * + * */ - public enum GraphicsType - { - AndroidGL, - JoglGL, - LWJGL + public enum GraphicsType { + AndroidGL, JoglGL, LWJGL } - + /** - * Returns whether OpenGL ES 1.1 is available. If it is - * you can get an instance of {@link GL11} via {@link getGL11()} - * to access OpenGL ES 1.1 functionality. + * Returns whether OpenGL ES 1.1 is available. If it is you can get an instance of {@link GL11} via {@link getGL11()} to access + * OpenGL ES 1.1 functionality. * * @return whether OpenGL ES 1.1 is available */ - public boolean isGL11Available( ); - + public boolean isGL11Available (); + /** - * Returns whether OpenGL ES 2.0 is available. If it is - * you can get an instance of {@link GL20} via {@link getGL20()} - * to access OpenGL ES 2.0 functionality. Note that this - * functionality will only be available if you instructed - * the Application instance to use OpenGL ES 2.0! + * Returns whether OpenGL ES 2.0 is available. If it is you can get an instance of {@link GL20} via {@link getGL20()} to access + * OpenGL ES 2.0 functionality. Note that this functionality will only be available if you instructed the Application instance + * to use OpenGL ES 2.0! * * @return whether OpenGL ES 2.0 is available * * @see DesktopApplication * @see AndroidApplication */ - public boolean isGL20Available( ); - + public boolean isGL20Available (); + /** * @return a {@link GLCommon} instance */ - public GLCommon getGLCommon( ); - + public GLCommon getGLCommon (); + /** * @return the {@link GL10} instance * @throws GdxRuntimeException in case the Application was configured to use OpenGL ES 2.0 */ - public GL10 getGL10( ); - + public GL10 getGL10 (); + /** * @return the {@link GL11} instance - * @throws GdxRuntimeException in case OpenGL ES 1.1 is not supported by the hardware or the Application was configured to use OpenGL ES 2.0 + * @throws GdxRuntimeException in case OpenGL ES 1.1 is not supported by the hardware or the Application was configured to use + * OpenGL ES 2.0 */ - public GL11 getGL11( ); - + public GL11 getGL11 (); + /** * @return the {@link GL20} instance - * @throws GdxRuntimeException in case OpenGL ES 2.0 is not supported by the hardware or the Application was configured to use OpenGL ES 1.x + * @throws GdxRuntimeException in case OpenGL ES 2.0 is not supported by the hardware or the Application was configured to use + * OpenGL ES 1.x */ - public GL20 getGL20( ); - + public GL20 getGL20 (); + /** * @return the width in pixels of the display surface */ - public int getWidth( ); - + public int getWidth (); + /** * @return the height in pixels of the display surface */ - public int getHeight( ); - + public int getHeight (); + /** * @return the time span between the current frame and the last frame in seconds */ - public float getDeltaTime( ); - + public float getDeltaTime (); + /** * @return the number of average frames per second */ - public int getFramesPerSecond( ); - + public int getFramesPerSecond (); + /** - * Sets the {@link RenderListener}. The RenderListener will be called - * once the OpenGL surface has been setup to give it an opportunity to - * create all its graphic resources like textures and meshes. After the - * setup is complete the RenderListener will be called continuously to - * render new frames. When the {@link Application} is closing the RenderListener + * Sets the {@link RenderListener}. The RenderListener will be called once the OpenGL surface has been setup to + * give it an opportunity to create all its graphic resources like textures and meshes. After the setup is complete the + * RenderListener will be called continuously to render new frames. When the {@link Application} is closing the RenderListener * will be called one last time to clean up. * * @param listener the RenderListener */ - public void setRenderListener( RenderListener listener ); - + public void setRenderListener (RenderListener listener); + /** - * Creates a new {@link Pixmap} with the specified dimensions and - * format. + * Creates a new {@link Pixmap} with the specified dimensions and format. * * @param width the width in pixels * @param height the height in pixels @@ -166,45 +147,42 @@ public interface Graphics * @return a new Pixmap * @throws GdxRuntimeException in case the pixmap could not be created */ - public Pixmap newPixmap( int width, int height, Pixmap.Format format ); - + public Pixmap newPixmap (int width, int height, Pixmap.Format format); + /** - * Creates a new {@link Pixmap} from the given InputStream which is assumed - * to point to a bitmap in a readable format, e.g. PNG, JPEG. The InputStream is not closed. + * Creates a new {@link Pixmap} from the given InputStream which is assumed to point to a bitmap in a readable format, e.g. + * PNG, JPEG. The InputStream is not closed. * * @param in the InputStream * @return a new Pixmap * @throws GdxRuntimeException in case the Pixmap could not be created. */ - public Pixmap newPixmap( InputStream in); - + public Pixmap newPixmap (InputStream in); + /** - * Creates a new {@link Pixmap} from the given file which is assumed - * to point to a bitmap in a readable format, e.g. PNG, JPEG. + * Creates a new {@link Pixmap} from the given file which is assumed to point to a bitmap in a readable format, e.g. PNG, JPEG. * * @param file the file to load the pixmap from * @return a new Pixmap * @throws GdxRuntimeException in case the Pixmap could not be created. */ - public Pixmap newPixmap( FileHandle file ); - + public Pixmap newPixmap (FileHandle file); + /** - * Creates a new {@link Pixmap} from the given native pixmap. The native - * pixmap is an instance of BufferedImage on the desktop or Bitmap on - * Android. + * Creates a new {@link Pixmap} from the given native pixmap. The native pixmap is an instance of BufferedImage on the desktop + * or Bitmap on Android. * * @param nativePixmap the native pixmap * @return a new Pixmap * @throws GdxRuntimeException in case the pixmap could not be created */ - public Pixmap newPixmap( Object nativePixmap ); + public Pixmap newPixmap (Object nativePixmap); /** - * Creates a new {@link Font} from the given font name, the size and the style. - * The font is looked up by name in the system fonts. In case no font with that - * name could be found a default font is returned. The Font has to be disposed - * once it's no longer used via the {@link Font.dispose()} method. The font is - * managed automatically and will be recreated when the OpenGL context is lost. + * Creates a new {@link Font} from the given font name, the size and the style. The font is looked up by name in the system + * fonts. In case no font with that name could be found a default font is returned. The Font has to be disposed once it's no + * longer used via the {@link Font.dispose()} method. The font is managed automatically and will be recreated when the OpenGL + * context is lost. * * @param fontName the font name * @param size the size @@ -212,12 +190,12 @@ public interface Graphics * @return a new Font * @throws GdxRuntimeException in case the Font could not be created */ - public Font newFont( String fontName, int size, Font.FontStyle style); - + public Font newFont (String fontName, int size, Font.FontStyle style); + /** - * Creates a new {@link Font} from the given file. The file must point to a true type font file. - * The Font has to be disposed once it's no longer used via the {@link Font.dispose()} method. - * The font is managed automatically and will be recreated when the OpenGL context is lost. + * Creates a new {@link Font} from the given file. The file must point to a true type font file. The Font has to be disposed + * once it's no longer used via the {@link Font.dispose()} method. The font is managed automatically and will be recreated when + * the OpenGL context is lost. * * @param file the file to load the font from * @param size the size @@ -225,15 +203,13 @@ public interface Graphics * @return a new Font * @throws GdxRuntimeException in case the Font could not be created */ - public Font newFont( FileHandle file, int size, Font.FontStyle style ); - + public Font newFont (FileHandle file, int size, Font.FontStyle style); + /** - * Creates a new {@link Texture} with the specified dimensions, minification - * and magnification filters and texture wraps in u and v. The Texture has - * to be disposed via the {@link Texture.dispose()} methods once it is no - * longer used. The width and height of the texture have to be a power of two! - * Textures created via this method can not be managed and have to be recreated - * manually when the OpenGL context is lost. + * Creates a new {@link Texture} with the specified dimensions, minification and magnification filters and texture wraps in u + * and v. The Texture has to be disposed via the {@link Texture.dispose()} methods once it is no longer used. The width and + * height of the texture have to be a power of two! Textures created via this method can not be managed and have to be + * recreated manually when the OpenGL context is lost. * * @param width the width in pixels, has to be a power of 2 * @param height the height in pixels, has to be a power of 2 @@ -245,17 +221,15 @@ public interface Graphics * @return a new Texture * @throws GdxRuntimeException in case the Texture could not be created */ - public Texture newUnmanagedTexture( int width, int height, Format format, Texture.TextureFilter minFilter, Texture.TextureFilter magFilter, Texture.TextureWrap uWrap, Texture.TextureWrap vWrap ); - + public Texture newUnmanagedTexture (int width, int height, Format format, Texture.TextureFilter minFilter, + Texture.TextureFilter magFilter, Texture.TextureWrap uWrap, Texture.TextureWrap vWrap); + /** - * Creates a new {@link Texture} from the given {@link Pixmap} using - * the specified minification and magnification filter and texture wraps in - * u and v. If the minification filter is specified as {@link Texture.TextureFilter.MipMap} - * mip maps will be created automatically. The Texture has - * to be disposed via the {@link Texture.dispose()} methods once it is no - * longer used. The Pixmap's width and height have to be a power of 2! - * Textures created via this method can not be managed and have to be recreated - * manually when the OpenGL context is lost. + * Creates a new {@link Texture} from the given {@link Pixmap} using the specified minification and magnification filter and + * texture wraps in u and v. If the minification filter is specified as {@link Texture.TextureFilter.MipMap} mip maps will be + * created automatically. The Texture has to be disposed via the {@link Texture.dispose()} methods once it is no longer used. + * The Pixmap's width and height have to be a power of 2! Textures created via this method can not be managed and have to be + * recreated manually when the OpenGL context is lost. * * @param pixmap the pixmap * @param minFilter the minification {@link Texture.TextureFilter} @@ -265,18 +239,16 @@ public interface Graphics * @return a new Texture * @throws GdxRuntimeException in case the texture could not be created */ - public Texture newUnmanagedTexture( Pixmap pixmap, Texture.TextureFilter minFilter, Texture.TextureFilter magFilter, Texture.TextureWrap uWrap, Texture.TextureWrap vWrap ); - + public Texture newUnmanagedTexture (Pixmap pixmap, Texture.TextureFilter minFilter, Texture.TextureFilter magFilter, + Texture.TextureWrap uWrap, Texture.TextureWrap vWrap); + /** - * Creates a new {@link Texture} from the given {@link FileHandle} using - * the specified minification and magnification filter and texture wraps in - * u and v. If the minification filter is specified as {@link Texture.TextureFilter.MipMap} - * mip maps will be created automatically. The Texture has - * to be disposed via the {@link Texture.dispose()} methods once it is no - * longer used. The FileHandle must point to a valid Jpg, Bmp or Png file. - * The Pixmap's width and height have to be a power of 2! - * Textures created via this method are managed and will be recreated automatically after - * the OpenGL context has been lost and recreated. + * Creates a new {@link Texture} from the given {@link FileHandle} using the specified minification and magnification filter + * and texture wraps in u and v. If the minification filter is specified as {@link Texture.TextureFilter.MipMap} mip maps will + * be created automatically. The Texture has to be disposed via the {@link Texture.dispose()} methods once it is no longer + * used. The FileHandle must point to a valid Jpg, Bmp or Png file. The Pixmap's width and height have to be a power of 2! + * Textures created via this method are managed and will be recreated automatically after the OpenGL context has been lost and + * recreated. * * @param file the FileHandle pointing to a Jpg, Bmp or Png file. * @param minFilter the minification {@link Texture.TextureFilter} @@ -286,10 +258,11 @@ public interface Graphics * @return a new Texture * @throws GdxRuntimeException in case the texture could not be created */ - public Texture newTexture( FileHandle file, Texture.TextureFilter minFilter, Texture.TextureFilter magFilter, Texture.TextureWrap uWrap, Texture.TextureWrap vWrap ); - + public Texture newTexture (FileHandle file, Texture.TextureFilter minFilter, Texture.TextureFilter magFilter, + Texture.TextureWrap uWrap, Texture.TextureWrap vWrap); + /** * @return the {@link GraphicsType} of this Graphics instance */ - public GraphicsType getType( ); + public GraphicsType getType (); } diff --git a/gdx/src/com/badlogic/gdx/Input.java b/gdx/src/com/badlogic/gdx/Input.java index bc1ed99f9..03f121ac2 100644 --- a/gdx/src/com/badlogic/gdx/Input.java +++ b/gdx/src/com/badlogic/gdx/Input.java @@ -1,285 +1,269 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; /** *

- * Interface to the input facilities. This allows to poll the state - * of the keyboard, touch screen and accelerometer. On the desktop - * the touch screen is replaced by mouse input, the accelerometer is - * of course not available. + * Interface to the input facilities. This allows to poll the state of the keyboard, touch screen and accelerometer. On the + * desktop the touch screen is replaced by mouse input, the accelerometer is of course not available. *

* - *

Additionally one can register an {@link - * InputListener} with this module. The InputListener will then be - * called each time a key is pressed or released or a touch event occures. + *

+ * Additionally one can register an {@link InputListener} with this module. The InputListener will then be called each time a key + * is pressed or released or a touch event occures. *

* *

- * The InputListener will be called in the rendering thread of the - * graphics module to which a RenderListener is probably attached. This - * means that one does not have to take precautions to guarantee thread - * safety. One can safely call graphics methods from within the InputListener - * callbacks. + * The InputListener will be called in the rendering thread of the graphics module to which a RenderListener is probably attached. + * This means that one does not have to take precautions to guarantee thread safety. One can safely call graphics methods from + * within the InputListener callbacks. *

* *

- * One or more InputListeners can be registered with the module. - * The events will then get passed to the InputListeners in the order they - * have been registered with the module. If an InputListeners signals that - * it consumed the event the InputListeners down the chain will not be invoked. + * One or more InputListeners can be registered with the module. The events will then get passed to the InputListeners in the + * order they have been registered with the module. If an InputListeners signals that it consumed the event the InputListeners + * down the chain will not be invoked. *

* *

- * Keyboard keys are translated to the constants in {@link Keys} transparantely - * on all systems. Do not use system specific key constants. + * Keyboard keys are translated to the constants in {@link Keys} transparantely on all systems. Do not use system specific key + * constants. *

* * @author mzechner - * + * */ -public interface Input -{ +public interface Input { /** * Callback interface for {@link Application.getTextInput()} * * @author badlogicgames@gmail.com - * + * */ - public interface TextInputListener - { - public void input( String text ); + public interface TextInputListener { + public void input (String text); } - + /** - * Keys. + * Keys. * * @author badlogicgames@gmail.com - * - */ - public class Keys - { - public static int ANY_KEY = -1; - public static int KEYCODE_0 = 7; - public static int KEYCODE_1 = 8; - public static int KEYCODE_2 = 9; - public static int KEYCODE_3 = 10; - public static int KEYCODE_4 = 11; - public static int KEYCODE_5 = 12; - public static int KEYCODE_6 = 13; - public static int KEYCODE_7 = 14; - public static int KEYCODE_8 = 15; - public static int KEYCODE_9 = 16; - public static int KEYCODE_A = 29; - public static int KEYCODE_ALT_LEFT = 57; - public static int KEYCODE_ALT_RIGHT = 58; - public static int KEYCODE_APOSTROPHE = 75; - public static int KEYCODE_AT = 77; - public static int KEYCODE_B = 30; - public static int KEYCODE_BACK = 4; - public static int KEYCODE_BACKSLASH = 73; - public static int KEYCODE_C = 31; - public static int KEYCODE_CALL = 5; - public static int KEYCODE_CAMERA = 27; - public static int KEYCODE_CLEAR = 28; - public static int KEYCODE_COMMA = 55; - public static int KEYCODE_D = 32; - public static int KEYCODE_DEL = 67; - public static int KEYCODE_DPAD_CENTER = 23; - public static int KEYCODE_DPAD_DOWN = 20; - public static int KEYCODE_DPAD_LEFT = 21; - public static int KEYCODE_DPAD_RIGHT = 22; - public static int KEYCODE_DPAD_UP = 19; - public static int KEYCODE_E = 33; - public static int KEYCODE_ENDCALL = 6; - public static int KEYCODE_ENTER = 66; - public static int KEYCODE_ENVELOPE = 65; - public static int KEYCODE_EQUALS = 70; - public static int KEYCODE_EXPLORER = 64; - public static int KEYCODE_F = 34; - public static int KEYCODE_FOCUS = 80; - public static int KEYCODE_G = 35; - public static int KEYCODE_GRAVE = 68; - public static int KEYCODE_H = 36; - public static int KEYCODE_HEADSETHOOK = 79; - public static int KEYCODE_HOME = 3; - public static int KEYCODE_I = 37; - public static int KEYCODE_J = 38; - public static int KEYCODE_K = 39; - public static int KEYCODE_L = 40; - public static int KEYCODE_LEFT_BRACKET = 71; - public static int KEYCODE_M = 41; - public static int KEYCODE_MEDIA_FAST_FORWARD = 90; - public static int KEYCODE_MEDIA_NEXT = 87; - public static int KEYCODE_MEDIA_PLAY_PAUSE = 85; - public static int KEYCODE_MEDIA_PREVIOUS = 88; - public static int KEYCODE_MEDIA_REWIND = 89; - public static int KEYCODE_MEDIA_STOP = 86; - public static int KEYCODE_MENU = 82; - public static int KEYCODE_MINUS = 69; - public static int KEYCODE_MUTE = 91; - public static int KEYCODE_N = 42; - public static int KEYCODE_NOTIFICATION = 83; - public static int KEYCODE_NUM = 78; - public static int KEYCODE_O = 43; - public static int KEYCODE_P = 44; - public static int KEYCODE_PERIOD = 56; - public static int KEYCODE_PLUS = 81; - public static int KEYCODE_POUND = 18; - public static int KEYCODE_POWER = 26; - public static int KEYCODE_Q = 45; - public static int KEYCODE_R = 46; - public static int KEYCODE_RIGHT_BRACKET = 72; - public static int KEYCODE_S = 47; - public static int KEYCODE_SEARCH = 84; - public static int KEYCODE_SEMICOLON = 74; - public static int KEYCODE_SHIFT_LEFT = 59; - public static int KEYCODE_SHIFT_RIGHT = 60; - public static int KEYCODE_SLASH = 76; - public static int KEYCODE_SOFT_LEFT = 1; - public static int KEYCODE_SOFT_RIGHT = 2; - public static int KEYCODE_SPACE = 62; - public static int KEYCODE_STAR = 17; - public static int KEYCODE_SYM = 63; - public static int KEYCODE_T = 48; - public static int KEYCODE_TAB = 61; - public static int KEYCODE_U = 49; - public static int KEYCODE_UNKNOWN = 0; - public static int KEYCODE_V = 50; - public static int KEYCODE_VOLUME_DOWN = 25; - public static int KEYCODE_VOLUME_UP = 24; - public static int KEYCODE_W = 51; - public static int KEYCODE_X = 52; - public static int KEYCODE_Y = 53; - public static int KEYCODE_Z = 54; - public static int META_ALT_LEFT_ON = 16; - public static int META_ALT_ON = 2; - public static int META_ALT_RIGHT_ON = 32; - public static int META_SHIFT_LEFT_ON = 64; - public static int META_SHIFT_ON = 1; - public static int META_SHIFT_RIGHT_ON = 128; - public static int META_SYM_ON = 4; + * + */ + public class Keys { + public static int ANY_KEY = -1; + public static int KEYCODE_0 = 7; + public static int KEYCODE_1 = 8; + public static int KEYCODE_2 = 9; + public static int KEYCODE_3 = 10; + public static int KEYCODE_4 = 11; + public static int KEYCODE_5 = 12; + public static int KEYCODE_6 = 13; + public static int KEYCODE_7 = 14; + public static int KEYCODE_8 = 15; + public static int KEYCODE_9 = 16; + public static int KEYCODE_A = 29; + public static int KEYCODE_ALT_LEFT = 57; + public static int KEYCODE_ALT_RIGHT = 58; + public static int KEYCODE_APOSTROPHE = 75; + public static int KEYCODE_AT = 77; + public static int KEYCODE_B = 30; + public static int KEYCODE_BACK = 4; + public static int KEYCODE_BACKSLASH = 73; + public static int KEYCODE_C = 31; + public static int KEYCODE_CALL = 5; + public static int KEYCODE_CAMERA = 27; + public static int KEYCODE_CLEAR = 28; + public static int KEYCODE_COMMA = 55; + public static int KEYCODE_D = 32; + public static int KEYCODE_DEL = 67; + public static int KEYCODE_DPAD_CENTER = 23; + public static int KEYCODE_DPAD_DOWN = 20; + public static int KEYCODE_DPAD_LEFT = 21; + public static int KEYCODE_DPAD_RIGHT = 22; + public static int KEYCODE_DPAD_UP = 19; + public static int KEYCODE_E = 33; + public static int KEYCODE_ENDCALL = 6; + public static int KEYCODE_ENTER = 66; + public static int KEYCODE_ENVELOPE = 65; + public static int KEYCODE_EQUALS = 70; + public static int KEYCODE_EXPLORER = 64; + public static int KEYCODE_F = 34; + public static int KEYCODE_FOCUS = 80; + public static int KEYCODE_G = 35; + public static int KEYCODE_GRAVE = 68; + public static int KEYCODE_H = 36; + public static int KEYCODE_HEADSETHOOK = 79; + public static int KEYCODE_HOME = 3; + public static int KEYCODE_I = 37; + public static int KEYCODE_J = 38; + public static int KEYCODE_K = 39; + public static int KEYCODE_L = 40; + public static int KEYCODE_LEFT_BRACKET = 71; + public static int KEYCODE_M = 41; + public static int KEYCODE_MEDIA_FAST_FORWARD = 90; + public static int KEYCODE_MEDIA_NEXT = 87; + public static int KEYCODE_MEDIA_PLAY_PAUSE = 85; + public static int KEYCODE_MEDIA_PREVIOUS = 88; + public static int KEYCODE_MEDIA_REWIND = 89; + public static int KEYCODE_MEDIA_STOP = 86; + public static int KEYCODE_MENU = 82; + public static int KEYCODE_MINUS = 69; + public static int KEYCODE_MUTE = 91; + public static int KEYCODE_N = 42; + public static int KEYCODE_NOTIFICATION = 83; + public static int KEYCODE_NUM = 78; + public static int KEYCODE_O = 43; + public static int KEYCODE_P = 44; + public static int KEYCODE_PERIOD = 56; + public static int KEYCODE_PLUS = 81; + public static int KEYCODE_POUND = 18; + public static int KEYCODE_POWER = 26; + public static int KEYCODE_Q = 45; + public static int KEYCODE_R = 46; + public static int KEYCODE_RIGHT_BRACKET = 72; + public static int KEYCODE_S = 47; + public static int KEYCODE_SEARCH = 84; + public static int KEYCODE_SEMICOLON = 74; + public static int KEYCODE_SHIFT_LEFT = 59; + public static int KEYCODE_SHIFT_RIGHT = 60; + public static int KEYCODE_SLASH = 76; + public static int KEYCODE_SOFT_LEFT = 1; + public static int KEYCODE_SOFT_RIGHT = 2; + public static int KEYCODE_SPACE = 62; + public static int KEYCODE_STAR = 17; + public static int KEYCODE_SYM = 63; + public static int KEYCODE_T = 48; + public static int KEYCODE_TAB = 61; + public static int KEYCODE_U = 49; + public static int KEYCODE_UNKNOWN = 0; + public static int KEYCODE_V = 50; + public static int KEYCODE_VOLUME_DOWN = 25; + public static int KEYCODE_VOLUME_UP = 24; + public static int KEYCODE_W = 51; + public static int KEYCODE_X = 52; + public static int KEYCODE_Y = 53; + public static int KEYCODE_Z = 54; + public static int META_ALT_LEFT_ON = 16; + public static int META_ALT_ON = 2; + public static int META_ALT_RIGHT_ON = 32; + public static int META_SHIFT_LEFT_ON = 64; + public static int META_SHIFT_ON = 1; + public static int META_SHIFT_RIGHT_ON = 128; + public static int META_SYM_ON = 4; } - + /** - * Adds an {@link InputListener}. The order InputListeners - * are added is the same as the order in which they are called in case of an event. If an input - * listener signals that it processed the event the event is not passed to - * the other listeners in the chain. + * Adds an {@link InputListener}. The order InputListeners are added is the same as the order in which they are called in case + * of an event. If an input listener signals that it processed the event the event is not passed to the other listeners in the + * chain. * * @param listener the listener */ - public void addInputListener( InputListener listener ); - + public void addInputListener (InputListener listener); + /** * Removes the {@link InputListener}. * @param listener the listener */ - public void removeInputListener( InputListener listener ); - - /** + public void removeInputListener (InputListener listener); + + /** * @return whether an accelerometer is available */ - public boolean isAccelerometerAvailable( ); - - /** + public boolean isAccelerometerAvailable (); + + /** * @return The value of the accelerometer on its x-axis. ranges between [-10,10]. */ - public float getAccelerometerX( ); - - /** + public float getAccelerometerX (); + + /** * @return The value of the accelerometer on its y-axis. ranges between [-10,10]. */ - public float getAccelerometerY( ); - - /** + public float getAccelerometerY (); + + /** * @return The value of the accelerometer on its y-axis. ranges between [-10,10]. */ - public float getAccelerometerZ( ); - + public float getAccelerometerZ (); + /** * @return the last touch x coordinate in screen coordinates. The screen origin is the top left corner. */ - public int getX( ); - + public int getX (); + /** - * Returns the x coordinate in screen coordinates of the given pointer. Pointers are indexed from 0 to n. The - * pointer id identifies the order in which the fingers went down on the screen, e.g. 0 is the first finger, 1 - * is the second and so on. When two fingers are touched down and the first one is lifted the second one becomes - * the first one. + * Returns the x coordinate in screen coordinates of the given pointer. Pointers are indexed from 0 to n. The pointer id + * identifies the order in which the fingers went down on the screen, e.g. 0 is the first finger, 1 is the second and so on. + * When two fingers are touched down and the first one is lifted the second one becomes the first one. * @param pointer the pointer id. * @return the x coordinate */ - public int getX( int pointer ); - + public int getX (int pointer); + /** * @return the last touch y coordinate in screen coordinates. The screen origin is the top left corner. */ - public int getY( ); - + public int getY (); + /** - * Returns the y coordinate in screen coordinates of the given pointer. Pointers are indexed from 0 to n. The - * pointer id identifies the order in which the fingers went down on the screen, e.g. 0 is the first finger, 1 - * is the second and so on. When two fingers are touched down and the first one is lifted the second one becomes - * the first one. + * Returns the y coordinate in screen coordinates of the given pointer. Pointers are indexed from 0 to n. The pointer id + * identifies the order in which the fingers went down on the screen, e.g. 0 is the first finger, 1 is the second and so on. + * When two fingers are touched down and the first one is lifted the second one becomes the first one. * * @param pointer the pointer id. * @return the y coordinate */ - public int getY( int pointer ); - + public int getY (int pointer); + /** * @return whether the screen is currently touched. */ - public boolean isTouched( ); - + public boolean isTouched (); + /** * Whether the screen is currently touched by the pointer with the given index. * @param pointer the pointer * @return whether the screen is touched by the pointer */ - public boolean isTouched( int pointer ); - + public boolean isTouched (int pointer); + /** * Returns whether the key is pressed. * * @param key The key code as found in {@link Input.Keys}. * @return true or false. */ - public boolean isKeyPressed( int key ); - + public boolean isKeyPressed (int key); + /** - * System dependent method to input a string of text. A dialog - * box will be created with the given title and the given text - * as a message for the user. Once the dialog has been closed - * the provided {@link TextInputListener} will be called in the - * rendering thread. + * System dependent method to input a string of text. A dialog box will be created with the given title and the given text as a + * message for the user. Once the dialog has been closed the provided {@link TextInputListener} will be called in the rendering + * thread. * * @param listener The TextInputListener. * @param title The title of the text input dialog. * @param text The message presented to the user. */ - public void getTextInput( TextInputListener listener, String title, String text ); - + public void getTextInput (TextInputListener listener, String title, String text); + /** - * Returns whether multitouch is supported by the device. Note that this - * also includes the broken multitouch on the Droid or Nexus One! This will - * only work correctly from Android version 2.1 onwards. + * Returns whether multitouch is supported by the device. Note that this also includes the broken multitouch on the Droid or + * Nexus One! This will only work correctly from Android version 2.1 onwards. * * @return whether multitouch is supported */ - public boolean supportsMultitouch( ); + public boolean supportsMultitouch (); } diff --git a/gdx/src/com/badlogic/gdx/InputListener.java b/gdx/src/com/badlogic/gdx/InputListener.java index a05aae28e..2c81d35c4 100644 --- a/gdx/src/com/badlogic/gdx/InputListener.java +++ b/gdx/src/com/badlogic/gdx/InputListener.java @@ -1,82 +1,77 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ -package com.badlogic.gdx; +package com.badlogic.gdx; /** - * An InputListener is used to receive input events from the keyboard and the touch screen (mouse on the desktop). For this - * it has to be registered with the {@link Input} instance of an {@link Application}. The - * events might arrive asynchronously in a UI thread, the {@link Input} instance will buffer those events - * and invoke the methods of the listener in the rendering thread to get rid of the need to synchronize - * the UI and renderer thread for input. If an InputListener signals that it processed an event by - * returning true the the event will not be passed to other listeners in the listener chain (multiple - * InputListeners can register with an Input instance). + * An InputListener is used to receive input events from the keyboard and the touch screen (mouse on the desktop). For this it has + * to be registered with the {@link Input} instance of an {@link Application}. The events might arrive asynchronously in a UI + * thread, the {@link Input} instance will buffer those events and invoke the methods of the listener in the rendering thread to + * get rid of the need to synchronize the UI and renderer thread for input. If an InputListener signals that it processed an event + * by returning true the the event will not be passed to other listeners in the listener chain (multiple InputListeners can + * register with an Input instance). * * @author badlogicgames@gmail.com - * + * */ -public interface InputListener -{ +public interface InputListener { /** * Called when a key was pressed * @param keycode one of the constants in {@link Input.Keys} * @return whether the input was processed */ - public boolean keyDown( int keycode ); - + public boolean keyDown (int keycode); + /** * Called when a key was released - * @param keycode one of the constants in {@link Input.Keys} + * @param keycode one of the constants in {@link Input.Keys} */ - public boolean keyUp( int keycode ); - + public boolean keyUp (int keycode); + /** * Called when a key was typed * @param character The character * @return whether the input was processed */ - public boolean keyTyped( char character ); - + public boolean keyTyped (char character); + /** - * Called when the screen was touched or the mouse was pressed. + * Called when the screen was touched or the mouse was pressed. * * @param x The x coordinate, origin is in the upper left corner * @param y The y coordinate, origin is in the upper left corner * @param pointer the pointer for the event. Unsupported yet, used for multitouch later on. * @return whether the input was processed */ - public boolean touchDown( int x, int y, int pointer ); - + public boolean touchDown (int x, int y, int pointer); + /** - * Called when a finger was lifted or a mouse button was released. + * Called when a finger was lifted or a mouse button was released. * * @param x The x coordinate * @param y The y coordinate * @param pointer the pointer for the event. Unsupported yet, used for multitouch later on. * @return whether the input was processed */ - public boolean touchUp( int x, int y, int pointer ); - + public boolean touchUp (int x, int y, int pointer); + /** - * Called when a finger or the mouse was dragged. + * Called when a finger or the mouse was dragged. * * @param x The x coordinate * @param y The y coordinate * @param pointer the pointer for the event. Unsupported yet, used for multitouch later on. * @return whether the input was processed */ - public boolean touchDragged( int x, int y, int pointer ); + public boolean touchDragged (int x, int y, int pointer); } diff --git a/gdx/src/com/badlogic/gdx/RenderListener.java b/gdx/src/com/badlogic/gdx/RenderListener.java index ccf5f4b99..8b881fd8f 100644 --- a/gdx/src/com/badlogic/gdx/RenderListener.java +++ b/gdx/src/com/badlogic/gdx/RenderListener.java @@ -1,72 +1,57 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ -package com.badlogic.gdx; -import com.badlogic.gdx.Application; +package com.badlogic.gdx; /** - * A RenderListener can be hooked to a {@link Graphics} instance - * and will receive setup, render and dispose events. In case - * of a setup event the listener can create any resources it - * needs later on to draw. The setup method is also called when - * the OpenGL surface has been recreated after a context loss. This happens only on - * Android in case the application was paused and resumed. All - * OpenGL resources like textures, meshes and shaders are lost and have to - * be recreated. The render method is called whenever the {@link Application} is redrawn. The - * dispose method is called before the Application is closed - * or the RenderListener is unregistered from the Graphics instance. + * A RenderListener can be hooked to a {@link Graphics} instance and will receive setup, render and dispose events. In case of a + * setup event the listener can create any resources it needs later on to draw. The setup method is also called when the OpenGL + * surface has been recreated after a context loss. This happens only on Android in case the application was paused and resumed. + * All OpenGL resources like textures, meshes and shaders are lost and have to be recreated. The render method is called whenever + * the {@link Application} is redrawn. The dispose method is called before the Application is closed or the RenderListener is + * unregistered from the Graphics instance. * - * The methods will be invoked in the rendering thread of the - * application and not in the UI thread! + * The methods will be invoked in the rendering thread of the application and not in the UI thread! * * * @author badlogicgames@gmail.com - * + * */ -public interface RenderListener -{ - /** - * The setup method is called once upon initialization of - * the {@link Application} and every time the OpenGL surface - * is recreated. On Android this happens when the application - * is unpaused after it was paused by a press of the home button - * or an incoming call. All unmanaged textures have to be recreated - * manually, all other resources will be reloaded automatically. +public interface RenderListener { + /** + * The setup method is called once upon initialization of the {@link Application} and every time the OpenGL surface is + * recreated. On Android this happens when the application is unpaused after it was paused by a press of the home button or an + * incoming call. All unmanaged textures have to be recreated manually, all other resources will be reloaded automatically. * */ - public void surfaceCreated( ); - + public void surfaceCreated (); + /** * Called when the OpenGL surface changed it's dimensions. * * @param width the width of the surface in pixels * @param height the height of the surface in pixels */ - public void surfaceChanged( int width, int height ); - + public void surfaceChanged (int width, int height); + /** - * The render method is called every time a new frame - * should be rendered. + * The render method is called every time a new frame should be rendered. */ - public void render( ); - + public void render (); + /** - * The dispose method is called when the application is closing - * or the {@link RenderListener} has been unregistered from the + * The dispose method is called when the application is closing or the {@link RenderListener} has been unregistered from the * Graphics instance. - */ - public void dispose( ); + */ + public void dispose (); } diff --git a/gdx/src/com/badlogic/gdx/Version.java b/gdx/src/com/badlogic/gdx/Version.java index 9e5d88ea1..37643e3ba 100644 --- a/gdx/src/com/badlogic/gdx/Version.java +++ b/gdx/src/com/badlogic/gdx/Version.java @@ -1,33 +1,29 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; /** * The version of libgdx * * @author mzechner - * + * */ -public class Version -{ +public class Version { /** the current version of libgdx in the major.minor format **/ public static String VERSION = "0.71"; - - public static void loadLibrary() - { - System.loadLibrary( "gdx" ); + + public static void loadLibrary () { + System.loadLibrary("gdx"); } } diff --git a/gdx/src/com/badlogic/gdx/audio/AudioDevice.java b/gdx/src/com/badlogic/gdx/audio/AudioDevice.java index c5d7c4b72..d9785979f 100644 --- a/gdx/src/com/badlogic/gdx/audio/AudioDevice.java +++ b/gdx/src/com/badlogic/gdx/audio/AudioDevice.java @@ -1,61 +1,52 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.audio; /** - * Encapsulates an audio device in 44.1khz mono or stereo mode. Use - * the {@link AudioDevice.writeSamples()} methods to write - * float or 16-bit signed short PCM data directly to the - * audio device. Stereo samples are interleaved in the order left channel - * sample, right channel sample. The {@link dispose()} method must be called - * when this AudioDevice is no longer needed. + * Encapsulates an audio device in 44.1khz mono or stereo mode. Use the {@link AudioDevice.writeSamples()} methods to write float + * or 16-bit signed short PCM data directly to the audio device. Stereo samples are interleaved in the order left channel sample, + * right channel sample. The {@link dispose()} method must be called when this AudioDevice is no longer needed. * * @author badlogicgames@gmail.com - * + * */ -public interface AudioDevice -{ +public interface AudioDevice { /** - * @return whether this AudioDevice is in mono or stereo mode. + * @return whether this AudioDevice is in mono or stereo mode. */ - public boolean isMono( ); - + public boolean isMono (); + /** - * Writes the array of 16-bit signed PCM samples to the - * audio device and blocks until they have been processed. + * Writes the array of 16-bit signed PCM samples to the audio device and blocks until they have been processed. * * @param samples The samples. * @param offset The offset into the samples array * @param numSamples the number of samples to write to the device */ - public void writeSamples( short[] samples, int offset, int numSamples ); - + public void writeSamples (short[] samples, int offset, int numSamples); + /** - * Writes the array of float PCM samples to the - * audio device and blocks until they have been processed. + * Writes the array of float PCM samples to the audio device and blocks until they have been processed. * * @param samples The samples. * @param offset The offset into the samples array * @param numSamples the number of samples to write to the device */ - public void writeSamples( float[] samples, int offset, int numSamples ); - + public void writeSamples (float[] samples, int offset, int numSamples); + /** - * Frees all resources associated with this AudioDevice. Needs - * to be called when the device is no longer needed. + * Frees all resources associated with this AudioDevice. Needs to be called when the device is no longer needed. */ - public void dispose( ); + public void dispose (); } diff --git a/gdx/src/com/badlogic/gdx/audio/AudioRecorder.java b/gdx/src/com/badlogic/gdx/audio/AudioRecorder.java index 787e60660..525892f78 100644 --- a/gdx/src/com/badlogic/gdx/audio/AudioRecorder.java +++ b/gdx/src/com/badlogic/gdx/audio/AudioRecorder.java @@ -1,43 +1,38 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.audio; /** - * An AudioRecorder allows to record input from an audio device. It - * has a sampling rate and is either stereo or mono. Samples are returned - * in signed 16-bit PCM format. + * An AudioRecorder allows to record input from an audio device. It has a sampling rate and is either stereo or mono. Samples are + * returned in signed 16-bit PCM format. * * @author mzechner - * + * */ -public interface AudioRecorder -{ +public interface AudioRecorder { /** - * Reads in numSamples samples into the array samples starting at - * offset. If the recorder is in stereo you have to multiply numSamples - * by 2. + * Reads in numSamples samples into the array samples starting at offset. If the recorder is in stereo you have to multiply + * numSamples by 2. * * @param samples the array to write the samples to * @param offset the offset into the array * @param numSamples the number of samples to be read */ - public void read( short[] samples, int offset, int numSamples ); - + public void read (short[] samples, int offset, int numSamples); + /** * Disposes the AudioRecorder */ - public void dispose( ); + public void dispose (); } diff --git a/gdx/src/com/badlogic/gdx/audio/Music.java b/gdx/src/com/badlogic/gdx/audio/Music.java index 91affc8fa..45753f7b1 100644 --- a/gdx/src/com/badlogic/gdx/audio/Music.java +++ b/gdx/src/com/badlogic/gdx/audio/Music.java @@ -1,80 +1,69 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.audio; /** - * A Music instance represents a streamed audio file which is played back. The interface - * supports setting the playback position, pausing and resuming and so on. When you are - * done with using the Music instance you have to dispose it via the {@link Music.dispose()} - * method. + * A Music instance represents a streamed audio file which is played back. The interface supports setting the playback position, + * pausing and resuming and so on. When you are done with using the Music instance you have to dispose it via the {@link + * Music.dispose()} method. * @author mzechner - * + * */ -public interface Music -{ +public interface Music { /** - * Starts the playback of the music stream. - * In case the stream was paused this will - * resume the playback. In case the music stream - * is finished playing this will restart the playback. + * Starts the playback of the music stream. In case the stream was paused this will resume the playback. In case the music + * stream is finished playing this will restart the playback. */ - public void play( ); - + public void play (); + /** - * Pauses the playback. If the music stream has - * not been started yet or has finished playing - * a call to this method will be ignored. + * Pauses the playback. If the music stream has not been started yet or has finished playing a call to this method will be + * ignored. */ - public void pause( ); - + public void pause (); + /** - * Stops a playing or paused Music instance. Next time play() - * is invoked the Music will start from the beginning. + * Stops a playing or paused Music instance. Next time play() is invoked the Music will start from the beginning. */ - public void stop( ); - + public void stop (); + /** * @return whether this music stream is playing or not */ - public boolean isPlaying( ); - + public boolean isPlaying (); + /** - * Sets whether the music stream is looping or not. This - * can be called at any time, whether the stream is playing - * or not. + * Sets whether the music stream is looping or not. This can be called at any time, whether the stream is playing or not. * * @param isLooping whether to loop the stream or not */ - public void setLooping( boolean isLooping ); - + public void setLooping (boolean isLooping); + /** - * @return whether the music stream is playing or not. + * @return whether the music stream is playing or not. */ - public boolean isLooping( ); - + public boolean isLooping (); + /** - * Sets the volume of this music stream. The volume - * must be given in the range [0,1] with 0 being silent - * and 1 being the maximum volume. + * Sets the volume of this music stream. The volume must be given in the range [0,1] with 0 being silent and 1 being the + * maximum volume. * @param volume */ - public void setVolume( float volume ); - + public void setVolume (float volume); + /** * Needs to be called when the Music is no longer needed. */ - public void dispose( ); + public void dispose (); } diff --git a/gdx/src/com/badlogic/gdx/audio/Sound.java b/gdx/src/com/badlogic/gdx/audio/Sound.java index 817fb3f85..a99a7061f 100644 --- a/gdx/src/com/badlogic/gdx/audio/Sound.java +++ b/gdx/src/com/badlogic/gdx/audio/Sound.java @@ -1,48 +1,40 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.audio; /** - * A Sound is a short audio clip that can be played numerous times in parallel. - * It's completely loaded into memory. Call the {@link Sound.dispose()} - * method when you're done using the Sound. + * A Sound is a short audio clip that can be played numerous times in parallel. It's completely loaded into memory. Call the + * {@link Sound.dispose()} method when you're done using the Sound. * * @author badlogicgames@gmail.com - * + * */ -public interface Sound -{ +public interface Sound { /** - * Plays the sound, you can call this repeatedly to - * play the same sound a couple of times with a bit - * of lag introduced. + * Plays the sound, you can call this repeatedly to play the same sound a couple of times with a bit of lag introduced. */ - public void play( ); - + public void play (); + /** - * Plays the sound, you can call this repeatedly to - * play the same sound a couple of times with a bit - * of lag introduced. + * Plays the sound, you can call this repeatedly to play the same sound a couple of times with a bit of lag introduced. * * @param volume the volume in the range [0,1] */ - public void play( float volume ); - + public void play (float volume); + /** * Releases all the resources. */ - public void dispose( ); + public void dispose (); } diff --git a/gdx/src/com/badlogic/gdx/audio/analysis/AudioTools.java b/gdx/src/com/badlogic/gdx/audio/analysis/AudioTools.java index 332321b85..b1958342c 100644 --- a/gdx/src/com/badlogic/gdx/audio/analysis/AudioTools.java +++ b/gdx/src/com/badlogic/gdx/audio/analysis/AudioTools.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.audio.analysis; import java.nio.ByteBuffer; @@ -21,120 +19,115 @@ import java.nio.FloatBuffer; import java.nio.ShortBuffer; /** - * Class holding various static native methods for processing - * audio data. + * Class holding various static native methods for processing audio data. * * @author mzechner - * + * */ -public class AudioTools -{ +public class AudioTools { /** - * Converts the 16-bit signed PCM data given in source to 32-bit float PCM - * in the range [-1,1]. It is assumed that there's numSamples elements available - * in both buffers. Source and target get read and written to from offset 0. + * Converts the 16-bit signed PCM data given in source to 32-bit float PCM in the range [-1,1]. It is assumed that there's + * numSamples elements available in both buffers. Source and target get read and written to from offset 0. * * @param source the source buffer * @param target the target buffer * @param numSamples the number of samples */ - public static native void convertToFloat( ShortBuffer source, FloatBuffer target, int numSamples ); + public static native void convertToFloat (ShortBuffer source, FloatBuffer target, int numSamples); /** - * Converts the 32-bit float PCM data given in source to 16-bit signed PCM - * in the range [-1,1]. It is assumed that there's numSamples elements available - * in both buffers. Source and target get read and written to from offset 0. + * Converts the 32-bit float PCM data given in source to 16-bit signed PCM in the range [-1,1]. It is assumed that there's + * numSamples elements available in both buffers. Source and target get read and written to from offset 0. * * @param source the source buffer * @param target the target buffer * @param numSamples the number of samples */ - public static native void convertToShort( FloatBuffer source, FloatBuffer target, int numSamples ); - + public static native void convertToShort (FloatBuffer source, FloatBuffer target, int numSamples); + /** - * Converts the samples in source which are assumed to be interleaved left/right stereo samples - * to mono, writting the converted samples to target. Source is assumed to hold numSamples samples, - * target should hold numSamples / 2. Samples are read and written from position 0 up to numSamples. + * Converts the samples in source which are assumed to be interleaved left/right stereo samples to mono, writting the converted + * samples to target. Source is assumed to hold numSamples samples, target should hold numSamples / 2. Samples are read and + * written from position 0 up to numSamples. * * @param source the source buffer * @param target the target buffer * @param numSamples the number of samples to convert (target will have numSamples /2 filled after a call to this) */ - public static native void convertToMono( ShortBuffer source, ShortBuffer target, int numSamples ); + public static native void convertToMono (ShortBuffer source, ShortBuffer target, int numSamples); /** - * Converts the samples in source which are assumed to be interleaved left/right stereo samples - * to mono, writting the converted samples to target. Source is assumed to hold numSamples samples, - * target should hold numSamples / 2. Samples are read and written from position 0 up to numSamples. + * Converts the samples in source which are assumed to be interleaved left/right stereo samples to mono, writting the converted + * samples to target. Source is assumed to hold numSamples samples, target should hold numSamples / 2. Samples are read and + * written from position 0 up to numSamples. * * @param source the source buffer * @param target the target buffer * @param numSamples the number of samples to convert (target will have numSamples /2 filled after a call to this) */ - public static native void convertToMono( FloatBuffer source, FloatBuffer target, int numSamples ); - + public static native void convertToMono (FloatBuffer source, FloatBuffer target, int numSamples); + /** - * Calculates the spectral flux between the two given spectra. Both buffers are assumed to hold - * numSamples elements. Spectrum B is the current spectrum spectrum A the last spectrum + * Calculates the spectral flux between the two given spectra. Both buffers are assumed to hold numSamples elements. Spectrum B + * is the current spectrum spectrum A the last spectrum * * @param bufferA the first spectrum * @param bufferB the second spectrum * @param numSamples the number of elements - * @return the spectral flux + * @return the spectral flux */ - public static native float spectralFlux( FloatBuffer spectrumA, FloatBuffer spectrumB, int numSamples ); - + public static native float spectralFlux (FloatBuffer spectrumA, FloatBuffer spectrumB, int numSamples); + /** - * Allcoates a direct buffer for the given number of samples and channels. The final - * numer of samples is numSamples * numChannels. + * Allcoates a direct buffer for the given number of samples and channels. The final numer of samples is numSamples * + * numChannels. * * @param numSamples the number of samples * @param numChannels the number of channels * @return the direct buffer */ - public static FloatBuffer allocateFloatBuffer( int numSamples, int numChannels ) - { - ByteBuffer b = ByteBuffer.allocateDirect( numSamples * numChannels * 4 ); + public static FloatBuffer allocateFloatBuffer (int numSamples, int numChannels) { + ByteBuffer b = ByteBuffer.allocateDirect(numSamples * numChannels * 4); b.order(ByteOrder.nativeOrder()); return b.asFloatBuffer(); } - + /** - * Allcoates a direct buffer for the given number of samples and channels. The final - * numer of samples is numSamples * numChannels. + * Allcoates a direct buffer for the given number of samples and channels. The final numer of samples is numSamples * + * numChannels. * * @param numSamples the number of samples * @param numChannels the number of channels * @return the direct buffer */ - public static ShortBuffer allocateShortBuffer( int numSamples, int numChannels ) - { - ByteBuffer b = ByteBuffer.allocateDirect( numSamples * numChannels * 2 ); + public static ShortBuffer allocateShortBuffer (int numSamples, int numChannels) { + ByteBuffer b = ByteBuffer.allocateDirect(numSamples * numChannels * 2); b.order(ByteOrder.nativeOrder()); - return b.asShortBuffer(); + return b.asShortBuffer(); } - -// public static void main( String[] argv ) -// { -// Mpg123Decoder decoder = new Mpg123Decoder( "data/threeofaperfectpair.mp3"); -// System.out.println( "rate: " + decoder.getRate() + ", channels: " + decoder.getNumChannels() + ", length: " + decoder.getLength() ); -// JoglAudioDevice device = new JoglAudioDevice( true ); -// -// ShortBuffer stereoSamples = AudioTools.allocateShortBuffer( 1024, decoder.getNumChannels() ); -// ShortBuffer monoSamples = AudioTools.allocateShortBuffer( 1024, 1 ); -// FloatBuffer floatSamples = AudioTools.allocateFloatBuffer( 1024, 1 ); -// -// float[] samples = new float[1024]; -// -// while( decoder.readSamples( stereoSamples ) > 0 ) -// { -// AudioTools.convertToMono( stereoSamples, monoSamples, stereoSamples.capacity() ); -// AudioTools.convertToFloat( monoSamples, floatSamples, 1024 ); -// -// floatSamples.position(0); -// floatSamples.get(samples); -// device.writeSamples(samples, 0, monoSamples.capacity()); -// } -// decoder.dispose(); -// } + +// public static void main( String[] argv ) +// { +// Mpg123Decoder decoder = new Mpg123Decoder( "data/threeofaperfectpair.mp3"); +// System.out.println( "rate: " + decoder.getRate() + ", channels: " + decoder.getNumChannels() + ", length: " + +// decoder.getLength() ); +// JoglAudioDevice device = new JoglAudioDevice( true ); +// +// ShortBuffer stereoSamples = AudioTools.allocateShortBuffer( 1024, decoder.getNumChannels() ); +// ShortBuffer monoSamples = AudioTools.allocateShortBuffer( 1024, 1 ); +// FloatBuffer floatSamples = AudioTools.allocateFloatBuffer( 1024, 1 ); +// +// float[] samples = new float[1024]; +// +// while( decoder.readSamples( stereoSamples ) > 0 ) +// { +// AudioTools.convertToMono( stereoSamples, monoSamples, stereoSamples.capacity() ); +// AudioTools.convertToFloat( monoSamples, floatSamples, 1024 ); +// +// floatSamples.position(0); +// floatSamples.get(samples); +// device.writeSamples(samples, 0, monoSamples.capacity()); +// } +// decoder.dispose(); +// } } diff --git a/gdx/src/com/badlogic/gdx/audio/analysis/DFT.java b/gdx/src/com/badlogic/gdx/audio/analysis/DFT.java index d86aeb8a2..205a5eae5 100644 --- a/gdx/src/com/badlogic/gdx/audio/analysis/DFT.java +++ b/gdx/src/com/badlogic/gdx/audio/analysis/DFT.java @@ -1,32 +1,23 @@ /* - * Copyright (c) 2007 - 2008 by Damien Di Fede - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Library General Public License as published - * by the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * Copyright (c) 2007 - 2008 by Damien Di Fede + * + * This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License along with this program; if not, write to the Free + * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package com.badlogic.gdx.audio.analysis; - /** - * DFT stands for Discrete Fourier Transform and is the most widely used Fourier - * Transform. You will never want to use this class due to the fact that it is a - * brute force implementation of the DFT and as such is quite slow. Use an FFT - * instead. This exists primarily as a way to ensure that other implementations - * of the DFT are working properly. This implementation expects an even - * timeSize and will throw and IllegalArgumentException if this - * is not the case. + * DFT stands for Discrete Fourier Transform and is the most widely used Fourier Transform. You will never want to use this class + * due to the fact that it is a brute force implementation of the DFT and as such is quite slow. Use an FFT instead. This exists + * primarily as a way to ensure that other implementations of the DFT are working properly. This implementation expects an even + * timeSize and will throw and IllegalArgumentException if this is not the case. * * @author Damien Di Fede * @@ -35,112 +26,94 @@ package com.badlogic.gdx.audio.analysis; * @see The Discrete Fourier Transform * */ -public class DFT extends FourierTransform -{ - /** - * Constructs a DFT that expects audio buffers of length timeSize that - * have been recorded with a sample rate of sampleRate. Will throw an - * IllegalArgumentException if timeSize is not even. - * - * @param timeSize the length of the audio buffers you plan to analyze - * @param sampleRate the sample rate of the audio samples you plan to analyze - */ - public DFT(int timeSize, float sampleRate) - { - super(timeSize, sampleRate); - if (timeSize % 2 != 0) - throw new IllegalArgumentException("DFT: timeSize must be even."); - buildTrigTables(); - } +public class DFT extends FourierTransform { + /** + * Constructs a DFT that expects audio buffers of length timeSize that have been recorded with a sample rate of + * sampleRate. Will throw an IllegalArgumentException if timeSize is not even. + * + * @param timeSize the length of the audio buffers you plan to analyze + * @param sampleRate the sample rate of the audio samples you plan to analyze + */ + public DFT (int timeSize, float sampleRate) { + super(timeSize, sampleRate); + if (timeSize % 2 != 0) throw new IllegalArgumentException("DFT: timeSize must be even."); + buildTrigTables(); + } - protected void allocateArrays() - { - spectrum = new float[timeSize / 2 + 1]; - real = new float[timeSize / 2 + 1]; - imag = new float[timeSize / 2 + 1]; - } + protected void allocateArrays () { + spectrum = new float[timeSize / 2 + 1]; + real = new float[timeSize / 2 + 1]; + imag = new float[timeSize / 2 + 1]; + } - /** - * Not currently implemented. - */ - public void scaleBand(int i, float s) - { - } + /** + * Not currently implemented. + */ + public void scaleBand (int i, float s) { + } - /** - * Not currently implemented. - */ - public void setBand(int i, float a) - { - } + /** + * Not currently implemented. + */ + public void setBand (int i, float a) { + } - public void forward(float[] samples) - { - if (samples.length != timeSize) - { - throw new IllegalArgumentException("DFT.forward: The length of the passed sample buffer must be equal to DFT.timeSize()."); - } - doWindow(samples); - int N = samples.length; - for (int f = 0; f <= N / 2; f++) - { - real[f] = 0.0f; - imag[f] = 0.0f; - for (int t = 0; t < N; t++) - { - real[f] += samples[t] * cos(t * f); - imag[f] += samples[t] * -sin(t * f); - } - } - fillSpectrum(); - } + public void forward (float[] samples) { + if (samples.length != timeSize) { + throw new IllegalArgumentException( + "DFT.forward: The length of the passed sample buffer must be equal to DFT.timeSize()."); + } + doWindow(samples); + int N = samples.length; + for (int f = 0; f <= N / 2; f++) { + real[f] = 0.0f; + imag[f] = 0.0f; + for (int t = 0; t < N; t++) { + real[f] += samples[t] * cos(t * f); + imag[f] += samples[t] * -sin(t * f); + } + } + fillSpectrum(); + } - public void inverse(float[] buffer) - { - int N = buffer.length; - real[0] /= N; - imag[0] = -imag[0] / (N / 2); - real[N / 2] /= N; - imag[N / 2] = -imag[0] / (N / 2); - for (int i = 0; i < N / 2; i++) - { - real[i] /= (N / 2); - imag[i] = -imag[i] / (N / 2); - } - for (int t = 0; t < N; t++) - { - buffer[t] = 0.0f; - for (int f = 0; f < N / 2; f++) - { - buffer[t] += real[f] * cos(t * f) + imag[f] * sin(t * f); - } - } - } + public void inverse (float[] buffer) { + int N = buffer.length; + real[0] /= N; + imag[0] = -imag[0] / (N / 2); + real[N / 2] /= N; + imag[N / 2] = -imag[0] / (N / 2); + for (int i = 0; i < N / 2; i++) { + real[i] /= (N / 2); + imag[i] = -imag[i] / (N / 2); + } + for (int t = 0; t < N; t++) { + buffer[t] = 0.0f; + for (int f = 0; f < N / 2; f++) { + buffer[t] += real[f] * cos(t * f) + imag[f] * sin(t * f); + } + } + } - // lookup table data and functions + // lookup table data and functions - private float[] sinlookup; - private float[] coslookup; + private float[] sinlookup; + private float[] coslookup; - private void buildTrigTables() - { - int N = spectrum.length * timeSize; - sinlookup = new float[N]; - coslookup = new float[N]; - for (int i = 0; i < N; i++) - { - sinlookup[i] = (float) Math.sin(i * TWO_PI / timeSize); - coslookup[i] = (float) Math.cos(i * TWO_PI / timeSize); - } - } + private void buildTrigTables () { + int N = spectrum.length * timeSize; + sinlookup = new float[N]; + coslookup = new float[N]; + for (int i = 0; i < N; i++) { + sinlookup[i] = (float)Math.sin(i * TWO_PI / timeSize); + coslookup[i] = (float)Math.cos(i * TWO_PI / timeSize); + } + } - private float sin(int i) - { - return sinlookup[i]; - } + private float sin (int i) { + return sinlookup[i]; + } - private float cos(int i) - { - return coslookup[i]; - } + private float cos (int i) { + return coslookup[i]; + } } diff --git a/gdx/src/com/badlogic/gdx/audio/analysis/FFT.java b/gdx/src/com/badlogic/gdx/audio/analysis/FFT.java index 51febed77..75ce2caf3 100644 --- a/gdx/src/com/badlogic/gdx/audio/analysis/FFT.java +++ b/gdx/src/com/badlogic/gdx/audio/analysis/FFT.java @@ -1,32 +1,24 @@ /* - * Copyright (c) 2007 - 2008 by Damien Di Fede - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Library General Public License as published - * by the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * Copyright (c) 2007 - 2008 by Damien Di Fede + * + * This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License along with this program; if not, write to the Free + * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package com.badlogic.gdx.audio.analysis; - /** - * FFT stands for Fast Fourier Transform. It is an efficient way to calculate the Complex - * Discrete Fourier Transform. There is not much to say about this class other than the fact - * that when you want to analyze the spectrum of an audio buffer you will almost always use - * this class. One restriction of this class is that the audio buffers you want to analyze - * must have a length that is a power of two. If you try to construct an FFT with a - * timeSize that is not a power of two, an IllegalArgumentException will be - * thrown. + * FFT stands for Fast Fourier Transform. It is an efficient way to calculate the Complex Discrete Fourier Transform. There is not + * much to say about this class other than the fact that when you want to analyze the spectrum of an audio buffer you will almost + * always use this class. One restriction of this class is that the audio buffers you want to analyze must have a length that is a + * power of two. If you try to construct an FFT with a timeSize that is not a power of two, an + * IllegalArgumentException will be thrown. * * @see FourierTransform * @see The Fast Fourier Transform @@ -34,241 +26,201 @@ package com.badlogic.gdx.audio.analysis; * @author Damien Di Fede * */ -public class FFT extends FourierTransform -{ - /** - * Constructs an FFT that will accept sample buffers that are - * timeSize long and have been recorded with a sample rate of - * sampleRate. timeSize must be a - * power of two. This will throw an exception if it is not. - * - * @param timeSize - * the length of the sample buffers you will be analyzing - * @param sampleRate - * the sample rate of the audio you will be analyzing - */ - public FFT(int timeSize, float sampleRate) - { - super(timeSize, sampleRate); - if ((timeSize & (timeSize - 1)) != 0) - throw new IllegalArgumentException( - "FFT: timeSize must be a power of two."); - buildReverseTable(); - buildTrigTables(); - } - - protected void allocateArrays() - { - spectrum = new float[timeSize / 2 + 1]; - real = new float[timeSize]; - imag = new float[timeSize]; - } - - public void scaleBand(int i, float s) - { - if (s < 0) - { - throw new IllegalArgumentException("Can't scale a frequency band by a negative value."); - } - if (spectrum[i] != 0) - { - real[i] /= spectrum[i]; - imag[i] /= spectrum[i]; - spectrum[i] *= s; - real[i] *= spectrum[i]; - imag[i] *= spectrum[i]; - } - if (i != 0 && i != timeSize / 2) - { - real[timeSize - i] = real[i]; - imag[timeSize - i] = -imag[i]; - } - } - - public void setBand(int i, float a) - { - if (a < 0) - { - throw new IllegalArgumentException("Can't set a frequency band to a negative value."); - } - if (real[i] == 0 && imag[i] == 0) - { - real[i] = a; - spectrum[i] = a; - } - else - { - real[i] /= spectrum[i]; - imag[i] /= spectrum[i]; - spectrum[i] = a; - real[i] *= spectrum[i]; - imag[i] *= spectrum[i]; - } - if (i != 0 && i != timeSize / 2) - { - real[timeSize - i] = real[i]; - imag[timeSize - i] = -imag[i]; - } - } - - // performs an in-place fft on the data in the real and imag arrays - // bit reversing is not necessary as the data will already be bit reversed - private void fft() - { - for (int halfSize = 1; halfSize < real.length; halfSize *= 2) - { - // float k = -(float)Math.PI/halfSize; - // phase shift step - // float phaseShiftStepR = (float)Math.cos(k); - // float phaseShiftStepI = (float)Math.sin(k); - // using lookup table - float phaseShiftStepR = cos(halfSize); - float phaseShiftStepI = sin(halfSize); - // current phase shift - float currentPhaseShiftR = 1.0f; - float currentPhaseShiftI = 0.0f; - for (int fftStep = 0; fftStep < halfSize; fftStep++) - { - for (int i = fftStep; i < real.length; i += 2 * halfSize) - { - int off = i + halfSize; - float tr = (currentPhaseShiftR * real[off]) - (currentPhaseShiftI * imag[off]); - float ti = (currentPhaseShiftR * imag[off]) + (currentPhaseShiftI * real[off]); - real[off] = real[i] - tr; - imag[off] = imag[i] - ti; - real[i] += tr; - imag[i] += ti; - } - float tmpR = currentPhaseShiftR; - currentPhaseShiftR = (tmpR * phaseShiftStepR) - (currentPhaseShiftI * phaseShiftStepI); - currentPhaseShiftI = (tmpR * phaseShiftStepI) + (currentPhaseShiftI * phaseShiftStepR); - } - } - } - - public void forward(float[] buffer) - { - if (buffer.length != timeSize) - { - throw new IllegalArgumentException("FFT.forward: The length of the passed sample buffer must be equal to timeSize()."); - } - doWindow(buffer); - // copy samples to real/imag in bit-reversed order - bitReverseSamples(buffer); - // perform the fft - fft(); - // fill the spectrum buffer with amplitudes - fillSpectrum(); - } - - /** - * Performs a forward transform on the passed buffers. - * - * @param buffReal the real part of the time domain signal to transform - * @param buffImag the imaginary part of the time domain signal to transform - */ - public void forward(float[] buffReal, float[] buffImag) - { - if (buffReal.length != timeSize || buffImag.length != timeSize) - { - throw new IllegalArgumentException("FFT.forward: The length of the passed buffers must be equal to timeSize()."); - } - setComplex(buffReal, buffImag); - bitReverseComplex(); - fft(); - fillSpectrum(); - } - - public void inverse(float[] buffer) - { - if (buffer.length > real.length) - { - throw new IllegalArgumentException("FFT.inverse: the passed array's length must equal FFT.timeSize()."); - } - // conjugate - for (int i = 0; i < timeSize; i++) - { - imag[i] *= -1; - } - bitReverseComplex(); - fft(); - // copy the result in real into buffer, scaling as we do - for (int i = 0; i < buffer.length; i++) - { - buffer[i] = real[i] / real.length; - } - } - - private int[] reverse; - - private void buildReverseTable() - { - int N = timeSize; - reverse = new int[N]; - - // set up the bit reversing table - reverse[0] = 0; - for (int limit = 1, bit = N / 2; limit < N; limit <<= 1, bit >>= 1) - for (int i = 0; i < limit; i++) - reverse[i + limit] = reverse[i] + bit; - } - - // copies the values in the samples array into the real array - // in bit reversed order. the imag array is filled with zeros. - private void bitReverseSamples(float[] samples) - { - for (int i = 0; i < samples.length; i++) - { - real[i] = samples[reverse[i]]; - imag[i] = 0.0f; - } - } - - // bit reverse real[] and imag[] - private void bitReverseComplex() - { - float[] revReal = new float[real.length]; - float[] revImag = new float[imag.length]; - for (int i = 0; i < real.length; i++) - { - revReal[i] = real[reverse[i]]; - revImag[i] = imag[reverse[i]]; - } - real = revReal; - imag = revImag; - } - - // lookup tables - - private float[] sinlookup; - private float[] coslookup; - - private float sin(int i) - { - return sinlookup[i]; - } - - private float cos(int i) - { - return coslookup[i]; - } - - private void buildTrigTables() - { - int N = timeSize; - sinlookup = new float[N]; - coslookup = new float[N]; - for (int i = 0; i < N; i++) - { - sinlookup[i] = (float) Math.sin(-(float) Math.PI / i); - coslookup[i] = (float) Math.cos(-(float) Math.PI / i); - } - } - - public static void main( String[] argv ) - { - FFT fft = new FFT(1024, 44100); - System.out.println( fft.getRealPart().length); - System.out.println( fft.getSpectrum().length ); - } +public class FFT extends FourierTransform { + /** + * Constructs an FFT that will accept sample buffers that are timeSize long and have been recorded with a sample + * rate of sampleRate. timeSize must be a power of two. This will throw an exception if it + * is not. + * + * @param timeSize the length of the sample buffers you will be analyzing + * @param sampleRate the sample rate of the audio you will be analyzing + */ + public FFT (int timeSize, float sampleRate) { + super(timeSize, sampleRate); + if ((timeSize & (timeSize - 1)) != 0) throw new IllegalArgumentException("FFT: timeSize must be a power of two."); + buildReverseTable(); + buildTrigTables(); + } + + protected void allocateArrays () { + spectrum = new float[timeSize / 2 + 1]; + real = new float[timeSize]; + imag = new float[timeSize]; + } + + public void scaleBand (int i, float s) { + if (s < 0) { + throw new IllegalArgumentException("Can't scale a frequency band by a negative value."); + } + if (spectrum[i] != 0) { + real[i] /= spectrum[i]; + imag[i] /= spectrum[i]; + spectrum[i] *= s; + real[i] *= spectrum[i]; + imag[i] *= spectrum[i]; + } + if (i != 0 && i != timeSize / 2) { + real[timeSize - i] = real[i]; + imag[timeSize - i] = -imag[i]; + } + } + + public void setBand (int i, float a) { + if (a < 0) { + throw new IllegalArgumentException("Can't set a frequency band to a negative value."); + } + if (real[i] == 0 && imag[i] == 0) { + real[i] = a; + spectrum[i] = a; + } else { + real[i] /= spectrum[i]; + imag[i] /= spectrum[i]; + spectrum[i] = a; + real[i] *= spectrum[i]; + imag[i] *= spectrum[i]; + } + if (i != 0 && i != timeSize / 2) { + real[timeSize - i] = real[i]; + imag[timeSize - i] = -imag[i]; + } + } + + // performs an in-place fft on the data in the real and imag arrays + // bit reversing is not necessary as the data will already be bit reversed + private void fft () { + for (int halfSize = 1; halfSize < real.length; halfSize *= 2) { + // float k = -(float)Math.PI/halfSize; + // phase shift step + // float phaseShiftStepR = (float)Math.cos(k); + // float phaseShiftStepI = (float)Math.sin(k); + // using lookup table + float phaseShiftStepR = cos(halfSize); + float phaseShiftStepI = sin(halfSize); + // current phase shift + float currentPhaseShiftR = 1.0f; + float currentPhaseShiftI = 0.0f; + for (int fftStep = 0; fftStep < halfSize; fftStep++) { + for (int i = fftStep; i < real.length; i += 2 * halfSize) { + int off = i + halfSize; + float tr = (currentPhaseShiftR * real[off]) - (currentPhaseShiftI * imag[off]); + float ti = (currentPhaseShiftR * imag[off]) + (currentPhaseShiftI * real[off]); + real[off] = real[i] - tr; + imag[off] = imag[i] - ti; + real[i] += tr; + imag[i] += ti; + } + float tmpR = currentPhaseShiftR; + currentPhaseShiftR = (tmpR * phaseShiftStepR) - (currentPhaseShiftI * phaseShiftStepI); + currentPhaseShiftI = (tmpR * phaseShiftStepI) + (currentPhaseShiftI * phaseShiftStepR); + } + } + } + + public void forward (float[] buffer) { + if (buffer.length != timeSize) { + throw new IllegalArgumentException("FFT.forward: The length of the passed sample buffer must be equal to timeSize()."); + } + doWindow(buffer); + // copy samples to real/imag in bit-reversed order + bitReverseSamples(buffer); + // perform the fft + fft(); + // fill the spectrum buffer with amplitudes + fillSpectrum(); + } + + /** + * Performs a forward transform on the passed buffers. + * + * @param buffReal the real part of the time domain signal to transform + * @param buffImag the imaginary part of the time domain signal to transform + */ + public void forward (float[] buffReal, float[] buffImag) { + if (buffReal.length != timeSize || buffImag.length != timeSize) { + throw new IllegalArgumentException("FFT.forward: The length of the passed buffers must be equal to timeSize()."); + } + setComplex(buffReal, buffImag); + bitReverseComplex(); + fft(); + fillSpectrum(); + } + + public void inverse (float[] buffer) { + if (buffer.length > real.length) { + throw new IllegalArgumentException("FFT.inverse: the passed array's length must equal FFT.timeSize()."); + } + // conjugate + for (int i = 0; i < timeSize; i++) { + imag[i] *= -1; + } + bitReverseComplex(); + fft(); + // copy the result in real into buffer, scaling as we do + for (int i = 0; i < buffer.length; i++) { + buffer[i] = real[i] / real.length; + } + } + + private int[] reverse; + + private void buildReverseTable () { + int N = timeSize; + reverse = new int[N]; + + // set up the bit reversing table + reverse[0] = 0; + for (int limit = 1, bit = N / 2; limit < N; limit <<= 1, bit >>= 1) + for (int i = 0; i < limit; i++) + reverse[i + limit] = reverse[i] + bit; + } + + // copies the values in the samples array into the real array + // in bit reversed order. the imag array is filled with zeros. + private void bitReverseSamples (float[] samples) { + for (int i = 0; i < samples.length; i++) { + real[i] = samples[reverse[i]]; + imag[i] = 0.0f; + } + } + + // bit reverse real[] and imag[] + private void bitReverseComplex () { + float[] revReal = new float[real.length]; + float[] revImag = new float[imag.length]; + for (int i = 0; i < real.length; i++) { + revReal[i] = real[reverse[i]]; + revImag[i] = imag[reverse[i]]; + } + real = revReal; + imag = revImag; + } + + // lookup tables + + private float[] sinlookup; + private float[] coslookup; + + private float sin (int i) { + return sinlookup[i]; + } + + private float cos (int i) { + return coslookup[i]; + } + + private void buildTrigTables () { + int N = timeSize; + sinlookup = new float[N]; + coslookup = new float[N]; + for (int i = 0; i < N; i++) { + sinlookup[i] = (float)Math.sin(-(float)Math.PI / i); + coslookup[i] = (float)Math.cos(-(float)Math.PI / i); + } + } + + public static void main (String[] argv) { + FFT fft = new FFT(1024, 44100); + System.out.println(fft.getRealPart().length); + System.out.println(fft.getSpectrum().length); + } } diff --git a/gdx/src/com/badlogic/gdx/audio/analysis/FourierTransform.java b/gdx/src/com/badlogic/gdx/audio/analysis/FourierTransform.java index 8e1b7ccb5..af993972d 100644 --- a/gdx/src/com/badlogic/gdx/audio/analysis/FourierTransform.java +++ b/gdx/src/com/badlogic/gdx/audio/analysis/FourierTransform.java @@ -1,683 +1,542 @@ /* - * Copyright (c) 2007 - 2008 by Damien Di Fede - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Library General Public License as published - * by the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * Copyright (c) 2007 - 2008 by Damien Di Fede + * + * This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License along with this program; if not, write to the Free + * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package com.badlogic.gdx.audio.analysis; - /** - * A Fourier Transform is an algorithm that transforms a signal in the time - * domain, such as a sample buffer, into a signal in the frequency domain, often - * called the spectrum. The spectrum does not represent individual frequencies, - * but actually represents frequency bands centered on particular frequencies. - * The center frequency of each band is usually expressed as a fraction of the - * sampling rate of the time domain signal and is equal to the index of the - * frequency band divided by the total number of bands. The total number of - * frequency bands is usually equal to the length of the time domain signal, but - * access is only provided to frequency bands with indices less than half the - * length, because they correspond to frequencies below the Nyquist frequency. - * In other words, given a signal of length N, there will be - * N/2 frequency bands in the spectrum. + * A Fourier Transform is an algorithm that transforms a signal in the time domain, such as a sample buffer, into a signal in the + * frequency domain, often called the spectrum. The spectrum does not represent individual frequencies, but actually represents + * frequency bands centered on particular frequencies. The center frequency of each band is usually expressed as a fraction of the + * sampling rate of the time domain signal and is equal to the index of the frequency band divided by the total number of bands. + * The total number of frequency bands is usually equal to the length of the time domain signal, but access is only provided to + * frequency bands with indices less than half the length, because they correspond to frequencies below the Nyquist frequency. In other words, given a signal of length + * N, there will be N/2 frequency bands in the spectrum. *

- * As an example, if you construct a FourierTransform with a - * timeSize of 1024 and and a sampleRate of 44100 - * Hz, then the spectrum will contain values for frequencies below 22010 Hz, - * which is the Nyquist frequency (half the sample rate). If you ask for the - * value of band number 5, this will correspond to a frequency band centered on - * 5/1024 * 44100 = 0.0048828125 * 44100 = 215 Hz. The width of - * that frequency band is equal to 2/1024, expressed as a - * fraction of the total bandwidth of the spectrum. The total bandwith of the - * spectrum is equal to the Nyquist frequency, which in this case is 22100, so - * the bandwidth is equal to about 50 Hz. It is not necessary for you to - * remember all of these relationships, though it is good to be aware of them. - * The function getFreq() allows you to query the spectrum with a - * frequency in Hz and the function getBandWidth() will return - * the bandwidth in Hz of each frequency band in the spectrum. + * As an example, if you construct a FourierTransform with a timeSize of 1024 and and a sampleRate of + * 44100 Hz, then the spectrum will contain values for frequencies below 22010 Hz, which is the Nyquist frequency (half the sample + * rate). If you ask for the value of band number 5, this will correspond to a frequency band centered on + * 5/1024 * 44100 = 0.0048828125 * 44100 = 215 Hz. The width of that frequency band is equal to 2/1024, + * expressed as a fraction of the total bandwidth of the spectrum. The total bandwith of the spectrum is equal to the Nyquist + * frequency, which in this case is 22100, so the bandwidth is equal to about 50 Hz. It is not necessary for you to remember all + * of these relationships, though it is good to be aware of them. The function getFreq() allows you to query the + * spectrum with a frequency in Hz and the function getBandWidth() will return the bandwidth in Hz of each frequency + * band in the spectrum. *

* Usage *

- * A typical usage of a FourierTransform is to analyze a signal so that the - * frequency spectrum may be represented in some way, typically with vertical - * lines. You could do this in Processing with the following code, where - * audio is an AudioSource and fft is an FFT (one - * of the derived classes of FourierTransform). + * A typical usage of a FourierTransform is to analyze a signal so that the frequency spectrum may be represented in some way, + * typically with vertical lines. You could do this in Processing with the following code, where audio is an + * AudioSource and fft is an FFT (one of the derived classes of FourierTransform). * *

  * fft.forward(audio.left);
- * for (int i = 0; i < fft.specSize(); i++)
- * {
- *   // draw the line for frequency band i, scaling it by 4 so we can see it a bit better
- *   line(i, height, i, height - fft.getBand(i) * 4);
+ * for (int i = 0; i < fft.specSize(); i++) {
+ * 	// draw the line for frequency band i, scaling it by 4 so we can see it a bit better
+ * 	line(i, height, i, height - fft.getBand(i) * 4);
  * }
  * 
* * Windowing *

- * Windowing is the process of shaping the audio samples before transforming them - * to the frequency domain. If you call the window() function - * with an appropriate constant, such as FourierTransform.HAMMING, the sample - * buffers passed to the object for analysis will be shaped by the current - * window before being transformed. The result of using a window is to reduce + * Windowing is the process of shaping the audio samples before transforming them to the frequency domain. If you call the + * window() function with an appropriate constant, such as FourierTransform.HAMMING, the sample buffers passed to the + * object for analysis will be shaped by the current window before being transformed. The result of using a window is to reduce * the noise in the spectrum somewhat. *

* Averages *

- * FourierTransform also has functions that allow you to request the creation of - * an average spectrum. An average spectrum is simply a spectrum with fewer - * bands than the full spectrum where each average band is the average of the - * amplitudes of some number of contiguous frequency bands in the full spectrum. + * FourierTransform also has functions that allow you to request the creation of an average spectrum. An average spectrum is + * simply a spectrum with fewer bands than the full spectrum where each average band is the average of the amplitudes of some + * number of contiguous frequency bands in the full spectrum. *

- * linAverages() allows you to specify the number of averages - * that you want and will group frequency bands into groups of equal number. So - * if you have a spectrum with 512 frequency bands and you ask for 64 averages, - * each average will span 8 bands of the full spectrum. + * linAverages() allows you to specify the number of averages that you want and will group frequency bands into + * groups of equal number. So if you have a spectrum with 512 frequency bands and you ask for 64 averages, each average will span + * 8 bands of the full spectrum. *

- * logAverages() will group frequency bands by octave and allows - * you to specify the size of the smallest octave to use (in Hz) and also how - * many bands to split each octave into. So you might ask for the smallest - * octave to be 60 Hz and to split each octave into two bands. The result is - * that the bandwidth of each average is different. One frequency is an octave - * above another when it's frequency is twice that of the lower frequency. So, - * 120 Hz is an octave above 60 Hz, 240 Hz is an octave above 120 Hz, and so on. - * When octaves are split, they are split based on Hz, so if you split the - * octave 60-120 Hz in half, you will get 60-90Hz and 90-120Hz. You can see how - * these bandwidths increase as your octave sizes grow. For instance, the last - * octave will always span sampleRate/4 - sampleRate/2, which in - * the case of audio sampled at 44100 Hz is 11025-22010 Hz. These - * logarithmically spaced averages are usually much more useful than the full - * spectrum or the linearly spaced averages because they map more directly to - * how humans perceive sound. + * logAverages() will group frequency bands by octave and allows you to specify the size of the smallest octave to + * use (in Hz) and also how many bands to split each octave into. So you might ask for the smallest octave to be 60 Hz and to + * split each octave into two bands. The result is that the bandwidth of each average is different. One frequency is an octave + * above another when it's frequency is twice that of the lower frequency. So, 120 Hz is an octave above 60 Hz, 240 Hz is an + * octave above 120 Hz, and so on. When octaves are split, they are split based on Hz, so if you split the octave 60-120 Hz in + * half, you will get 60-90Hz and 90-120Hz. You can see how these bandwidths increase as your octave sizes grow. For instance, the + * last octave will always span sampleRate/4 - sampleRate/2, which in the case of audio sampled at 44100 Hz is + * 11025-22010 Hz. These logarithmically spaced averages are usually much more useful than the full spectrum or the linearly + * spaced averages because they map more directly to how humans perceive sound. *

- * calcAvg() allows you to specify the frequency band you want an - * average calculated for. You might ask for 60-500Hz and this function will - * group together the bands from the full spectrum that fall into that range and - * average their amplitudes for you. + * calcAvg() allows you to specify the frequency band you want an average calculated for. You might ask for 60-500Hz + * and this function will group together the bands from the full spectrum that fall into that range and average their amplitudes + * for you. *

- * If you don't want any averages calculated, then you can call - * noAverages(). This will not impact your ability to use - * calcAvg(), it will merely prevent the object from calculating - * an average array every time you use forward(). + * If you don't want any averages calculated, then you can call noAverages(). This will not impact your ability to + * use calcAvg(), it will merely prevent the object from calculating an average array every time you use + * forward(). *

* Inverse Transform *

- * FourierTransform also supports taking the inverse transform of a spectrum. - * This means that a frequency spectrum will be transformed into a time domain - * signal and placed in a provided sample buffer. The length of the time domain - * signal will be timeSize() long. The set and - * scale functions allow you the ability to shape the spectrum - * already stored in the object before taking the inverse transform. You might - * use these to filter frequencies in a spectrum or modify it in some other way. + * FourierTransform also supports taking the inverse transform of a spectrum. This means that a frequency spectrum will be + * transformed into a time domain signal and placed in a provided sample buffer. The length of the time domain signal will be + * timeSize() long. The set and scale functions allow you the ability to shape the spectrum + * already stored in the object before taking the inverse transform. You might use these to filter frequencies in a spectrum or + * modify it in some other way. * * @author Damien Di Fede * @see The Discrete Fourier Transform */ -public abstract class FourierTransform -{ - /** A constant indicating no window should be used on sample buffers. */ - public static final int NONE = 0; - /** A constant indicating a Hamming window should be used on sample buffers. */ - public static final int HAMMING = 1; - protected static final int LINAVG = 2; - protected static final int LOGAVG = 3; - protected static final int NOAVG = 4; - protected static final float TWO_PI = (float) (2 * Math.PI); - protected int timeSize; - protected int sampleRate; - protected float bandWidth; - protected int whichWindow; - protected float[] real; - protected float[] imag; - protected float[] spectrum; - protected float[] averages; - protected int whichAverage; - protected int octaves; - protected int avgPerOctave; - - /** - * Construct a FourierTransform that will analyze sample buffers that are - * ts samples long and contain samples with a sr - * sample rate. - * - * @param ts - * the length of the buffers that will be analyzed - * @param sr - * the sample rate of the samples that will be analyzed - */ - FourierTransform(int ts, float sr) - { - timeSize = ts; - sampleRate = (int)sr; - bandWidth = (2f / timeSize) * ((float)sampleRate / 2f); - noAverages(); - allocateArrays(); - whichWindow = NONE; - } - - // allocating real, imag, and spectrum are the responsibility of derived - // classes - // because the size of the arrays will depend on the implementation being used - // this enforces that responsibility - protected abstract void allocateArrays(); - - protected void setComplex(float[] r, float[] i) - { - if (real.length != r.length && imag.length != i.length) - { - throw new IllegalArgumentException( "This won't work" ); - } - else - { - System.arraycopy(r, 0, real, 0, r.length); - System.arraycopy(i, 0, imag, 0, i.length); - } - } - - // fill the spectrum array with the amps of the data in real and imag - // used so that this class can handle creating the average array - // and also do spectrum shaping if necessary - protected void fillSpectrum() - { - for (int i = 0; i < spectrum.length; i++) - { - spectrum[i] = (float) Math.sqrt(real[i] * real[i] + imag[i] * imag[i]); - } - - if (whichAverage == LINAVG) - { - int avgWidth = (int) spectrum.length / averages.length; - for (int i = 0; i < averages.length; i++) - { - float avg = 0; - int j; - for (j = 0; j < avgWidth; j++) - { - int offset = j + i * avgWidth; - if (offset < spectrum.length) - { - avg += spectrum[offset]; - } - else - { - break; - } - } - avg /= j + 1; - averages[i] = avg; - } - } - else if (whichAverage == LOGAVG) - { - for (int i = 0; i < octaves; i++) - { - float lowFreq, hiFreq, freqStep; - if (i == 0) - { - lowFreq = 0; - } - else - { - lowFreq = (sampleRate / 2) / (float) Math.pow(2, octaves - i); - } - hiFreq = (sampleRate / 2) / (float) Math.pow(2, octaves - i - 1); - freqStep = (hiFreq - lowFreq) / avgPerOctave; - float f = lowFreq; - for (int j = 0; j < avgPerOctave; j++) - { - int offset = j + i * avgPerOctave; - averages[offset] = calcAvg(f, f + freqStep); - f += freqStep; - } - } - } - } - - /** - * Sets the object to not compute averages. - * - */ - public void noAverages() - { - averages = new float[0]; - whichAverage = NOAVG; - } - - /** - * Sets the number of averages used when computing the spectrum and spaces the - * averages in a linear manner. In other words, each average band will be - * specSize() / numAvg bands wide. - * - * @param numAvg - * how many averages to compute - */ - public void linAverages(int numAvg) - { - if (numAvg > spectrum.length / 2) - { - throw new IllegalArgumentException("The number of averages for this transform can be at most " + spectrum.length / 2 + "."); - } - else - { - averages = new float[numAvg]; - } - whichAverage = LINAVG; - } - - /** - * Sets the number of averages used when computing the spectrum based on the - * minimum bandwidth for an octave and the number of bands per octave. For - * example, with audio that has a sample rate of 44100 Hz, - * logAverages(11, 1) will result in 12 averages, each - * corresponding to an octave, the first spanning 0 to 11 Hz. To ensure that - * each octave band is a full octave, the number of octaves is computed by - * dividing the Nyquist frequency by two, and then the result of that by two, - * and so on. This means that the actual bandwidth of the lowest octave may - * not be exactly the value specified. - * - * @param minBandwidth - * the minimum bandwidth used for an octave - * @param bandsPerOctave - * how many bands to split each octave into - */ - public void logAverages(int minBandwidth, int bandsPerOctave) - { - float nyq = (float) sampleRate / 2f; - octaves = 1; - while ((nyq /= 2) > minBandwidth) - { - octaves++; - } - avgPerOctave = bandsPerOctave; - averages = new float[octaves * bandsPerOctave]; - whichAverage = LOGAVG; - } - - /** - * Sets the window to use on the samples before taking the forward transform. - * If an invalid window is asked for, an error will be reported and the - * current window will not be changed. - * - * @param which - * FourierTransform.HAMMING or FourierTransform.NONE - */ - public void window(int which) - { - if (which < 0 || which > 1) - { - throw new IllegalArgumentException("Invalid window type."); - } - else - { - whichWindow = which; - } - } - - protected void doWindow(float[] samples) - { - switch (whichWindow) - { - case HAMMING: - hamming(samples); - break; - } - } - - // windows the data in samples with a Hamming window - protected void hamming(float[] samples) - { - for (int i = 0; i < samples.length; i++) - { - samples[i] *= (0.54f - 0.46f * Math.cos(TWO_PI * i / (samples.length - 1))); - } - } - - /** - * Returns the length of the time domain signal expected by this transform. - * - * @return the length of the time domain signal expected by this transform - */ - public int timeSize() - { - return timeSize; - } - - /** - * Returns the size of the spectrum created by this transform. In other words, - * the number of frequency bands produced by this transform. This is typically - * equal to timeSize()/2 + 1, see above for an explanation. - * - * @return the size of the spectrum - */ - public int specSize() - { - return spectrum.length; - } - - /** - * Returns the amplitude of the requested frequency band. - * - * @param i - * the index of a frequency band - * @return the amplitude of the requested frequency band - */ - public float getBand(int i) - { - if (i < 0) i = 0; - if (i > spectrum.length - 1) i = spectrum.length - 1; - return spectrum[i]; - } - - /** - * Returns the width of each frequency band in the spectrum (in Hz). It should - * be noted that the bandwidth of the first and last frequency bands is half - * as large as the value returned by this function. - * - * @return the width of each frequency band in Hz. - */ - public float getBandWidth() - { - return bandWidth; - } - - /** - * Sets the amplitude of the ith frequency band to - * a. You can use this to shape the spectrum before using - * inverse(). - * - * @param i - * the frequency band to modify - * @param a - * the new amplitude - */ - public abstract void setBand(int i, float a); - - /** - * Scales the amplitude of the ith frequency band - * by s. You can use this to shape the spectrum before using - * inverse(). - * - * @param i - * the frequency band to modify - * @param s - * the scaling factor - */ - public abstract void scaleBand(int i, float s); - - /** - * Returns the index of the frequency band that contains the requested - * frequency. - * - * @param freq - * the frequency you want the index for (in Hz) - * @return the index of the frequency band that contains freq - */ - public int freqToIndex(float freq) - { - // special case: freq is lower than the bandwidth of spectrum[0] - if (freq < getBandWidth() / 2) return 0; - // special case: freq is within the bandwidth of spectrum[spectrum.length - 1] - if (freq > sampleRate / 2 - getBandWidth() / 2) return spectrum.length - 1; - // all other cases - float fraction = freq / (float) sampleRate; - int i = Math.round(timeSize * fraction); - return i; - } - - /** - * Returns the middle frequency of the ith band. - * @param i - * the index of the band you want to middle frequency of - */ - public float indexToFreq(int i) - { - float bw = getBandWidth(); - // special case: the width of the first bin is half that of the others. - // so the center frequency is a quarter of the way. - if ( i == 0 ) return bw * 0.25f; - // special case: the width of the last bin is half that of the others. - if ( i == spectrum.length - 1 ) - { - float lastBinBeginFreq = (sampleRate / 2) - (bw / 2); - float binHalfWidth = bw * 0.25f; - return lastBinBeginFreq + binHalfWidth; - } - // the center frequency of the ith band is simply i*bw - // because the first band is half the width of all others. - // treating it as if it wasn't offsets us to the middle - // of the band. - return i*bw; - } - - /** - * Returns the center frequency of the ith average band. - * - * @param i - * which average band you want the center frequency of. - */ - public float getAverageCenterFrequency(int i) - { - if ( whichAverage == LINAVG ) - { - // an average represents a certain number of bands in the spectrum - int avgWidth = (int) spectrum.length / averages.length; - // the "center" bin of the average, this is fudgy. - int centerBinIndex = i*avgWidth + avgWidth/2; - return indexToFreq(centerBinIndex); - - } - else if ( whichAverage == LOGAVG ) - { - // which "octave" is this index in? - int octave = i / avgPerOctave; - // which band within that octave is this? - int offset = i % avgPerOctave; - float lowFreq, hiFreq, freqStep; - // figure out the low frequency for this octave - if (octave == 0) - { - lowFreq = 0; - } - else - { - lowFreq = (sampleRate / 2) / (float) Math.pow(2, octaves - octave); - } - // and the high frequency for this octave - hiFreq = (sampleRate / 2) / (float) Math.pow(2, octaves - octave - 1); - // each average band within the octave will be this big - freqStep = (hiFreq - lowFreq) / avgPerOctave; - // figure out the low frequency of the band we care about - float f = lowFreq + offset*freqStep; - // the center of the band will be the low plus half the width - return f + freqStep/2; - } - - return 0; - } - - - /** - * Gets the amplitude of the requested frequency in the spectrum. - * - * @param freq - * the frequency in Hz - * @return the amplitude of the frequency in the spectrum - */ - public float getFreq(float freq) - { - return getBand(freqToIndex(freq)); - } - - /** - * Sets the amplitude of the requested frequency in the spectrum to - * a. - * - * @param freq - * the frequency in Hz - * @param a - * the new amplitude - */ - public void setFreq(float freq, float a) - { - setBand(freqToIndex(freq), a); - } - - /** - * Scales the amplitude of the requested frequency by a. - * - * @param freq - * the frequency in Hz - * @param s - * the scaling factor - */ - public void scaleFreq(float freq, float s) - { - scaleBand(freqToIndex(freq), s); - } - - /** - * Returns the number of averages currently being calculated. - * - * @return the length of the averages array - */ - public int avgSize() - { - return averages.length; - } - - /** - * Gets the value of the ith average. - * - * @param i - * the average you want the value of - * @return the value of the requested average band - */ - public float getAvg(int i) - { - float ret; - if (averages.length > 0) - ret = averages[i]; - else - ret = 0; - return ret; - } - - /** - * Calculate the average amplitude of the frequency band bounded by - * lowFreq and hiFreq, inclusive. - * - * @param lowFreq - * the lower bound of the band - * @param hiFreq - * the upper bound of the band - * @return the average of all spectrum values within the bounds - */ - public float calcAvg(float lowFreq, float hiFreq) - { - int lowBound = freqToIndex(lowFreq); - int hiBound = freqToIndex(hiFreq); - float avg = 0; - for (int i = lowBound; i <= hiBound; i++) - { - avg += spectrum[i]; - } - avg /= (hiBound - lowBound + 1); - return avg; - } - - /** - * Performs a forward transform on buffer. - * - * @param buffer - * the buffer to analyze - */ - public abstract void forward(float[] buffer); - - /** - * Performs a forward transform on values in buffer. - * - * @param buffer - * the buffer of samples - * @param startAt - * the index to start at in the buffer. there must be at least timeSize() samples - * between the starting index and the end of the buffer. If there aren't, an - * error will be issued and the operation will not be performed. - * - */ - public void forward(float[] buffer, int startAt) - { - if ( buffer.length - startAt < timeSize ) - { - throw new IllegalArgumentException( "FourierTransform.forward: not enough samples in the buffer between " + startAt + " and " + buffer.length + " to perform a transform." ); - } - - // copy the section of samples we want to analyze - float[] section = new float[timeSize]; - System.arraycopy(buffer, startAt, section, 0, section.length); - forward(section); - } - - - /** - * Performs an inverse transform of the frequency spectrum and places the - * result in buffer. - * - * @param buffer - * the buffer to place the result of the inverse transform in - */ - public abstract void inverse(float[] buffer); - - /** - * Performs an inverse transform of the frequency spectrum represented by - * freqReal and freqImag and places the result in buffer. - * - * @param freqReal - * the real part of the frequency spectrum - * @param freqImag - * the imaginary part the frequency spectrum - * @param buffer - * the buffer to place the inverse transform in - */ - public void inverse(float[] freqReal, float[] freqImag, float[] buffer) - { - setComplex(freqReal, freqImag); - inverse(buffer); - } - - /** - * @return the spectrum of the last FourierTransform.forward() call. - */ - public float[] getSpectrum( ) - { - return spectrum; - } - - /** - * @return the real part of the last FourierTransform.forward() call. - */ - public float[] getRealPart( ) - { - return real; - } - - /** - * @return the imaginary part of the last FourierTransform.forward() call. - */ - public float[] getImaginaryPart( ) - { - return imag; - } +public abstract class FourierTransform { + /** A constant indicating no window should be used on sample buffers. */ + public static final int NONE = 0; + /** A constant indicating a Hamming window should be used on sample buffers. */ + public static final int HAMMING = 1; + protected static final int LINAVG = 2; + protected static final int LOGAVG = 3; + protected static final int NOAVG = 4; + protected static final float TWO_PI = (float)(2 * Math.PI); + protected int timeSize; + protected int sampleRate; + protected float bandWidth; + protected int whichWindow; + protected float[] real; + protected float[] imag; + protected float[] spectrum; + protected float[] averages; + protected int whichAverage; + protected int octaves; + protected int avgPerOctave; + + /** + * Construct a FourierTransform that will analyze sample buffers that are ts samples long and contain samples with + * a sr sample rate. + * + * @param ts the length of the buffers that will be analyzed + * @param sr the sample rate of the samples that will be analyzed + */ + FourierTransform (int ts, float sr) { + timeSize = ts; + sampleRate = (int)sr; + bandWidth = (2f / timeSize) * ((float)sampleRate / 2f); + noAverages(); + allocateArrays(); + whichWindow = NONE; + } + + // allocating real, imag, and spectrum are the responsibility of derived + // classes + // because the size of the arrays will depend on the implementation being used + // this enforces that responsibility + protected abstract void allocateArrays (); + + protected void setComplex (float[] r, float[] i) { + if (real.length != r.length && imag.length != i.length) { + throw new IllegalArgumentException("This won't work"); + } else { + System.arraycopy(r, 0, real, 0, r.length); + System.arraycopy(i, 0, imag, 0, i.length); + } + } + + // fill the spectrum array with the amps of the data in real and imag + // used so that this class can handle creating the average array + // and also do spectrum shaping if necessary + protected void fillSpectrum () { + for (int i = 0; i < spectrum.length; i++) { + spectrum[i] = (float)Math.sqrt(real[i] * real[i] + imag[i] * imag[i]); + } + + if (whichAverage == LINAVG) { + int avgWidth = (int)spectrum.length / averages.length; + for (int i = 0; i < averages.length; i++) { + float avg = 0; + int j; + for (j = 0; j < avgWidth; j++) { + int offset = j + i * avgWidth; + if (offset < spectrum.length) { + avg += spectrum[offset]; + } else { + break; + } + } + avg /= j + 1; + averages[i] = avg; + } + } else if (whichAverage == LOGAVG) { + for (int i = 0; i < octaves; i++) { + float lowFreq, hiFreq, freqStep; + if (i == 0) { + lowFreq = 0; + } else { + lowFreq = (sampleRate / 2) / (float)Math.pow(2, octaves - i); + } + hiFreq = (sampleRate / 2) / (float)Math.pow(2, octaves - i - 1); + freqStep = (hiFreq - lowFreq) / avgPerOctave; + float f = lowFreq; + for (int j = 0; j < avgPerOctave; j++) { + int offset = j + i * avgPerOctave; + averages[offset] = calcAvg(f, f + freqStep); + f += freqStep; + } + } + } + } + + /** + * Sets the object to not compute averages. + * + */ + public void noAverages () { + averages = new float[0]; + whichAverage = NOAVG; + } + + /** + * Sets the number of averages used when computing the spectrum and spaces the averages in a linear manner. In other words, + * each average band will be specSize() / numAvg bands wide. + * + * @param numAvg how many averages to compute + */ + public void linAverages (int numAvg) { + if (numAvg > spectrum.length / 2) { + throw new IllegalArgumentException("The number of averages for this transform can be at most " + spectrum.length / 2 + + "."); + } else { + averages = new float[numAvg]; + } + whichAverage = LINAVG; + } + + /** + * Sets the number of averages used when computing the spectrum based on the minimum bandwidth for an octave and the number of + * bands per octave. For example, with audio that has a sample rate of 44100 Hz, logAverages(11, 1) will result in + * 12 averages, each corresponding to an octave, the first spanning 0 to 11 Hz. To ensure that each octave band is a full + * octave, the number of octaves is computed by dividing the Nyquist frequency by two, and then the result of that by two, and + * so on. This means that the actual bandwidth of the lowest octave may not be exactly the value specified. + * + * @param minBandwidth the minimum bandwidth used for an octave + * @param bandsPerOctave how many bands to split each octave into + */ + public void logAverages (int minBandwidth, int bandsPerOctave) { + float nyq = (float)sampleRate / 2f; + octaves = 1; + while ((nyq /= 2) > minBandwidth) { + octaves++; + } + avgPerOctave = bandsPerOctave; + averages = new float[octaves * bandsPerOctave]; + whichAverage = LOGAVG; + } + + /** + * Sets the window to use on the samples before taking the forward transform. If an invalid window is asked for, an error will + * be reported and the current window will not be changed. + * + * @param which FourierTransform.HAMMING or FourierTransform.NONE + */ + public void window (int which) { + if (which < 0 || which > 1) { + throw new IllegalArgumentException("Invalid window type."); + } else { + whichWindow = which; + } + } + + protected void doWindow (float[] samples) { + switch (whichWindow) { + case HAMMING: + hamming(samples); + break; + } + } + + // windows the data in samples with a Hamming window + protected void hamming (float[] samples) { + for (int i = 0; i < samples.length; i++) { + samples[i] *= (0.54f - 0.46f * Math.cos(TWO_PI * i / (samples.length - 1))); + } + } + + /** + * Returns the length of the time domain signal expected by this transform. + * + * @return the length of the time domain signal expected by this transform + */ + public int timeSize () { + return timeSize; + } + + /** + * Returns the size of the spectrum created by this transform. In other words, the number of frequency bands produced by this + * transform. This is typically equal to timeSize()/2 + 1, see above for an explanation. + * + * @return the size of the spectrum + */ + public int specSize () { + return spectrum.length; + } + + /** + * Returns the amplitude of the requested frequency band. + * + * @param i the index of a frequency band + * @return the amplitude of the requested frequency band + */ + public float getBand (int i) { + if (i < 0) i = 0; + if (i > spectrum.length - 1) i = spectrum.length - 1; + return spectrum[i]; + } + + /** + * Returns the width of each frequency band in the spectrum (in Hz). It should be noted that the bandwidth of the first and + * last frequency bands is half as large as the value returned by this function. + * + * @return the width of each frequency band in Hz. + */ + public float getBandWidth () { + return bandWidth; + } + + /** + * Sets the amplitude of the ith frequency band to a. You can use this to shape the + * spectrum before using inverse(). + * + * @param i the frequency band to modify + * @param a the new amplitude + */ + public abstract void setBand (int i, float a); + + /** + * Scales the amplitude of the ith frequency band by s. You can use this to shape the + * spectrum before using inverse(). + * + * @param i the frequency band to modify + * @param s the scaling factor + */ + public abstract void scaleBand (int i, float s); + + /** + * Returns the index of the frequency band that contains the requested frequency. + * + * @param freq the frequency you want the index for (in Hz) + * @return the index of the frequency band that contains freq + */ + public int freqToIndex (float freq) { + // special case: freq is lower than the bandwidth of spectrum[0] + if (freq < getBandWidth() / 2) return 0; + // special case: freq is within the bandwidth of spectrum[spectrum.length - 1] + if (freq > sampleRate / 2 - getBandWidth() / 2) return spectrum.length - 1; + // all other cases + float fraction = freq / (float)sampleRate; + int i = Math.round(timeSize * fraction); + return i; + } + + /** + * Returns the middle frequency of the ith band. + * @param i the index of the band you want to middle frequency of + */ + public float indexToFreq (int i) { + float bw = getBandWidth(); + // special case: the width of the first bin is half that of the others. + // so the center frequency is a quarter of the way. + if (i == 0) return bw * 0.25f; + // special case: the width of the last bin is half that of the others. + if (i == spectrum.length - 1) { + float lastBinBeginFreq = (sampleRate / 2) - (bw / 2); + float binHalfWidth = bw * 0.25f; + return lastBinBeginFreq + binHalfWidth; + } + // the center frequency of the ith band is simply i*bw + // because the first band is half the width of all others. + // treating it as if it wasn't offsets us to the middle + // of the band. + return i * bw; + } + + /** + * Returns the center frequency of the ith average band. + * + * @param i which average band you want the center frequency of. + */ + public float getAverageCenterFrequency (int i) { + if (whichAverage == LINAVG) { + // an average represents a certain number of bands in the spectrum + int avgWidth = (int)spectrum.length / averages.length; + // the "center" bin of the average, this is fudgy. + int centerBinIndex = i * avgWidth + avgWidth / 2; + return indexToFreq(centerBinIndex); + + } else if (whichAverage == LOGAVG) { + // which "octave" is this index in? + int octave = i / avgPerOctave; + // which band within that octave is this? + int offset = i % avgPerOctave; + float lowFreq, hiFreq, freqStep; + // figure out the low frequency for this octave + if (octave == 0) { + lowFreq = 0; + } else { + lowFreq = (sampleRate / 2) / (float)Math.pow(2, octaves - octave); + } + // and the high frequency for this octave + hiFreq = (sampleRate / 2) / (float)Math.pow(2, octaves - octave - 1); + // each average band within the octave will be this big + freqStep = (hiFreq - lowFreq) / avgPerOctave; + // figure out the low frequency of the band we care about + float f = lowFreq + offset * freqStep; + // the center of the band will be the low plus half the width + return f + freqStep / 2; + } + + return 0; + } + + /** + * Gets the amplitude of the requested frequency in the spectrum. + * + * @param freq the frequency in Hz + * @return the amplitude of the frequency in the spectrum + */ + public float getFreq (float freq) { + return getBand(freqToIndex(freq)); + } + + /** + * Sets the amplitude of the requested frequency in the spectrum to a. + * + * @param freq the frequency in Hz + * @param a the new amplitude + */ + public void setFreq (float freq, float a) { + setBand(freqToIndex(freq), a); + } + + /** + * Scales the amplitude of the requested frequency by a. + * + * @param freq the frequency in Hz + * @param s the scaling factor + */ + public void scaleFreq (float freq, float s) { + scaleBand(freqToIndex(freq), s); + } + + /** + * Returns the number of averages currently being calculated. + * + * @return the length of the averages array + */ + public int avgSize () { + return averages.length; + } + + /** + * Gets the value of the ith average. + * + * @param i the average you want the value of + * @return the value of the requested average band + */ + public float getAvg (int i) { + float ret; + if (averages.length > 0) + ret = averages[i]; + else + ret = 0; + return ret; + } + + /** + * Calculate the average amplitude of the frequency band bounded by lowFreq and hiFreq, inclusive. + * + * @param lowFreq the lower bound of the band + * @param hiFreq the upper bound of the band + * @return the average of all spectrum values within the bounds + */ + public float calcAvg (float lowFreq, float hiFreq) { + int lowBound = freqToIndex(lowFreq); + int hiBound = freqToIndex(hiFreq); + float avg = 0; + for (int i = lowBound; i <= hiBound; i++) { + avg += spectrum[i]; + } + avg /= (hiBound - lowBound + 1); + return avg; + } + + /** + * Performs a forward transform on buffer. + * + * @param buffer the buffer to analyze + */ + public abstract void forward (float[] buffer); + + /** + * Performs a forward transform on values in buffer. + * + * @param buffer the buffer of samples + * @param startAt the index to start at in the buffer. there must be at least timeSize() samples between the starting index and + * the end of the buffer. If there aren't, an error will be issued and the operation will not be performed. + * + */ + public void forward (float[] buffer, int startAt) { + if (buffer.length - startAt < timeSize) { + throw new IllegalArgumentException("FourierTransform.forward: not enough samples in the buffer between " + startAt + + " and " + buffer.length + " to perform a transform."); + } + + // copy the section of samples we want to analyze + float[] section = new float[timeSize]; + System.arraycopy(buffer, startAt, section, 0, section.length); + forward(section); + } + + /** + * Performs an inverse transform of the frequency spectrum and places the result in buffer. + * + * @param buffer the buffer to place the result of the inverse transform in + */ + public abstract void inverse (float[] buffer); + + /** + * Performs an inverse transform of the frequency spectrum represented by freqReal and freqImag and places the result in + * buffer. + * + * @param freqReal the real part of the frequency spectrum + * @param freqImag the imaginary part the frequency spectrum + * @param buffer the buffer to place the inverse transform in + */ + public void inverse (float[] freqReal, float[] freqImag, float[] buffer) { + setComplex(freqReal, freqImag); + inverse(buffer); + } + + /** + * @return the spectrum of the last FourierTransform.forward() call. + */ + public float[] getSpectrum () { + return spectrum; + } + + /** + * @return the real part of the last FourierTransform.forward() call. + */ + public float[] getRealPart () { + return real; + } + + /** + * @return the imaginary part of the last FourierTransform.forward() call. + */ + public float[] getImaginaryPart () { + return imag; + } } diff --git a/gdx/src/com/badlogic/gdx/audio/analysis/KissFFT.java b/gdx/src/com/badlogic/gdx/audio/analysis/KissFFT.java index 221ef006b..45763541f 100644 --- a/gdx/src/com/badlogic/gdx/audio/analysis/KissFFT.java +++ b/gdx/src/com/badlogic/gdx/audio/analysis/KissFFT.java @@ -1,37 +1,32 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.audio.analysis; import java.nio.FloatBuffer; import java.nio.ShortBuffer; -public class KissFFT -{ +public class KissFFT { /** the pointer to the kiss fft object **/ private final long handle; /** - * Creates a new fft instance that can analyse numSamples samples. - * timeSize must be a power of two. + * Creates a new fft instance that can analyse numSamples samples. timeSize must be a power of two. * * @param numSamples the number of samples to be analysed. */ - public KissFFT( int numSamples ) - { - handle = create( numSamples ); + public KissFFT (int numSamples) { + handle = create(numSamples); } /** @@ -39,85 +34,77 @@ public class KissFFT * @param timeSize the number of samples * @return the handle to the kiss fft object */ - private native long create( int timeSize ); + private native long create (int timeSize); /** * Destroys a kiss fft object * @param handle the handle to the kiss fft object */ - private native void destroy( long handle ); + private native void destroy (long handle); /** - * Calculates the frequency spectrum of the given samples. There must be - * as many samples as specified in the constructor of this class. Spectrum - * must hold timeSize / 2 + 1 elements + * Calculates the frequency spectrum of the given samples. There must be as many samples as specified in the constructor of + * this class. Spectrum must hold timeSize / 2 + 1 elements * * @param handle the handle to the kiss fft object * @param samples the samples in 16-bit signed PCM encoding * @param spectrum the spectrum */ - private native void spectrum( long handle, ShortBuffer samples, FloatBuffer spectrum ); + private native void spectrum (long handle, ShortBuffer samples, FloatBuffer spectrum); /** - * Calculates the frequency spectrum of the given samples. There must be - * as many samples as specified in the constructor of this class. Spectrum - * must hold timeSize / 2 + 1 elements + * Calculates the frequency spectrum of the given samples. There must be as many samples as specified in the constructor of + * this class. Spectrum must hold timeSize / 2 + 1 elements * * @param samples the samples * @param spectrum the spectrum */ - public void spectrum( ShortBuffer samples, FloatBuffer spectrum ) - { - spectrum( handle, samples, spectrum ); + public void spectrum (ShortBuffer samples, FloatBuffer spectrum) { + spectrum(handle, samples, spectrum); } /** * Releases all resources of this object */ - public void dispose( ) - { + public void dispose () { destroy(handle); } - - public void getRealPart( ShortBuffer real ) - { + + public void getRealPart (ShortBuffer real) { getRealPart(handle, real); } - - public void getImagPart( ShortBuffer imag ) - { - getImagPart( handle, imag ); + + public void getImagPart (ShortBuffer imag) { + getImagPart(handle, imag); } - - private native void getRealPart( long handle, ShortBuffer real ); - - private native void getImagPart( long handle, ShortBuffer imag ); - - public static void main( String[] argv ) - { + + private native void getRealPart (long handle, ShortBuffer real); + + private native void getImagPart (long handle, ShortBuffer imag); + + public static void main (String[] argv) { final float frequency = 440; - float increment = (float)(2*Math.PI) * frequency / 44100; // angular increment for each sample - float angle = 0; + float increment = (float)(2 * Math.PI) * frequency / 44100; // angular increment for each sample + float angle = 0; short samples[] = new short[1024]; - for( int i = 0; i < samples.length; i++ ) - { - float value = (float)Math.sin( angle ); + for (int i = 0; i < samples.length; i++) { + float value = (float)Math.sin(angle); samples[i] = (short)(value * 32767); angle += increment; } - - ShortBuffer samplesBuffer = AudioTools.allocateShortBuffer( 1024, 1 ); - ShortBuffer realBuffer = AudioTools.allocateShortBuffer(512,1 ); - ShortBuffer imagBuffer = AudioTools.allocateShortBuffer(512,1 ); - samplesBuffer.put( samples ); - FloatBuffer spectrum = AudioTools.allocateFloatBuffer( 513, 1 ); - KissFFT fft = new KissFFT( 1024 ); - - fft.spectrum( samplesBuffer, spectrum ); - - fft.getRealPart( realBuffer ); - fft.getImagPart( imagBuffer ); + + ShortBuffer samplesBuffer = AudioTools.allocateShortBuffer(1024, 1); + ShortBuffer realBuffer = AudioTools.allocateShortBuffer(512, 1); + ShortBuffer imagBuffer = AudioTools.allocateShortBuffer(512, 1); + samplesBuffer.put(samples); + FloatBuffer spectrum = AudioTools.allocateFloatBuffer(513, 1); + KissFFT fft = new KissFFT(1024); + + fft.spectrum(samplesBuffer, spectrum); + + fft.getRealPart(realBuffer); + fft.getImagPart(imagBuffer); short[] re = new short[512]; short[] im = new short[512]; float[] sp = new float[513]; @@ -127,10 +114,9 @@ public class KissFFT imagBuffer.get(im); spectrum.position(0); spectrum.get(sp); - - for( int i = 0; i < 30; i++ ) - { - System.out.println( sp[i] ); + + for (int i = 0; i < 30; i++) { + System.out.println(sp[i]); } } } diff --git a/gdx/src/com/badlogic/gdx/audio/analysis/NativeFFT.java b/gdx/src/com/badlogic/gdx/audio/analysis/NativeFFT.java index 5d444f0e8..12257ccfd 100644 --- a/gdx/src/com/badlogic/gdx/audio/analysis/NativeFFT.java +++ b/gdx/src/com/badlogic/gdx/audio/analysis/NativeFFT.java @@ -1,53 +1,45 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.audio.analysis; import java.nio.FloatBuffer; /** - * A native implementation of the Fast Fourier Transform, directly - * ported from the {@link FFT} class. + * A native implementation of the Fast Fourier Transform, directly ported from the {@link FFT} class. * * @author mzechner - * + * */ -public class NativeFFT -{ +public class NativeFFT { /** the handle to the native fft instance **/ private long handle; - - - public NativeFFT( int timeSize, int sampleRate ) - { - handle = createFFT( timeSize, sampleRate ); + + public NativeFFT (int timeSize, int sampleRate) { + handle = createFFT(timeSize, sampleRate); } - - private native long createFFT( int timeSize, int sampleRate ); - - private native void destroyFFT( long handle ); - - private native void nativeSpectrum( long handle, FloatBuffer samples, FloatBuffer spectrum, int numSamples ); - - public void spectrum( FloatBuffer samples, FloatBuffer spectrum, int numSamples ) - { - nativeSpectrum( handle, samples, spectrum, numSamples ); + + private native long createFFT (int timeSize, int sampleRate); + + private native void destroyFFT (long handle); + + private native void nativeSpectrum (long handle, FloatBuffer samples, FloatBuffer spectrum, int numSamples); + + public void spectrum (FloatBuffer samples, FloatBuffer spectrum, int numSamples) { + nativeSpectrum(handle, samples, spectrum, numSamples); + } + + public void dispose () { + destroyFFT(handle); } - - public void dispose( ) - { - destroyFFT( handle ); - } } diff --git a/gdx/src/com/badlogic/gdx/audio/analysis/ThresholdFunction.java b/gdx/src/com/badlogic/gdx/audio/analysis/ThresholdFunction.java index db3cfc719..0d4234a4e 100644 --- a/gdx/src/com/badlogic/gdx/audio/analysis/ThresholdFunction.java +++ b/gdx/src/com/badlogic/gdx/audio/analysis/ThresholdFunction.java @@ -1,74 +1,65 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.audio.analysis; import java.util.ArrayList; import java.util.List; /** - * Calculates a threshold function based on the spectral flux. + * Calculates a threshold function based on the spectral flux. * * @author badlogicgames@gmail.com - * + * */ -public class ThresholdFunction -{ +public class ThresholdFunction { /** the history size **/ private final int historySize; - + /** the average multiplier **/ private final float multiplier; - + /** - * Consturctor, sets the history size in number of spectra - * to take into account to calculate the average spectral flux - * at a specific position. Also sets the multiplier to - * multiply the average with. + * Consturctor, sets the history size in number of spectra to take into account to calculate the average spectral flux at a + * specific position. Also sets the multiplier to multiply the average with. * * @param historySize The history size. * @param multiplier The average multiplier. */ - public ThresholdFunction( int historySize, float multiplier ) - { + public ThresholdFunction (int historySize, float multiplier) { this.historySize = historySize; this.multiplier = multiplier; } - + /** - * Returns the threshold function for a given - * spectral flux function. + * Returns the threshold function for a given spectral flux function. * * @return The threshold function. */ - public List calculate( List spectralFlux ) - { - ArrayList thresholds = new ArrayList( spectralFlux.size() ); - - for( int i = 0; i < spectralFlux.size(); i++ ) - { + public List calculate (List spectralFlux) { + ArrayList thresholds = new ArrayList(spectralFlux.size()); + + for (int i = 0; i < spectralFlux.size(); i++) { float sum = 0; - int start = Math.max( 0, i - historySize / 2); - int end = Math.min( spectralFlux.size()-1, i + historySize / 2 ); - for( int j = start; j <= end; j++ ) + int start = Math.max(0, i - historySize / 2); + int end = Math.min(spectralFlux.size() - 1, i + historySize / 2); + for (int j = start; j <= end; j++) sum += spectralFlux.get(j); - sum /= (end-start); + sum /= (end - start); sum *= multiplier; - thresholds.add( sum ); + thresholds.add(sum); } - + return thresholds; } } diff --git a/gdx/src/com/badlogic/gdx/audio/io/Decoder.java b/gdx/src/com/badlogic/gdx/audio/io/Decoder.java index d1b0704f7..d6cdfc60c 100644 --- a/gdx/src/com/badlogic/gdx/audio/io/Decoder.java +++ b/gdx/src/com/badlogic/gdx/audio/io/Decoder.java @@ -1,67 +1,60 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.audio.io; import java.nio.ShortBuffer; /** - * Interface for audio decoders that return successive - * amplitude frames. When a decoder is no longer used - * it has to be disposed. + * Interface for audio decoders that return successive amplitude frames. When a decoder is no longer used it has to be disposed. * * @author badlogicgames@gmail.com - * + * */ -public interface Decoder -{ +public interface Decoder { /** - * Reads in samples.capacity() samples in 16-bit signed PCM format from the decoder. Returns - * the actual number read in. If this number is smaller than - * the capacity of the buffer then the end of stream has been reached. + * Reads in samples.capacity() samples in 16-bit signed PCM format from the decoder. Returns the actual number read in. If this + * number is smaller than the capacity of the buffer then the end of stream has been reached. * * @param samples The number of read samples. */ - public int readSamples( ShortBuffer samples ); - + public int readSamples (ShortBuffer samples); + /** - * Skips numSamples samples. If the decoded file is in stereo the left and right channel samples - * are counted as 2 samples. + * Skips numSamples samples. If the decoded file is in stereo the left and right channel samples are counted as 2 samples. * * @param numSamples the number of samples to skip * @return the number of samples actually skipped. If this is < numSamples then the end of the file has been reached. */ - public int skipSamples( int numSamples ); - - /** + public int skipSamples (int numSamples); + + /** * @return the number of channels */ - public int getNumChannels( ); - + public int getNumChannels (); + /** * @return the sampling rate in herz, e.g. 44100 */ - public int getRate( ); + public int getRate (); /** * @return the length of the file in seconds */ - public float getLength( ); - + public float getLength (); + /** * Disposes the decoder and frees all associated resources */ - public void dispose( ); + public void dispose (); } diff --git a/gdx/src/com/badlogic/gdx/audio/io/Mpg123Decoder.java b/gdx/src/com/badlogic/gdx/audio/io/Mpg123Decoder.java index af4e3c8a4..13ce1743c 100644 --- a/gdx/src/com/badlogic/gdx/audio/io/Mpg123Decoder.java +++ b/gdx/src/com/badlogic/gdx/audio/io/Mpg123Decoder.java @@ -1,129 +1,113 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.audio.io; import java.nio.ShortBuffer; /** - * A {@link Decoder} implementation that decodes MP3 files via - * libmpg123 natively. + * A {@link Decoder} implementation that decodes MP3 files via libmpg123 natively. * * @author mzechner - * + * */ -public class Mpg123Decoder implements Decoder -{ +public class Mpg123Decoder implements Decoder { public final long handle; - + /** - * Opens the given file for mp3 decoding. Throws an IllegalArugmentException - * in case the file could not be opened. + * Opens the given file for mp3 decoding. Throws an IllegalArugmentException in case the file could not be opened. * * @param filename the filename */ - public Mpg123Decoder( String filename ) - { - handle = openFile( filename ); - - if( handle == -1 ) - throw new IllegalArgumentException( "couldn't open file" ); + public Mpg123Decoder (String filename) { + handle = openFile(filename); + + if (handle == -1) throw new IllegalArgumentException("couldn't open file"); } - /** * {@inheritDoc} */ - @Override - public int readSamples(ShortBuffer samples) - { - int read = readSamples( handle, samples, samples.capacity() ); + @Override public int readSamples (ShortBuffer samples) { + int read = readSamples(handle, samples, samples.capacity()); samples.position(0); return read; } - + /** * {@inheritDoc} */ - @Override - public int skipSamples(int numSamples) - { - return skipSamples( handle, numSamples ); + @Override public int skipSamples (int numSamples) { + return skipSamples(handle, numSamples); } - + /** * {@inheritDoc} */ - public int getNumChannels( ) - { - return getNumChannels( handle ); + public int getNumChannels () { + return getNumChannels(handle); } - + /** * {@inheritDoc} */ - public int getRate( ) - { - return getRate( handle ); + public int getRate () { + return getRate(handle); } - + /** * {@inheritDoc} */ - public float getLength( ) - { - return getLength( handle ); + public float getLength () { + return getLength(handle); } - - private native long openFile( String filename ); - - private native int readSamples( long handle, ShortBuffer buffer, int numSamples ); - - private native int skipSamples( long handle, int numSamples ); - - private native int getNumChannels( long handle ); - - private native int getRate( long handle ); - - private native float getLength( long handle ); - - private native void closeFile( long handle ); + + private native long openFile (String filename); + + private native int readSamples (long handle, ShortBuffer buffer, int numSamples); + + private native int skipSamples (long handle, int numSamples); + + private native int getNumChannels (long handle); + + private native int getRate (long handle); + + private native float getLength (long handle); + + private native void closeFile (long handle); /** * {@inheritDoc} */ - @Override - public void dispose() - { - closeFile( handle ); + @Override public void dispose () { + closeFile(handle); } - -// public static void main( String[] argv ) -// { -// Mpg123Decoder decoder = new Mpg123Decoder( "data/threeofaperfectpair.mp3"); -// JoglAudioDevice device = new JoglAudioDevice( false ); -// ShortBuffer buffer = AudioTools.allocateShortBuffer( 1024, decoder.getNumChannels() ); -// short[] samples = new short[1024*decoder.getNumChannels()]; -// -// System.out.println( "rate: " + decoder.getRate() + ", channels: " + decoder.getNumChannels() + ", length: " + decoder.getLength() ); -// -// while( decoder.readSamples( buffer ) > 0 ) -// { -// buffer.get(samples); -// device.writeSamples(samples, 0, 1024*2); -// } -// decoder.dispose(); -// } + +// public static void main( String[] argv ) +// { +// Mpg123Decoder decoder = new Mpg123Decoder( "data/threeofaperfectpair.mp3"); +// JoglAudioDevice device = new JoglAudioDevice( false ); +// ShortBuffer buffer = AudioTools.allocateShortBuffer( 1024, decoder.getNumChannels() ); +// short[] samples = new short[1024*decoder.getNumChannels()]; +// +// System.out.println( "rate: " + decoder.getRate() + ", channels: " + decoder.getNumChannels() + ", length: " + +// decoder.getLength() ); +// +// while( decoder.readSamples( buffer ) > 0 ) +// { +// buffer.get(samples); +// device.writeSamples(samples, 0, 1024*2); +// } +// decoder.dispose(); +// } } diff --git a/gdx/src/com/badlogic/gdx/audio/io/VorbisDecoder.java b/gdx/src/com/badlogic/gdx/audio/io/VorbisDecoder.java index 445d8b345..e520e3a5b 100644 --- a/gdx/src/com/badlogic/gdx/audio/io/VorbisDecoder.java +++ b/gdx/src/com/badlogic/gdx/audio/io/VorbisDecoder.java @@ -1,89 +1,72 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.audio.io; import java.nio.ShortBuffer; /** - * A {@link Decoder} implementation that decodes OGG Vorbis files using - * libvorbis and libogg + * A {@link Decoder} implementation that decodes OGG Vorbis files using libvorbis and libogg * @author mzechner - * + * */ -public class VorbisDecoder implements Decoder -{ +public class VorbisDecoder implements Decoder { /** the handle **/ private final long handle; - + /** - * Opens the given file for ogg decoding. Throws an IllegalArugmentException - * in case the file could not be opened. + * Opens the given file for ogg decoding. Throws an IllegalArugmentException in case the file could not be opened. * * @param filename the filename */ - public VorbisDecoder( String filename ) - { - handle = openFile( filename ); - if( handle == 0 ) - throw new IllegalArgumentException( "couldn't open file '" + filename + "'" ); + public VorbisDecoder (String filename) { + handle = openFile(filename); + if (handle == 0) throw new IllegalArgumentException("couldn't open file '" + filename + "'"); } - + /** * {@inheritDoc} */ - @Override - public void dispose() - { - closeFile( handle ); + @Override public void dispose () { + closeFile(handle); } /** * {@inheritDoc} */ - @Override - public float getLength() - { + @Override public float getLength () { return getLength(handle); } /** * {@inheritDoc} */ - @Override - public int getNumChannels() - { + @Override public int getNumChannels () { return getNumChannels(handle); } /** * {@inheritDoc} */ - @Override - public int getRate() - { + @Override public int getRate () { return getRate(handle); } /** * {@inheritDoc} */ - @Override - public int readSamples(ShortBuffer samples) - { - int read = readSamples( handle, samples, samples.capacity() ); + @Override public int readSamples (ShortBuffer samples) { + int read = readSamples(handle, samples, samples.capacity()); samples.position(0); return read; } @@ -91,42 +74,41 @@ public class VorbisDecoder implements Decoder /** * {@inheritDoc} */ - @Override - public int skipSamples(int numSamples) - { - return skipSamples( handle, numSamples ); + @Override public int skipSamples (int numSamples) { + return skipSamples(handle, numSamples); } - - private native long openFile( String file ); - - private native int getNumChannels( long handle ); - - private native int getRate( long handle ); - - private native float getLength( long handle ); - - private native int readSamples( long handle, ShortBuffer buffer, int numSamples ); - - private native int skipSamples( long handle, int numSamples ); - - private native void closeFile( long handle ); - -// public static void main( String[] argv ) -// { -// VorbisDecoder decoder = new VorbisDecoder( "data/cloudconnected.ogg" ); -// System.out.println( "channels: "+ decoder.getNumChannels() + ", rate: " + decoder.getRate() + ", length: " + decoder.getLength() );; -// -// JoglAudioDevice device = new JoglAudioDevice( decoder.getNumChannels() == 2?false:true ); -// ShortBuffer samplesBuffer = AudioTools.allocateShortBuffer( 1024*10, 2 ); -// short[] samples = new short[samplesBuffer.capacity()]; -// -// while( decoder.readSamples( samplesBuffer ) > 0 ) -// { -// samplesBuffer.get(samples); -// device.writeSamples( samples, 0, samples.length ); -// } -// -// decoder.dispose(); -// device.dispose(); -// } + + private native long openFile (String file); + + private native int getNumChannels (long handle); + + private native int getRate (long handle); + + private native float getLength (long handle); + + private native int readSamples (long handle, ShortBuffer buffer, int numSamples); + + private native int skipSamples (long handle, int numSamples); + + private native void closeFile (long handle); + +// public static void main( String[] argv ) +// { +// VorbisDecoder decoder = new VorbisDecoder( "data/cloudconnected.ogg" ); +// System.out.println( "channels: "+ decoder.getNumChannels() + ", rate: " + decoder.getRate() + ", length: " + +// decoder.getLength() );; +// +// JoglAudioDevice device = new JoglAudioDevice( decoder.getNumChannels() == 2?false:true ); +// ShortBuffer samplesBuffer = AudioTools.allocateShortBuffer( 1024*10, 2 ); +// short[] samples = new short[samplesBuffer.capacity()]; +// +// while( decoder.readSamples( samplesBuffer ) > 0 ) +// { +// samplesBuffer.get(samples); +// device.writeSamples( samples, 0, samples.length ); +// } +// +// decoder.dispose(); +// device.dispose(); +// } } diff --git a/gdx/src/com/badlogic/gdx/files/FileHandle.java b/gdx/src/com/badlogic/gdx/files/FileHandle.java index 5c6beb1dd..58c572a4e 100644 --- a/gdx/src/com/badlogic/gdx/files/FileHandle.java +++ b/gdx/src/com/badlogic/gdx/files/FileHandle.java @@ -1,31 +1,29 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.files; import java.io.InputStream; +import com.badlogic.gdx.Files; + /** - * A file handle represents a system dependant representation of an - * internal or external file. FileHandles can only be created via + * A file handle represents a system dependant representation of an internal or external file. FileHandles can only be created via * a {@link Files} instance. * * @author mzechner - * + * */ -public interface FileHandle -{ +public interface FileHandle { public InputStream getInputStream (); } diff --git a/gdx/src/com/badlogic/gdx/graphics/BitmapFont.java b/gdx/src/com/badlogic/gdx/graphics/BitmapFont.java index cd2d3f96d..680364520 100644 --- a/gdx/src/com/badlogic/gdx/graphics/BitmapFont.java +++ b/gdx/src/com/badlogic/gdx/graphics/BitmapFont.java @@ -13,25 +13,35 @@ import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; /** - *

A BitmapFont is used to load and render AngleCode bitmap font files. The AngleCode - * bitmap font consists of 2 files, the .fnt file which must be saved with text encoding - * (not xml or binary!) and the bitmap file holding the glyphs, usually in .png format.

+ *

+ * A BitmapFont is used to load and render AngleCode bitmap font files. The AngleCode bitmap font consists of 2 files, the .fnt + * file which must be saved with text encoding (not xml or binary!) and the bitmap file holding the glyphs, usually in .png + * format. + *

* - *

This implementation currently only supports a single glyph page.

+ *

+ * This implementation currently only supports a single glyph page. + *

* - *

To draw text with this class you need to call one of the draw() methods together with - * a {@link SpriteBatch}. The SpriteBatch must be in rendering mode, that is, {@link SpriteBatch#begin()} - * must have been called before drawing

+ *

+ * To draw text with this class you need to call one of the draw() methods together with a {@link SpriteBatch}. The SpriteBatch + * must be in rendering mode, that is, {@link SpriteBatch#begin()} must have been called before drawing + *

* - *

Additionally you can cache text in a {@link BitmapFontCache} for faster rendering of static text

+ *

+ * Additionally you can cache text in a {@link BitmapFontCache} for faster rendering of static text + *

* - *

A BitmapFont is managed. You need to call the {@link #dispose()} method when you no longer need it

+ *

+ * A BitmapFont is managed. You need to call the {@link #dispose()} method when you no longer need it + *

* - *

The code is heavily based on Matthias Mann's TWL BitmapFont class. Thanks for sharing - * Matthias :)

+ *

+ * The code is heavily based on Matthias Mann's TWL BitmapFont class. Thanks for sharing Matthias :) + *

* * @author nathan.sweet - * + * */ public class BitmapFont { private static final int LOG2_PAGE_SIZE = 9; @@ -46,9 +56,8 @@ public class BitmapFont { private int ex; private int capHeight; - /** - * Creates a new BitmapFont instance based on a .fnt file and - * an image file holding the page with glyphs. Currently only + /** + * Creates a new BitmapFont instance based on a .fnt file and an image file holding the page with glyphs. Currently only * supports single page AngleCode fonts. * * @param fontFile The font file @@ -146,8 +155,8 @@ public class BitmapFont { } /** - * Draws the given string at the given position with the given color. You - * can only call this between {@link SpriteBatch#begin()}/{@link SpriteBatch#end()}. + * Draws the given string at the given position with the given color. You can only call this between + * {@link SpriteBatch#begin()}/{@link SpriteBatch#end()}. * * @param spriteBatch The {@link SpriteBatch} to use * @param str The string @@ -161,8 +170,8 @@ public class BitmapFont { } /** - * Draws the given string at the given position with the given color. You - * can only call this between {@link SpriteBatch#begin()}/{@link SpriteBatch#end()}. + * Draws the given string at the given position with the given color. You can only call this between + * {@link SpriteBatch#begin()}/{@link SpriteBatch#end()}. * * @param spriteBatch The {@link SpriteBatch} to use * @param str The string @@ -201,9 +210,9 @@ public class BitmapFont { } /** - * Draws the given string at the given position with the given color. The position coincides - * with the top left corner of the first line's glyph. The method interprets new lines. - * You can only call this between {@link SpriteBatch#begin()}/{@link SpriteBatch#end()}. + * Draws the given string at the given position with the given color. The position coincides with the top left corner of the + * first line's glyph. The method interprets new lines. You can only call this between {@link SpriteBatch#begin()}/ + * {@link SpriteBatch#end()}. * * @param spriteBatch The {@link SpriteBatch} to use * @param str The string @@ -217,12 +226,15 @@ public class BitmapFont { } /** - *

Draws the given string at the given position with the given color. The position coincides - * with the top left corner of the first line's glyph. The method interprets new lines. - * You can only call this between {@link SpriteBatch#begin()}/{@link SpriteBatch#end()}.

- *

You can specify the horizontal alignment of the text with the alignmentWidth and alignment - * parameters. The first parameter specifies the width of the rectangle the text should be aligned in (x to x + alignmentWidth). - * The second parameter specifies the alignment itself. + *

+ * Draws the given string at the given position with the given color. The position coincides with the top left corner of the + * first line's glyph. The method interprets new lines. You can only call this between {@link SpriteBatch#begin()}/ + * {@link SpriteBatch#end()}. + *

+ *

+ * You can specify the horizontal alignment of the text with the alignmentWidth and alignment + * parameters. The first parameter specifies the width of the rectangle the text should be aligned in (x to x + + * alignmentWidth). The second parameter specifies the alignment itself. * * @param spriteBatch The {@link SpriteBatch} to use * @param str The string @@ -281,11 +293,10 @@ public class BitmapFont { * Creates a new {@link BitmapFontCache} to be used with {@link #cacheText()}. * @return The cache */ - public BitmapFontCache newCache( ) - { - return new BitmapFontCache( this.texture ); + public BitmapFontCache newCache () { + return new BitmapFontCache(this.texture); } - + /** * Caches the given string at the given position with the given color in the provided {@link BitmapFontCache}. * @@ -319,8 +330,8 @@ public class BitmapFont { } /** - * Caches the given string at the given position with the given color in the provided {@link BitmapFontCache}. - * The position coincides with the top left corner of the first line's glyph. The method interprets new lines. + * Caches the given string at the given position with the given color in the provided {@link BitmapFontCache}. The position + * coincides with the top left corner of the first line's glyph. The method interprets new lines. * * @param spriteBatch The {@link SpriteBatch} to use * @param str The string @@ -333,11 +344,14 @@ public class BitmapFont { } /** - *

Caches the given string at the given position with the given color in the provided {@link BitmapFontCache}. The position coincides - * with the top left corner of the first line's glyph. The method interprets new lines.

- *

You can specify the horizontal alignment of the text with the alignmentWidth and alignment - * parameters. The first parameter specifies the width of the rectangle the text should be aligned in (x to x + alignmentWidth). - * The second parameter specifies the alignment itself. + *

+ * Caches the given string at the given position with the given color in the provided {@link BitmapFontCache}. The position + * coincides with the top left corner of the first line's glyph. The method interprets new lines. + *

+ *

+ * You can specify the horizontal alignment of the text with the alignmentWidth and alignment + * parameters. The first parameter specifies the width of the rectangle the text should be aligned in (x to x + + * alignmentWidth). The second parameter specifies the alignment itself. * * @param cache The cache * @param str The string @@ -372,8 +386,8 @@ public class BitmapFont { } /** - * Computes the strings width - * @param str The string + * Computes the strings width + * @param str The string * @return the width */ public int computeTextWidth (CharSequence str) { @@ -382,7 +396,7 @@ public class BitmapFont { /** * Computes the string with - * @param str the string + * @param str the string * @param start the first character index * @param end the last character index (exclusive) * @return the string width @@ -492,7 +506,7 @@ public class BitmapFont { } /** - * Frees all resources of this font. + * Frees all resources of this font. */ public void dispose () { texture.dispose(); diff --git a/gdx/src/com/badlogic/gdx/graphics/BitmapFontCache.java b/gdx/src/com/badlogic/gdx/graphics/BitmapFontCache.java index 55637afe6..d7932cf2e 100644 --- a/gdx/src/com/badlogic/gdx/graphics/BitmapFontCache.java +++ b/gdx/src/com/badlogic/gdx/graphics/BitmapFontCache.java @@ -2,15 +2,17 @@ package com.badlogic.gdx.graphics; /** - *

A BitmapFontCache caches glyph geometry produced by a call to one of the - * {@link BitmapFontCache#cacheText()} methods. It provides a fast way to - * render static text.

+ *

+ * A BitmapFontCache caches glyph geometry produced by a call to one of the {@link BitmapFontCache#cacheText()} methods. It + * provides a fast way to render static text. + *

* - *

The code is heavily based on Matthias Mann's TWL BitmapFont class. Thanks for sharing - * Matthias :)

+ *

+ * The code is heavily based on Matthias Mann's TWL BitmapFont class. Thanks for sharing Matthias :) + *

* * @author nathan.sweet - * + * */ public class BitmapFontCache { private final Texture texture; @@ -38,7 +40,7 @@ public class BitmapFontCache { /** * Translates the text - * @param xAmount the amount in x to move the text + * @param xAmount the amount in x to move the text * @param yAmount the amount in y to move the text */ public void translate (float xAmount, float yAmount) { @@ -101,8 +103,8 @@ public class BitmapFontCache { } /** - * Draws the contents of the given cache via a {@link SpriteBatch}. Must - * be called between a {@link SpriteBatch#begin()}/{@link SpriteBatch#end()} pair. + * Draws the contents of the given cache via a {@link SpriteBatch}. Must be called between a {@link SpriteBatch#begin()}/ + * {@link SpriteBatch#end()} pair. * @param spriteBatch the SpriteBatch. */ public void draw (SpriteBatch spriteBatch) { @@ -115,7 +117,7 @@ public class BitmapFontCache { idx = 0; int vertexCount = glyphCount * 20; - if ( vertices == null || vertices.length < vertexCount) vertices = new float[vertexCount]; + if (vertices == null || vertices.length < vertexCount) vertices = new float[vertexCount]; } /** diff --git a/gdx/src/com/badlogic/gdx/graphics/Color.java b/gdx/src/com/badlogic/gdx/graphics/Color.java index 35422c346..4c9255749 100644 --- a/gdx/src/com/badlogic/gdx/graphics/Color.java +++ b/gdx/src/com/badlogic/gdx/graphics/Color.java @@ -1,40 +1,35 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ -package com.badlogic.gdx.graphics; +package com.badlogic.gdx.graphics; /** - * A color class, holding the r, g, b and alpha component - * as floats in the range [0,1]. All methods perform clamping - * on the internal values after execution. + * A color class, holding the r, g, b and alpha component as floats in the range [0,1]. All methods perform clamping on the + * internal values after execution. * * @author mzechner - * + * */ -public class Color -{ - public static final Color WHITE = new Color( 1, 1, 1, 1 ); - public static final Color BLACK = new Color( 0, 0, 0, 1 ); - public static final Color RED = new Color( 1, 0, 0, 1 ); - public static final Color GREEN = new Color( 0, 1, 0, 1 ); - public static final Color BLUE = new Color( 0, 0, 1, 1 ); - +public class Color { + public static final Color WHITE = new Color(1, 1, 1, 1); + public static final Color BLACK = new Color(0, 0, 0, 1); + public static final Color RED = new Color(1, 0, 0, 1); + public static final Color GREEN = new Color(0, 1, 0, 1); + public static final Color BLUE = new Color(0, 0, 1, 1); + /** the red, green, blue and alpha components **/ public float r, g, b, a; - + /** * Constructor, sets the components of the color * @param r the red component @@ -42,8 +37,7 @@ public class Color * @param b the blue component * @param a the alpha component */ - public Color( float r, float g, float b, float a ) - { + public Color (float r, float g, float b, float a) { this.r = r; this.g = g; this.b = b; @@ -55,17 +49,15 @@ public class Color * Constructs a new color using the given color * @param color the color */ - public Color( Color color ) - { - set( color ); + public Color (Color color) { + set(color); } - + /** * Sets this color to the given color. * @param color the Color */ - public Color set( Color color ) - { + public Color set (Color color) { this.r = color.r; this.g = color.g; this.b = color.b; @@ -73,14 +65,13 @@ public class Color clamp(); return this; } - + /** * Multiplies the this color and the given color * @param color the color * @return this color. */ - public Color mul( Color color ) - { + public Color mul (Color color) { this.r *= color.r; this.g *= color.g; this.b *= color.b; @@ -90,13 +81,12 @@ public class Color } /** - * Multiplies all components of this Color with the given value. + * Multiplies all components of this Color with the given value. * * @param value the value * @return this color */ - public Color mul(float value) - { + public Color mul (float value) { this.r *= value; this.g *= value; this.b *= value; @@ -104,18 +94,17 @@ public class Color clamp(); return this; } - + /** * Adds the given color to this color. * @param color the color * @return this color */ - public Color add( Color color ) - { + public Color add (Color color) { this.r += color.r; this.g += color.g; this.b += color.b; - this.a += color.a; + this.a += color.a; clamp(); return this; } @@ -125,8 +114,7 @@ public class Color * @param color the color * @return this color */ - public Color sub(Color color) - { + public Color sub (Color color) { this.r -= color.r; this.g -= color.g; this.b -= color.b; @@ -134,125 +122,105 @@ public class Color clamp(); return this; } - - public void clamp( ) - { - if( r < 0 ) r = 0; - if( r > 1 ) r = 1; - - if( g < 0 ) g = 0; - if( g > 1 ) g = 1; - - if( b < 0 ) b = 0; - if( b > 1 ) b = 1; - - if( a < 0 ) a = 0; - if( a > 1 ) a = 1; + + public void clamp () { + if (r < 0) r = 0; + if (r > 1) r = 1; + + if (g < 0) g = 0; + if (g > 1) g = 1; + + if (b < 0) b = 0; + if (b > 1) b = 1; + + if (a < 0) a = 0; + if (a > 1) a = 1; } - public void set(float r, float g, float b, float a) - { + public void set (float r, float g, float b, float a) { this.r = r; this.g = g; this.b = b; this.a = a; } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override public boolean equals (Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; - Color color = (Color) o; + Color color = (Color)o; - if (Float.compare(color.a, a) != 0) return false; - if (Float.compare(color.b, b) != 0) return false; - if (Float.compare(color.g, g) != 0) return false; - if (Float.compare(color.r, r) != 0) return false; + if (Float.compare(color.a, a) != 0) return false; + if (Float.compare(color.b, b) != 0) return false; + if (Float.compare(color.g, g) != 0) return false; + if (Float.compare(color.r, r) != 0) return false; - return true; - } + return true; + } - @Override - public int hashCode() { - int result = (r != +0.0f ? Float.floatToIntBits(r) : 0); - result = 31 * result + (g != +0.0f ? Float.floatToIntBits(g) : 0); - result = 31 * result + (b != +0.0f ? Float.floatToIntBits(b) : 0); - result = 31 * result + (a != +0.0f ? Float.floatToIntBits(a) : 0); - return result; - } - - /** - * Packs the four color components which should be in the range 0-255 into - * a 32-bit integer and then converts it to a float. Note that no range - * checking is performed for higher performance. - * @param r the red component, 0 - 255 - * @param g the green component, 0 - 255 - * @param b the blue component, 0 - 255 - * @param a the alpha component, 0 - 255 - * @return the packed color as a float - */ - public static float toFloatBits( int r, int g, int b, int a ) - { - int color = ( a << 24 ) | ( b << 16 ) | ( g << 8 ) | r; - float floatColor = Float.intBitsToFloat( color ); - return floatColor; - } + @Override public int hashCode () { + int result = (r != +0.0f ? Float.floatToIntBits(r) : 0); + result = 31 * result + (g != +0.0f ? Float.floatToIntBits(g) : 0); + result = 31 * result + (b != +0.0f ? Float.floatToIntBits(b) : 0); + result = 31 * result + (a != +0.0f ? Float.floatToIntBits(a) : 0); + return result; + } - /** - * Packs the four color components which should be in the range 0-255 into - * a 32-bit. Note that no range checking is performed for higher performance. - * @param r the red component, 0 - 255 - * @param g the green component, 0 - 255 - * @param b the blue component, 0 - 255 - * @param a the alpha component, 0 - 255 - * @return the packed color as a 32-bit int - */ - public static float toIntBits( int r, int g, int b, int a ) - { - return ( a << 24 ) | ( b << 16 ) | ( g << 8 ) | r; + /** + * Packs the four color components which should be in the range 0-255 into a 32-bit integer and then converts it to a float. + * Note that no range checking is performed for higher performance. + * @param r the red component, 0 - 255 + * @param g the green component, 0 - 255 + * @param b the blue component, 0 - 255 + * @param a the alpha component, 0 - 255 + * @return the packed color as a float + */ + public static float toFloatBits (int r, int g, int b, int a) { + int color = (a << 24) | (b << 16) | (g << 8) | r; + float floatColor = Float.intBitsToFloat(color); + return floatColor; + } - } - - /** - * Packs the 4 components of this color into a 32-bit int and returns it as a - * float. - * - * @return the packed color as a 32-bit float - */ - public float toFloatBits( ) - { - int color = ( (int)( 255 * a ) << 24 ) | - ( (int)( 255 * b ) << 16 ) | - ( (int)( 255 * g ) << 8 ) | - ( (int)( 255 * r ) ); - return Float.intBitsToFloat( color ); - } - - /** - * Packs the 4 components of this color into a 32-bit int. - * @return the packed color as a 32-bit int. - */ - public int toIntBits( ) - { - int color = ( (int)( 255 * a ) << 24 ) | - ( (int)( 255 * b ) << 16 ) | - ( (int)( 255 * g ) << 8 ) | - ( (int)( 255 * r ) ); - return color; - } + /** + * Packs the four color components which should be in the range 0-255 into a 32-bit. Note that no range checking is performed + * for higher performance. + * @param r the red component, 0 - 255 + * @param g the green component, 0 - 255 + * @param b the blue component, 0 - 255 + * @param a the alpha component, 0 - 255 + * @return the packed color as a 32-bit int + */ + public static float toIntBits (int r, int g, int b, int a) { + return (a << 24) | (b << 16) | (g << 8) | r; + + } + + /** + * Packs the 4 components of this color into a 32-bit int and returns it as a float. + * + * @return the packed color as a 32-bit float + */ + public float toFloatBits () { + int color = ((int)(255 * a) << 24) | ((int)(255 * b) << 16) | ((int)(255 * g) << 8) | ((int)(255 * r)); + return Float.intBitsToFloat(color); + } + + /** + * Packs the 4 components of this color into a 32-bit int. + * @return the packed color as a 32-bit int. + */ + public int toIntBits () { + int color = ((int)(255 * a) << 24) | ((int)(255 * b) << 16) | ((int)(255 * g) << 8) | ((int)(255 * r)); + return color; + } - /** - * Packs the 4 components of this color into a 32-bit int and returns it as a - * float. - * - * @return the packed color as a 32-bit float - */ - public static float toFloatBits(float r, float g, float b, float a) { - int color = ( (int)( 255 * a ) << 24 ) | - ( (int)( 255 * b ) << 16 ) | - ( (int)( 255 * g ) << 8 ) | - ( (int)( 255 * r ) ); - return Float.intBitsToFloat( color ); + /** + * Packs the 4 components of this color into a 32-bit int and returns it as a float. + * + * @return the packed color as a 32-bit float + */ + public static float toFloatBits (float r, float g, float b, float a) { + int color = ((int)(255 * a) << 24) | ((int)(255 * b) << 16) | ((int)(255 * g) << 8) | ((int)(255 * r)); + return Float.intBitsToFloat(color); } } diff --git a/gdx/src/com/badlogic/gdx/graphics/Font.java b/gdx/src/com/badlogic/gdx/graphics/Font.java index 316742b0b..a0aa7543c 100644 --- a/gdx/src/com/badlogic/gdx/graphics/Font.java +++ b/gdx/src/com/badlogic/gdx/graphics/Font.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics; import java.util.ArrayList; @@ -25,12 +23,9 @@ import com.badlogic.gdx.math.Rectangle; /** *

- * A Font creates glyph bitmaps and stores them in a texture cache. - * It has methods to retrieve text metrics to calculate bounds. To - * render text with a specific Font one has to use a {@link SpriteBatch} - * instance and it's {@link SpriteBatch.drawText()} method. Once the Font is no longer - * needed it has to be disposed via the {@link Font.dispose()} method - * to free all resources. + * A Font creates glyph bitmaps and stores them in a texture cache. It has methods to retrieve text metrics to calculate bounds. + * To render text with a specific Font one has to use a {@link SpriteBatch} instance and it's {@link SpriteBatch.drawText()} + * method. Once the Font is no longer needed it has to be disposed via the {@link Font.dispose()} method to free all resources. *

* *

@@ -38,201 +33,178 @@ import com.badlogic.gdx.math.Rectangle; *

* *

- * A Font can be managed. In case the OpenGL context is lost all OpenGL resources - * such as textures get invalidated and have to be reloaded. A Font is basically a - * texture and is thus also invalidated by a context loss. A context loss happens - * when a user presses switches to another application or receives an incoming call. This - * only happens on Android, there are not context losses on the desktop. A managed Font - * will be reloaded automatically after a context loss so you don't have to do that - * manually. The drawback: it uses twice the memory for storing the original bitmap - * from which the texture cache was created. Use this only if you know that you have - * enough memory available. Future versions will use a different mechanism to get - * rid of this additional memory overhead. + * A Font can be managed. In case the OpenGL context is lost all OpenGL resources such as textures get invalidated and have to be + * reloaded. A Font is basically a texture and is thus also invalidated by a context loss. A context loss happens when a user + * presses switches to another application or receives an incoming call. This only happens on Android, there are not context + * losses on the desktop. A managed Font will be reloaded automatically after a context loss so you don't have to do that + * manually. The drawback: it uses twice the memory for storing the original bitmap from which the texture cache was created. Use + * this only if you know that you have enough memory available. Future versions will use a different mechanism to get rid of this + * additional memory overhead. *

* * @author badlogicgames@gmail.com - * - * FIXME this class could be improved quiet a lot. Dynamical texture resizes, better - * subregion allocation and so on. + * + * FIXME this class could be improved quiet a lot. Dynamical texture resizes, better subregion allocation and so on. */ -public abstract class Font -{ +public abstract class Font { protected static final Pixmap.Format pixelFormat = Pixmap.Format.RGBA8888; - + /** * The font style * @author mzechner - * + * */ - public enum FontStyle - { - Plain, - Bold, - Italic, - BoldItalic + public enum FontStyle { + Plain, Bold, Italic, BoldItalic } - + private final static int TEXTURE_WIDTH = 512; private final static int TEXTURE_HEIGHT = 512; - + /** the glyph texture **/ private Texture texture; - + /** glyph hashmap **/ // FIXME potentially wasteful, for the time being we keep it as a hashmap would be even worse. private final Glyph[] glyphs = new Glyph[Character.MAX_VALUE]; - + /** current position in glyph texture to write the next glyph to **/ private int glyphX = 0; private int glyphY = 0; - - private static final List fonts = new ArrayList( ); - - protected Font( ) - { - fonts.add( this ); + + private static final List fonts = new ArrayList(); + + protected Font () { + fonts.add(this); build(); } - - private void build( ) - { - for( int i = 0; i < glyphs.length; i++ ) + + private void build () { + for (int i = 0; i < glyphs.length; i++) glyphs[i] = null; - this.texture = Gdx.graphics.newUnmanagedTexture( TEXTURE_WIDTH, TEXTURE_HEIGHT, pixelFormat, TextureFilter.Nearest, TextureFilter.Nearest, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); + this.texture = Gdx.graphics.newUnmanagedTexture(TEXTURE_WIDTH, TEXTURE_HEIGHT, pixelFormat, TextureFilter.Nearest, + TextureFilter.Nearest, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); glyphX = 0; glyphY = 0; } - + /** - * Disposes the font and all associated - * resources. + * Disposes the font and all associated resources. */ - public void dispose( ) - { - fonts.remove( this ); + public void dispose () { + fonts.remove(this); texture.dispose(); } - + /** * @return The height of a line in pixels */ - public abstract int getLineHeight( ); - + public abstract int getLineHeight (); + /** * @return The gap in pixels between two lines */ - public abstract int getLineGap( ); - + public abstract int getLineGap (); + /** - * Returns a bitmap containing the glyph for the - * given character. The bitmap height equals the - * value returned by getLineHeight() + * Returns a bitmap containing the glyph for the given character. The bitmap height equals the value returned by + * getLineHeight() * * @param character The character to get the glyph for * @return A {@link Pixmap} containing the glyph */ - protected abstract Pixmap getGlyphBitmap( char character ); - + protected abstract Pixmap getGlyphBitmap (char character); + /** * @param character The character to get the advance for * @return The advance in pixels */ - public abstract int getGlyphAdvance( char character ); - + public abstract int getGlyphAdvance (char character); + /** * Returns the pixel bounds of a glyph * @param character The character * @param Rect structure to be filled with the bounds */ - public abstract void getGlyphBounds( char character, Rectangle rect ); - + public abstract void getGlyphBounds (char character, Rectangle rect); + /** - * Returns the width of the string in pixels. Note that this - * ignores newlines. + * Returns the width of the string in pixels. Note that this ignores newlines. * * @param text The text to get the width for * @return The width of the text in pixels */ - public abstract int getStringWidth( String text ); - + public abstract int getStringWidth (String text); + /** * @return The glyph texture */ - public Texture getTexture( ) - { + public Texture getTexture () { return texture; } - + /** * Returns the glyph for the given character * * @param character The character * @return The glyph of the character */ - public Glyph getGlyph( char character ) - { + public Glyph getGlyph (char character) { Glyph glyph = glyphs[character]; - if( glyph == null ) - { + if (glyph == null) { glyph = createGlyph(character); glyphs[character] = glyph; } return glyph; } - - private Glyph createGlyph( char character ) - { - Pixmap bitmap = getGlyphBitmap( character ); - Rectangle rect = new Rectangle( ); - getGlyphBounds( character, rect ); - - if( glyphX + rect.getWidth() >= TEXTURE_WIDTH) - { + + private Glyph createGlyph (char character) { + Pixmap bitmap = getGlyphBitmap(character); + Rectangle rect = new Rectangle(); + getGlyphBounds(character, rect); + + if (glyphX + rect.getWidth() >= TEXTURE_WIDTH) { glyphX = 0; glyphY += getLineGap() + getLineHeight(); } - - texture.draw( bitmap, glyphX, glyphY ); - - Glyph glyph = new Glyph( getGlyphAdvance( character ), (int)rect.getWidth(), (int)rect.getHeight(), glyphX / (float)TEXTURE_WIDTH, glyphY / (float)TEXTURE_HEIGHT, rect.getWidth() / (float)TEXTURE_WIDTH, rect.getHeight() / (float)TEXTURE_HEIGHT); + + texture.draw(bitmap, glyphX, glyphY); + + Glyph glyph = new Glyph(getGlyphAdvance(character), (int)rect.getWidth(), (int)rect.getHeight(), glyphX + / (float)TEXTURE_WIDTH, glyphY / (float)TEXTURE_HEIGHT, rect.getWidth() / (float)TEXTURE_WIDTH, rect.getHeight() + / (float)TEXTURE_HEIGHT); glyphX += rect.getWidth(); - return glyph; + return glyph; } - + /** - * This rebuilds all fonts currently alive. Used when the OpenGL context - * was lost and is being reconstructed. Use with care. + * This rebuilds all fonts currently alive. Used when the OpenGL context was lost and is being reconstructed. Use with care. */ - public static void invalidateAllFonts( ) - { - for( int i = 0; i < fonts.size(); i++ ) + public static void invalidateAllFonts () { + for (int i = 0; i < fonts.size(); i++) fonts.get(i).build(); } - - public static void clearAllFonts( ) - { + + public static void clearAllFonts () { fonts.clear(); } - - /** - * Package private helper class to store - * glyph information. + + /** + * Package private helper class to store glyph information. * * @author mzechner - * + * */ - public static class Glyph - { + public static class Glyph { public int advance; - public int width; + public int width; public int height; public float u; public float v; public float uWidth; public float vHeight; - - public Glyph( int advance, int width, int height, float u, float v, float uWidth, float vHeight ) - { + + public Glyph (int advance, int width, int height, float u, float v, float uWidth, float vHeight) { this.advance = advance; this.width = width; this.height = height; diff --git a/gdx/src/com/badlogic/gdx/graphics/FrameBuffer.java b/gdx/src/com/badlogic/gdx/graphics/FrameBuffer.java index 871ecf895..04d091435 100644 --- a/gdx/src/com/badlogic/gdx/graphics/FrameBuffer.java +++ b/gdx/src/com/badlogic/gdx/graphics/FrameBuffer.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics; import java.nio.ByteBuffer; @@ -27,199 +25,181 @@ import com.badlogic.gdx.graphics.Texture.TextureWrap; /** *

- * Encapsulates OpenGL ES 2.0 frame buffer objects. This is a simple helper - * class which should cover most FBO uses. It will automatically create a - * texture for the color attachment and a renderbuffer for the depth buffer. - * You can get a hold of the texture by {@link FrameBuffer.getColorBufferTexture()}. - * This class will only work with OpenGL ES 2.0. + * Encapsulates OpenGL ES 2.0 frame buffer objects. This is a simple helper class which should cover most FBO uses. It will + * automatically create a texture for the color attachment and a renderbuffer for the depth buffer. You can get a hold of the + * texture by {@link FrameBuffer.getColorBufferTexture()}. This class will only work with OpenGL ES 2.0. *

* *

- * FrameBuffers can be managed. In case of an OpenGL context loss, which only happens - * on Android when a user switches to another application or receives an incoming call, the - * framebuffer will be automatically recreated. This will essentially double the size - * of the memory used so use this feature with care. Future versions will fix this and not - * eat up additional memory. + * FrameBuffers can be managed. In case of an OpenGL context loss, which only happens on Android when a user switches to another + * application or receives an incoming call, the framebuffer will be automatically recreated. This will essentially double the + * size of the memory used so use this feature with care. Future versions will fix this and not eat up additional memory. *

- * + * * @author mzechner - * + * */ -public class FrameBuffer -{ +public class FrameBuffer { /** the frame buffers **/ private final static ArrayList buffers = new ArrayList(); - + /** the color buffer texture **/ - private Texture colorTexture; - + private Texture colorTexture; + /** the framebuffer handle **/ private int framebufferHandle; - + /** the depthbuffer render object handle **/ private int depthbufferHandle; - + /** width **/ private final int width; - + /** height **/ private final int height; - + /** format **/ private final Pixmap.Format format; - + /** - * Creates a new FrameBuffer having the given dimensions and potentially - * a depth buffer attached. + * Creates a new FrameBuffer having the given dimensions and potentially a depth buffer attached. * * @param format the format of the color buffer * @param width the width of the framebuffer in pixels - * @param height the height of the framebuffer in pixels + * @param height the height of the framebuffer in pixels * @param hasDepth whether to attach a depth buffer * @param managed whether this framebuffer should be managed * @throws GdxRuntimeException in case the FraeBuffer could not be created */ - public FrameBuffer( Pixmap.Format format, int width, int height, boolean hasDepth ) - { + public FrameBuffer (Pixmap.Format format, int width, int height, boolean hasDepth) { this.width = width; this.height = height; this.format = format; - build( ); - - buffers.add( this ); + build(); + + buffers.add(this); } - - private void build( ) - { - colorTexture = Gdx.graphics.newUnmanagedTexture(width, height, format, TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); + + private void build () { + colorTexture = Gdx.graphics.newUnmanagedTexture(width, height, format, TextureFilter.Linear, TextureFilter.Linear, + TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); GL20 gl = Gdx.graphics.getGL20(); - + ByteBuffer tmp = ByteBuffer.allocateDirect(4); tmp.order(ByteOrder.nativeOrder()); IntBuffer handle = tmp.asIntBuffer(); - - gl.glGenFramebuffers( 1, handle ); + + gl.glGenFramebuffers(1, handle); framebufferHandle = handle.get(0); - - gl.glGenRenderbuffers( 1, handle ); + + gl.glGenRenderbuffers(1, handle); depthbufferHandle = handle.get(0); - - gl.glBindTexture( GL20.GL_TEXTURE_2D, colorTexture.getTextureObjectHandle() ); - gl.glBindRenderbuffer( GL20.GL_RENDERBUFFER, depthbufferHandle ); - gl.glRenderbufferStorage( GL20.GL_RENDERBUFFER, GL20.GL_DEPTH_COMPONENT16, colorTexture.getWidth(), colorTexture.getHeight() ); - - gl.glBindFramebuffer( GL20.GL_FRAMEBUFFER, framebufferHandle ); - gl.glFramebufferTexture2D( GL20.GL_FRAMEBUFFER, GL20.GL_COLOR_ATTACHMENT0, GL20.GL_TEXTURE_2D, colorTexture.getTextureObjectHandle(), 0 ); - gl.glFramebufferRenderbuffer( GL20.GL_FRAMEBUFFER, GL20.GL_DEPTH_ATTACHMENT, GL20.GL_RENDERBUFFER, depthbufferHandle ); - int result = gl.glCheckFramebufferStatus( GL20.GL_FRAMEBUFFER ); - - gl.glBindRenderbuffer( GL20.GL_RENDERBUFFER, 0); - gl.glBindTexture( GL20.GL_TEXTURE_2D, 0); - gl.glBindFramebuffer( GL20.GL_FRAMEBUFFER, 0); - - if( result != GL20.GL_FRAMEBUFFER_COMPLETE ) - { + + gl.glBindTexture(GL20.GL_TEXTURE_2D, colorTexture.getTextureObjectHandle()); + gl.glBindRenderbuffer(GL20.GL_RENDERBUFFER, depthbufferHandle); + gl.glRenderbufferStorage(GL20.GL_RENDERBUFFER, GL20.GL_DEPTH_COMPONENT16, colorTexture.getWidth(), colorTexture.getHeight()); + + gl.glBindFramebuffer(GL20.GL_FRAMEBUFFER, framebufferHandle); + gl.glFramebufferTexture2D(GL20.GL_FRAMEBUFFER, GL20.GL_COLOR_ATTACHMENT0, GL20.GL_TEXTURE_2D, + colorTexture.getTextureObjectHandle(), 0); + gl.glFramebufferRenderbuffer(GL20.GL_FRAMEBUFFER, GL20.GL_DEPTH_ATTACHMENT, GL20.GL_RENDERBUFFER, depthbufferHandle); + int result = gl.glCheckFramebufferStatus(GL20.GL_FRAMEBUFFER); + + gl.glBindRenderbuffer(GL20.GL_RENDERBUFFER, 0); + gl.glBindTexture(GL20.GL_TEXTURE_2D, 0); + gl.glBindFramebuffer(GL20.GL_FRAMEBUFFER, 0); + + if (result != GL20.GL_FRAMEBUFFER_COMPLETE) { colorTexture.dispose(); - handle.put( depthbufferHandle ); + handle.put(depthbufferHandle); handle.flip(); - gl.glDeleteRenderbuffers( 1, handle ); - - handle.put( framebufferHandle ); + gl.glDeleteRenderbuffers(1, handle); + + handle.put(framebufferHandle); handle.flip(); - gl.glDeleteFramebuffers( 1, handle ); - - if( result == GL20.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT ) - throw new IllegalStateException( "frame buffer couldn't be constructed: incomplete attachment" ); - if( result == GL20.GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS ) - throw new IllegalStateException( "frame buffer couldn't be constructed: incomplete dimensions" ); - if( result == GL20.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT ) - throw new IllegalStateException( "frame buffer couldn't be constructed: missing attachment" ); - } + gl.glDeleteFramebuffers(1, handle); + + if (result == GL20.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT) + throw new IllegalStateException("frame buffer couldn't be constructed: incomplete attachment"); + if (result == GL20.GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS) + throw new IllegalStateException("frame buffer couldn't be constructed: incomplete dimensions"); + if (result == GL20.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT) + throw new IllegalStateException("frame buffer couldn't be constructed: missing attachment"); + } } - + /** * Releases all resources associated with the FrameBuffer. */ - public void dispose( ) - { + public void dispose () { GL20 gl = Gdx.graphics.getGL20(); - + ByteBuffer tmp = ByteBuffer.allocateDirect(4); tmp.order(ByteOrder.nativeOrder()); IntBuffer handle = tmp.asIntBuffer(); - + colorTexture.dispose(); - handle.put( depthbufferHandle ); + handle.put(depthbufferHandle); handle.flip(); - gl.glDeleteRenderbuffers( 1, handle ); - - handle.put( framebufferHandle ); + gl.glDeleteRenderbuffers(1, handle); + + handle.put(framebufferHandle); handle.flip(); - gl.glDeleteFramebuffers( 1, handle ); - - buffers.remove( this ); + gl.glDeleteFramebuffers(1, handle); + + buffers.remove(this); } - + /** * Makes the frame buffer current so everything gets drawn to it. */ - public void begin( ) - { - Gdx.graphics.getGL20().glViewport( 0, 0, colorTexture.getWidth(), colorTexture.getHeight() ); - Gdx.graphics.getGL20().glBindFramebuffer( GL20.GL_FRAMEBUFFER, framebufferHandle ); + public void begin () { + Gdx.graphics.getGL20().glViewport(0, 0, colorTexture.getWidth(), colorTexture.getHeight()); + Gdx.graphics.getGL20().glBindFramebuffer(GL20.GL_FRAMEBUFFER, framebufferHandle); } - + /** * Unbinds the framebuffer, all drawing will be performed to the normal framebuffer from here on. */ - public void end( ) - { - Gdx.graphics.getGL20().glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - Gdx.graphics.getGL20().glBindFramebuffer( GL20.GL_FRAMEBUFFER, 0 ); + public void end () { + Gdx.graphics.getGL20().glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + Gdx.graphics.getGL20().glBindFramebuffer(GL20.GL_FRAMEBUFFER, 0); } - + /** - * Invalidates all frame buffers. This can be used when the OpenGL context is - * lost to rebuild all managed frame buffers. This assumes that the texture - * attached to this buffer has already been rebuild! Use with care. + * Invalidates all frame buffers. This can be used when the OpenGL context is lost to rebuild all managed frame buffers. This + * assumes that the texture attached to this buffer has already been rebuild! Use with care. */ - public static void invalidateAllFrameBuffers( ) - { - if( Gdx.graphics.getGL20() == null ) - return; - - for( int i = 0; i < buffers.size(); i++ ) - { + public static void invalidateAllFrameBuffers () { + if (Gdx.graphics.getGL20() == null) return; + + for (int i = 0; i < buffers.size(); i++) { buffers.get(i).build(); } } - - public static void clearAllFrameBuffers( ) - { + + public static void clearAllFrameBuffers () { buffers.clear(); } /** * @return the color buffer texture */ - public Texture getColorBufferTexture() - { + public Texture getColorBufferTexture () { return colorTexture; } /** * @return the height of the framebuffer in pixels */ - public int getHeight() - { + public int getHeight () { return colorTexture.getHeight(); } /** * @return the width of the framebuffer in pixels */ - public int getWidth() - { + public int getWidth () { return colorTexture.getWidth(); } } diff --git a/gdx/src/com/badlogic/gdx/graphics/GL10.java b/gdx/src/com/badlogic/gdx/graphics/GL10.java index b7bfb80e4..0af5148e0 100644 --- a/gdx/src/com/badlogic/gdx/graphics/GL10.java +++ b/gdx/src/com/badlogic/gdx/graphics/GL10.java @@ -1,19 +1,18 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics; + import java.nio.Buffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; @@ -22,10 +21,9 @@ import java.nio.IntBuffer; * Interface wrapping all standard OpenGL ES 1.0 methods. * * @author mzechner - * + * */ -public interface GL10 extends GLCommon -{ +public interface GL10 extends GLCommon { public static final int GL_OES_VERSION_1_0 = 1; public static final int GL_OES_read_format = 1; public static final int GL_OES_compressed_paletted_texture = 1; @@ -62,7 +60,7 @@ public interface GL10 extends GLCommon public static final int GL_SRC_ALPHA_SATURATE = 0x0308; public static final int GL_FRONT = 0x0404; public static final int GL_BACK = 0x0405; - public static final int GL_FRONT_AND_BACK = 0x0408; + public static final int GL_FRONT_AND_BACK = 0x0408; public static final int GL_FOG = 0x0B60; public static final int GL_LIGHTING = 0x0B50; public static final int GL_TEXTURE_2D = 0x0DE1; @@ -269,169 +267,169 @@ public interface GL10 extends GLCommon public static final int GL_LINE = 0x1B01; public static final int GL_FILL = 0x1B02; - public void glAlphaFunc ( int func, float ref ); + public void glAlphaFunc (int func, float ref); + + public void glAlphaFuncx (int func, int ref); + + public void glClearColorx (int red, int green, int blue, int alpha); + + public void glClearDepthx (int depth); + + public void glClientActiveTexture (int texture); + + public void glColor4f (float red, float green, float blue, float alpha); + + public void glColor4x (int red, int green, int blue, int alpha); + + public void glColorPointer (int size, int type, int stride, Buffer pointer); + + public void glDeleteTextures (int n, int[] textures, int offset); + + public void glDepthRangex (int zNear, int zFar); + + public void glDisableClientState (int array); + + public void glEnableClientState (int array); + + public void glFogf (int pname, float param); + + public void glFogfv (int pname, float[] params, int offset); + + public void glFogfv (int pname, FloatBuffer params); - public void glAlphaFuncx ( int func, int ref ); + public void glFogx (int pname, int param); - public void glClearColorx ( int red, int green, int blue, int alpha ); + public void glFogxv (int pname, int[] params, int offset); - public void glClearDepthx ( int depth ); + public void glFogxv (int pname, IntBuffer params); - public void glClientActiveTexture ( int texture ); + public void glFrustumf (float left, float right, float bottom, float top, float zNear, float zFar); - public void glColor4f ( float red, float green, float blue, float alpha ); + public void glFrustumx (int left, int right, int bottom, int top, int zNear, int zFar); - public void glColor4x ( int red, int green, int blue, int alpha ); + public void glGenTextures (int n, int[] textures, int offset); - public void glColorPointer ( int size, int type, int stride, Buffer pointer ); + public void glGetIntegerv (int pname, int[] params, int offset); - public void glDeleteTextures( int n, int[] textures, int offset ); + public void glLightModelf (int pname, float param); - public void glDepthRangex ( int zNear, int zFar ); + public void glLightModelfv (int pname, float[] params, int offset); - public void glDisableClientState ( int array ); + public void glLightModelfv (int pname, FloatBuffer params); - public void glEnableClientState ( int array ); + public void glLightModelx (int pname, int param); - public void glFogf ( int pname, float param ); + public void glLightModelxv (int pname, int[] params, int offset); - public void glFogfv ( int pname, float[] params, int offset ); - - public void glFogfv ( int pname, FloatBuffer params ); + public void glLightModelxv (int pname, IntBuffer params); - public void glFogx ( int pname, int param ); + public void glLightf (int light, int pname, float param); - public void glFogxv ( int pname, int[] params, int offset ); - - public void glFogxv ( int pname, IntBuffer params ); + public void glLightfv (int light, int pname, float[] params, int offset); - public void glFrustumf ( float left, float right, float bottom, float top, float zNear, float zFar ); + public void glLightfv (int light, int pname, FloatBuffer params); - public void glFrustumx ( int left, int right, int bottom, int top, int zNear, int zFar ); + public void glLightx (int light, int pname, int param); - public void glGenTextures ( int n, int[] textures, int offset ); + public void glLightxv (int light, int pname, int[] params, int offset); - public void glGetIntegerv ( int pname, int[] params, int offset ); + public void glLightxv (int light, int pname, IntBuffer params); - public void glLightModelf ( int pname, float param ); + public void glLineWidthx (int width); - public void glLightModelfv ( int pname, float[] params, int offset ); - - public void glLightModelfv ( int pname, FloatBuffer params ); + public void glLoadIdentity (); - public void glLightModelx ( int pname, int param ); + public void glLoadMatrixf (float[] m, int offset); - public void glLightModelxv ( int pname, int[] params, int offset ); - - public void glLightModelxv ( int pname, IntBuffer params ); + public void glLoadMatrixf (FloatBuffer m); - public void glLightf ( int light, int pname, float param ); + public void glLoadMatrixx (int[] m, int offset); - public void glLightfv ( int light, int pname, float[] params, int offset ); - - public void glLightfv ( int light, int pname, FloatBuffer params ); + public void glLoadMatrixx (IntBuffer m); - public void glLightx ( int light, int pname, int param ); + public void glLogicOp (int opcode); - public void glLightxv ( int light, int pname, int[] params, int offset ); - - public void glLightxv ( int light, int pname, IntBuffer params ); + public void glMaterialf (int face, int pname, float param); - public void glLineWidthx ( int width ); + public void glMaterialfv (int face, int pname, float[] params, int offset); - public void glLoadIdentity ( ); + public void glMaterialfv (int face, int pname, FloatBuffer params); - public void glLoadMatrixf ( float[] m, int offset ); - - public void glLoadMatrixf ( FloatBuffer m ); + public void glMaterialx (int face, int pname, int param); - public void glLoadMatrixx( int[] m, int offset ); - - public void glLoadMatrixx ( IntBuffer m ); + public void glMaterialxv (int face, int pname, int[] params, int offset); - public void glLogicOp ( int opcode ); + public void glMaterialxv (int face, int pname, IntBuffer params); - public void glMaterialf ( int face, int pname, float param ); + public void glMatrixMode (int mode); - public void glMaterialfv ( int face, int pname, float[] params, int offset ); - - public void glMaterialfv ( int face, int pname, FloatBuffer params ); + public void glMultMatrixf (float[] m, int offset); - public void glMaterialx ( int face, int pname, int param ); + public void glMultMatrixf (FloatBuffer m); - public void glMaterialxv ( int face, int pname, int[] params, int offset ); - - public void glMaterialxv ( int face, int pname, IntBuffer params ); + public void glMultMatrixx (int[] m, int offset); - public void glMatrixMode ( int mode ); + public void glMultMatrixx (IntBuffer m); - public void glMultMatrixf ( float[] m, int offset ); - - public void glMultMatrixf ( FloatBuffer m ); + public void glMultiTexCoord4f (int target, float s, float t, float r, float q); - public void glMultMatrixx ( int[] m, int offset ); - - public void glMultMatrixx ( IntBuffer m ); + public void glMultiTexCoord4x (int target, int s, int t, int r, int q); - public void glMultiTexCoord4f ( int target, float s, float t, float r, float q ); + public void glNormal3f (float nx, float ny, float nz); - public void glMultiTexCoord4x ( int target, int s, int t, int r, int q ); + public void glNormal3x (int nx, int ny, int nz); - public void glNormal3f ( float nx, float ny, float nz ); + public void glNormalPointer (int type, int stride, Buffer pointer); - public void glNormal3x ( int nx, int ny, int nz ); + public void glOrthof (float left, float right, float bottom, float top, float zNear, float zFar); - public void glNormalPointer ( int type, int stride, Buffer pointer ); + public void glOrthox (int left, int right, int bottom, int top, int zNear, int zFar); - public void glOrthof ( float left, float right, float bottom, float top, float zNear, float zFar ); + public void glPointSize (float size); - public void glOrthox ( int left, int right, int bottom, int top, int zNear, int zFar ); + public void glPointSizex (int size); - public void glPointSize ( float size ); + public void glPolygonOffsetx (int factor, int units); - public void glPointSizex ( int size ); + public void glPopMatrix (); - public void glPolygonOffsetx ( int factor, int units ); + public void glPushMatrix (); - public void glPopMatrix ( ); + public void glRotatef (float angle, float x, float y, float z); - public void glPushMatrix ( ); + public void glRotatex (int angle, int x, int y, int z); - public void glRotatef ( float angle, float x, float y, float z ); + public void glSampleCoverage (float value, boolean invert); - public void glRotatex ( int angle, int x, int y, int z ); + public void glSampleCoveragex (int value, boolean invert); - public void glSampleCoverage ( float value, boolean invert ); + public void glScalef (float x, float y, float z); - public void glSampleCoveragex ( int value, boolean invert ); + public void glScalex (int x, int y, int z); - public void glScalef ( float x, float y, float z ); + public void glShadeModel (int mode); - public void glScalex ( int x, int y, int z ); + public void glTexCoordPointer (int size, int type, int stride, Buffer pointer); - public void glShadeModel ( int mode ); + public void glTexEnvf (int target, int pname, float param); - public void glTexCoordPointer ( int size, int type, int stride, Buffer pointer ); + public void glTexEnvfv (int target, int pname, float[] params, int offset); - public void glTexEnvf ( int target, int pname, float param ); + public void glTexEnvfv (int target, int pname, FloatBuffer params); - public void glTexEnvfv ( int target, int pname, float[] params, int offset ); - - public void glTexEnvfv ( int target, int pname, FloatBuffer params ); + public void glTexEnvx (int target, int pname, int param); - public void glTexEnvx ( int target, int pname, int param ); + public void glTexEnvxv (int target, int pname, int[] params, int offset); - public void glTexEnvxv ( int target, int pname, int[] params, int offset ); - - public void glTexEnvxv ( int target, int pname, IntBuffer params ); + public void glTexEnvxv (int target, int pname, IntBuffer params); - public void glTexParameterx ( int target, int pname, int param ); + public void glTexParameterx (int target, int pname, int param); - public void glTranslatef ( float x, float y, float z ); + public void glTranslatef (float x, float y, float z); - public void glTranslatex ( int x, int y, int z ); + public void glTranslatex (int x, int y, int z); - public void glVertexPointer ( int size, int type, int stride, Buffer pointer ); + public void glVertexPointer (int size, int type, int stride, Buffer pointer); - public void glPolygonMode( int face, int mode ); + public void glPolygonMode (int face, int mode); } diff --git a/gdx/src/com/badlogic/gdx/graphics/GL11.java b/gdx/src/com/badlogic/gdx/graphics/GL11.java index 500659f57..1f9144d9c 100644 --- a/gdx/src/com/badlogic/gdx/graphics/GL11.java +++ b/gdx/src/com/badlogic/gdx/graphics/GL11.java @@ -1,31 +1,28 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics; + import java.nio.Buffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; /** - * Interface wrapping all OpenGL ES 1.1 methods. This interface inherits - * all the methods from {@link GL10}. + * Interface wrapping all OpenGL ES 1.1 methods. This interface inherits all the methods from {@link GL10}. * @author mzechner - * + * */ -public interface GL11 extends GL10 -{ +public interface GL11 extends GL10 { public static final int GL_OES_VERSION_1_0 = 1; public static final int GL_MAX_ELEMENTS_VERTICES = 0x80E8; public static final int GL_MAX_ELEMENTS_INDICES = 0x80E9; @@ -154,140 +151,140 @@ public interface GL11 extends GL10 public static final int GL_OES_point_size_array = 1; public static final int GL_OES_point_sprite = 1; - public void glClipPlanef( int plane, float[] equation, int offset ); - - public void glClipPlanef ( int plane, FloatBuffer equation ); + public void glClipPlanef (int plane, float[] equation, int offset); + + public void glClipPlanef (int plane, FloatBuffer equation); + + public void glGetClipPlanef (int pname, float[] eqn, int offset); + + public void glGetClipPlanef (int pname, FloatBuffer eqn); + + public void glGetFloatv (int pname, float[] params, int offset); + + public void glGetFloatv (int pname, FloatBuffer params); + + public void glGetLightfv (int light, int pname, float[] params, int offset); + + public void glGetLightfv (int light, int pname, FloatBuffer params); + + public void glGetMaterialfv (int face, int pname, float[] params, int offset); + + public void glGetMaterialfv (int face, int pname, FloatBuffer params); + + public void glGetTexParameterfv (int target, int pname, float[] params, int offset); + + public void glGetTexParameterfv (int target, int pname, FloatBuffer params); + + public void glPointParameterf (int pname, float param); + + public void glPointParameterfv (int pname, float[] params, int offset); + + public void glPointParameterfv (int pname, FloatBuffer params); + + public void glTexParameterfv (int target, int pname, float[] params, int offset); + + public void glTexParameterfv (int target, int pname, FloatBuffer params); + + public void glBindBuffer (int target, int buffer); + + public void glBufferData (int target, int size, Buffer data, int usage); + + public void glBufferSubData (int target, int offset, int size, Buffer data); + + public void glClipPlanex (int plane, int[] equation, int offset); + + public void glClipPlanex (int plane, IntBuffer equation); + + public void glColor4ub (byte red, byte green, byte blue, byte alpha); + + public void glDeleteBuffers (int n, int[] buffers, int offset); + + public void glDeleteBuffers (int n, IntBuffer buffers); + + public void glGetBooleanv (int pname, boolean[] params, int offset); + + public void glGetBooleanv (int pname, IntBuffer params); + + public void glGetBufferParameteriv (int target, int pname, int[] params, int offset); + + public void glGetBufferParameteriv (int target, int pname, IntBuffer params); + + public void glGetClipPlanex (int pname, int[] eqn, int offset); + + public void glGetClipPlanex (int pname, IntBuffer eqn); + + public void glGenBuffers (int n, int[] buffers, int offset); + + public void glGenBuffers (int n, IntBuffer buffers); + + public void glGetFixedv (int pname, int[] params, int offset); - public void glGetClipPlanef( int pname, float[] eqn, int offset ); - - public void glGetClipPlanef ( int pname, FloatBuffer eqn ); + public void glGetFixedv (int pname, IntBuffer params); - public void glGetFloatv( int pname, float[] params, int offset ); - - public void glGetFloatv ( int pname, FloatBuffer params ); + public void glGetLightxv (int light, int pname, int[] params, int offset); - public void glGetLightfv ( int light, int pname, float[] params, int offset ); - - public void glGetLightfv ( int light, int pname, FloatBuffer params ); - - public void glGetMaterialfv ( int face, int pname, float[] params, int offset ); - - public void glGetMaterialfv ( int face, int pname, FloatBuffer params ); + public void glGetLightxv (int light, int pname, IntBuffer params); - public void glGetTexParameterfv ( int target, int pname, float[] params, int offset ); - - public void glGetTexParameterfv ( int target, int pname, FloatBuffer params ); + public void glGetMaterialxv (int face, int pname, int[] params, int offset); - public void glPointParameterf ( int pname, float param ); + public void glGetMaterialxv (int face, int pname, IntBuffer params); - public void glPointParameterfv ( int pname, float[] params, int offset ); - - public void glPointParameterfv ( int pname, FloatBuffer params ); + public void glGetPointerv (int pname, Buffer[] params); - public void glTexParameterfv ( int target, int pname, float[] params, int offset ); - - public void glTexParameterfv ( int target, int pname, FloatBuffer params ); + public void glGetTexEnviv (int env, int pname, int[] params, int offset); - public void glBindBuffer ( int target, int buffer ); + public void glGetTexEnviv (int env, int pname, IntBuffer params); - public void glBufferData ( int target, int size, Buffer data, int usage ); + public void glGetTexEnvxv (int env, int pname, int[] params, int offset); - public void glBufferSubData ( int target, int offset, int size, Buffer data ); + public void glGetTexEnvxv (int env, int pname, IntBuffer params); - public void glClipPlanex ( int plane, int[] equation, int offset ); - - public void glClipPlanex ( int plane, IntBuffer equation ); + public void glGetTexParameteriv (int target, int pname, int[] params, int offset); - public void glColor4ub ( byte red, byte green, byte blue, byte alpha ); + public void glGetTexParameteriv (int target, int pname, IntBuffer params); - public void glDeleteBuffers ( int n, int[] buffers, int offset ); - - public void glDeleteBuffers ( int n, IntBuffer buffers ); + public void glGetTexParameterxv (int target, int pname, int[] params, int offset); - public void glGetBooleanv ( int pname, boolean[] params, int offset ); - - public void glGetBooleanv ( int pname, IntBuffer params ); + public void glGetTexParameterxv (int target, int pname, IntBuffer params); - public void glGetBufferParameteriv ( int target, int pname, int[] params, int offset ); - - public void glGetBufferParameteriv ( int target, int pname, IntBuffer params ); - - public void glGetClipPlanex ( int pname, int[] eqn, int offset ); - - public void glGetClipPlanex ( int pname, IntBuffer eqn ); + public boolean glIsBuffer (int buffer); - public void glGenBuffers ( int n, int[] buffers, int offset ); - - public void glGenBuffers ( int n, IntBuffer buffers ); + public boolean glIsEnabled (int cap); - public void glGetFixedv ( int pname, int[] params, int offset ); - - public void glGetFixedv ( int pname, IntBuffer params ); + public boolean glIsTexture (int texture); - public void glGetLightxv ( int light, int pname, int[] params, int offset ); - - public void glGetLightxv ( int light, int pname, IntBuffer params ); + public void glPointParameterx (int pname, int param); - public void glGetMaterialxv ( int face, int pname, int[] params, int offset ); - - public void glGetMaterialxv ( int face, int pname, IntBuffer params ); + public void glPointParameterxv (int pname, int[] params, int offset); - public void glGetPointerv ( int pname, Buffer[] params ); + public void glPointParameterxv (int pname, IntBuffer params); - public void glGetTexEnviv ( int env, int pname, int[] params, int offset ); - - public void glGetTexEnviv ( int env, int pname, IntBuffer params ); + public void glTexEnvi (int target, int pname, int param); - public void glGetTexEnvxv ( int env, int pname, int[] params, int offset ); - - public void glGetTexEnvxv ( int env, int pname, IntBuffer params ); + public void glTexEnviv (int target, int pname, int[] params, int offset); - public void glGetTexParameteriv ( int target, int pname, int[] params, int offset ); - - public void glGetTexParameteriv ( int target, int pname, IntBuffer params ); + public void glTexEnviv (int target, int pname, IntBuffer params); - public void glGetTexParameterxv ( int target, int pname, int[] params, int offset ); - - public void glGetTexParameterxv ( int target, int pname, IntBuffer params ); + public void glTexParameteri (int target, int pname, int param); - public boolean glIsBuffer ( int buffer ); + public void glTexParameteriv (int target, int pname, int[] params, int offset); - public boolean glIsEnabled ( int cap ); + public void glTexParameteriv (int target, int pname, IntBuffer params); - public boolean glIsTexture ( int texture ); + public void glTexParameterxv (int target, int pname, int[] params, int offset); - public void glPointParameterx ( int pname, int param ); + public void glTexParameterxv (int target, int pname, IntBuffer params); - public void glPointParameterxv ( int pname, int[] params, int offset ); - - public void glPointParameterxv ( int pname, IntBuffer params ); + public void glPointSizePointerOES (int type, int stride, Buffer pointer); - public void glTexEnvi ( int target, int pname, int param ); - - public void glTexEnviv ( int target, int pname, int[] params, int offset ); - - public void glTexEnviv ( int target, int pname, IntBuffer params ); + public void glVertexPointer (int size, int type, int stride, int pointer); - public void glTexParameteri ( int target, int pname, int param ); + public void glColorPointer (int size, int type, int stride, int pointer); - public void glTexParameteriv ( int target, int pname, int[] params, int offset ); - - public void glTexParameteriv ( int target, int pname, IntBuffer params ); + public void glNormalPointer (int type, int stride, int pointer); - public void glTexParameterxv ( int target, int pname, int[] params, int offset ); - - public void glTexParameterxv ( int target, int pname, IntBuffer params ); + public void glTexCoordPointer (int size, int type, int stride, int pointer); - public void glPointSizePointerOES ( int type, int stride, Buffer pointer ); - - public void glVertexPointer( int size, int type, int stride, int pointer ); - - public void glColorPointer( int size, int type, int stride, int pointer ); - - public void glNormalPointer( int type, int stride, int pointer ); - - public void glTexCoordPointer( int size, int type, int stride, int pointer ); - - public void glDrawElements( int mode, int count, int type, int indices ); + public void glDrawElements (int mode, int count, int type, int indices); } diff --git a/gdx/src/com/badlogic/gdx/graphics/GL20.java b/gdx/src/com/badlogic/gdx/graphics/GL20.java index 48db2059a..c18b1fdaf 100644 --- a/gdx/src/com/badlogic/gdx/graphics/GL20.java +++ b/gdx/src/com/badlogic/gdx/graphics/GL20.java @@ -1,19 +1,18 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics; + import java.nio.Buffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; @@ -21,10 +20,9 @@ import java.nio.IntBuffer; /** * Interface wrapping all the methods of OpenGL ES 2.0 * @author mzechner - * + * */ -public interface GL20 extends GLCommon -{ +public interface GL20 extends GLCommon { public static final int GL_ES_VERSION_2_0 = 1; public static final int GL_DEPTH_BUFFER_BIT = 0x00000100; public static final int GL_STENCIL_BUFFER_BIT = 0x00000400; @@ -329,214 +327,214 @@ public interface GL20 extends GLCommon public static final int GL_MAX_RENDERBUFFER_SIZE = 0x84E8; public static final int GL_INVALID_FRAMEBUFFER_OPERATION = 0x0506; - public void glAttachShader ( int program, int shader ); + public void glAttachShader (int program, int shader); - public void glBindAttribLocation ( int program, int index, String name ); + public void glBindAttribLocation (int program, int index, String name); - public void glBindBuffer ( int target, int buffer ); + public void glBindBuffer (int target, int buffer); - public void glBindFramebuffer ( int target, int framebuffer ); + public void glBindFramebuffer (int target, int framebuffer); - public void glBindRenderbuffer ( int target, int renderbuffer ); + public void glBindRenderbuffer (int target, int renderbuffer); - public void glBlendColor ( float red, float green, float blue, float alpha ); + public void glBlendColor (float red, float green, float blue, float alpha); - public void glBlendEquation ( int mode ); + public void glBlendEquation (int mode); - public void glBlendEquationSeparate ( int modeRGB, int modeAlpha ); + public void glBlendEquationSeparate (int modeRGB, int modeAlpha); - public void glBlendFuncSeparate ( int srcRGB, int dstRGB, int srcAlpha, int dstAlpha ); + public void glBlendFuncSeparate (int srcRGB, int dstRGB, int srcAlpha, int dstAlpha); - public void glBufferData ( int target, int size, Buffer data, int usage ); + public void glBufferData (int target, int size, Buffer data, int usage); - public void glBufferSubData ( int target, int offset, int size, Buffer data ); + public void glBufferSubData (int target, int offset, int size, Buffer data); - public int glCheckFramebufferStatus ( int target ); + public int glCheckFramebufferStatus (int target); - public void glCompileShader ( int shader ); + public void glCompileShader (int shader); - public int glCreateProgram ( ); + public int glCreateProgram (); - public int glCreateShader ( int type ); + public int glCreateShader (int type); - public void glDeleteBuffers ( int n, IntBuffer buffers ); + public void glDeleteBuffers (int n, IntBuffer buffers); - public void glDeleteFramebuffers ( int n, IntBuffer framebuffers ); + public void glDeleteFramebuffers (int n, IntBuffer framebuffers); - public void glDeleteProgram ( int program ); + public void glDeleteProgram (int program); - public void glDeleteRenderbuffers ( int n, IntBuffer renderbuffers ); + public void glDeleteRenderbuffers (int n, IntBuffer renderbuffers); - public void glDeleteShader ( int shader ); + public void glDeleteShader (int shader); - public void glDetachShader ( int program, int shader ); + public void glDetachShader (int program, int shader); - public void glDisableVertexAttribArray ( int index ); - - public void glDrawElements ( int mode, int count, int type, int indices ); + public void glDisableVertexAttribArray (int index); - public void glEnableVertexAttribArray ( int index ); + public void glDrawElements (int mode, int count, int type, int indices); - public void glFramebufferRenderbuffer ( int target, int attachment, int renderbuffertarget, int renderbuffer ); + public void glEnableVertexAttribArray (int index); - public void glFramebufferTexture2D ( int target, int attachment, int textarget, int texture, int level ); + public void glFramebufferRenderbuffer (int target, int attachment, int renderbuffertarget, int renderbuffer); - public void glGenBuffers ( int n, IntBuffer buffers ); + public void glFramebufferTexture2D (int target, int attachment, int textarget, int texture, int level); - public void glGenerateMipmap ( int target ); + public void glGenBuffers (int n, IntBuffer buffers); - public void glGenFramebuffers ( int n, IntBuffer framebuffers ); + public void glGenerateMipmap (int target); - public void glGenRenderbuffers ( int n, IntBuffer renderbuffers ); + public void glGenFramebuffers (int n, IntBuffer framebuffers); + + public void glGenRenderbuffers (int n, IntBuffer renderbuffers); // deviates - public String glGetActiveAttrib ( int program, int index, IntBuffer size, Buffer type ); + public String glGetActiveAttrib (int program, int index, IntBuffer size, Buffer type); // deviates - public String glGetActiveUniform ( int program, int index, IntBuffer size, Buffer type ); + public String glGetActiveUniform (int program, int index, IntBuffer size, Buffer type); - public void glGetAttachedShaders ( int program, int maxcount, Buffer count, IntBuffer shaders ); + public void glGetAttachedShaders (int program, int maxcount, Buffer count, IntBuffer shaders); - public int glGetAttribLocation ( int program, String name ); + public int glGetAttribLocation (int program, String name); - public void glGetBooleanv ( int pname, Buffer params ); + public void glGetBooleanv (int pname, Buffer params); - public void glGetBufferParameteriv ( int target, int pname, IntBuffer params ); + public void glGetBufferParameteriv (int target, int pname, IntBuffer params); - public void glGetFloatv ( int pname, FloatBuffer params ); + public void glGetFloatv (int pname, FloatBuffer params); - public void glGetFramebufferAttachmentParameteriv ( int target, int attachment, int pname, IntBuffer params ); + public void glGetFramebufferAttachmentParameteriv (int target, int attachment, int pname, IntBuffer params); - public void glGetProgramiv ( int program, int pname, IntBuffer params ); + public void glGetProgramiv (int program, int pname, IntBuffer params); // deviates - public String glGetProgramInfoLog ( int program ); + public String glGetProgramInfoLog (int program); - public void glGetRenderbufferParameteriv ( int target, int pname, IntBuffer params ); + public void glGetRenderbufferParameteriv (int target, int pname, IntBuffer params); - public void glGetShaderiv ( int shader, int pname, IntBuffer params ); + public void glGetShaderiv (int shader, int pname, IntBuffer params); // deviates - public String glGetShaderInfoLog ( int shader ); + public String glGetShaderInfoLog (int shader); - public void glGetShaderPrecisionFormat ( int shadertype, int precisiontype, IntBuffer range, IntBuffer precision ); + public void glGetShaderPrecisionFormat (int shadertype, int precisiontype, IntBuffer range, IntBuffer precision); - public void glGetShaderSource ( int shader, int bufsize, Buffer length, String source ); + public void glGetShaderSource (int shader, int bufsize, Buffer length, String source); - public void glGetTexParameterfv ( int target, int pname, FloatBuffer params ); + public void glGetTexParameterfv (int target, int pname, FloatBuffer params); - public void glGetTexParameteriv ( int target, int pname, IntBuffer params ); + public void glGetTexParameteriv (int target, int pname, IntBuffer params); - public void glGetUniformfv ( int program, int location, FloatBuffer params ); + public void glGetUniformfv (int program, int location, FloatBuffer params); - public void glGetUniformiv ( int program, int location, IntBuffer params ); + public void glGetUniformiv (int program, int location, IntBuffer params); - public int glGetUniformLocation ( int program, String name ); + public int glGetUniformLocation (int program, String name); - public void glGetVertexAttribfv ( int index, int pname, FloatBuffer params ); + public void glGetVertexAttribfv (int index, int pname, FloatBuffer params); - public void glGetVertexAttribiv ( int index, int pname, IntBuffer params ); + public void glGetVertexAttribiv (int index, int pname, IntBuffer params); - public void glGetVertexAttribPointerv ( int index, int pname, Buffer pointer ); + public void glGetVertexAttribPointerv (int index, int pname, Buffer pointer); - public boolean glIsBuffer ( int buffer ); + public boolean glIsBuffer (int buffer); - public boolean glIsEnabled ( int cap ); + public boolean glIsEnabled (int cap); - public boolean glIsFramebuffer ( int framebuffer ); + public boolean glIsFramebuffer (int framebuffer); - public boolean glIsProgram ( int program ); + public boolean glIsProgram (int program); - public boolean glIsRenderbuffer ( int renderbuffer ); + public boolean glIsRenderbuffer (int renderbuffer); - public boolean glIsShader ( int shader ); + public boolean glIsShader (int shader); - public boolean glIsTexture ( int texture ); + public boolean glIsTexture (int texture); - public void glLinkProgram ( int program ); + public void glLinkProgram (int program); - public void glReleaseShaderCompiler ( ); + public void glReleaseShaderCompiler (); - public void glRenderbufferStorage ( int target, int internalformat, int width, int height ); + public void glRenderbufferStorage (int target, int internalformat, int width, int height); - public void glSampleCoverage ( float value, boolean invert ); + public void glSampleCoverage (float value, boolean invert); - public void glShaderBinary ( int n, IntBuffer shaders, int binaryformat, Buffer binary, int length ); + public void glShaderBinary (int n, IntBuffer shaders, int binaryformat, Buffer binary, int length); // Deviates - public void glShaderSource ( int shader, String string ); + public void glShaderSource (int shader, String string); + + public void glStencilFuncSeparate (int face, int func, int ref, int mask); - public void glStencilFuncSeparate ( int face, int func, int ref, int mask ); + public void glStencilMaskSeparate (int face, int mask); - public void glStencilMaskSeparate ( int face, int mask ); + public void glStencilOpSeparate (int face, int fail, int zfail, int zpass); - public void glStencilOpSeparate ( int face, int fail, int zfail, int zpass ); + public void glTexParameterfv (int target, int pname, FloatBuffer params); - public void glTexParameterfv ( int target, int pname, FloatBuffer params ); + public void glTexParameteri (int target, int pname, int param); - public void glTexParameteri ( int target, int pname, int param ); + public void glTexParameteriv (int target, int pname, IntBuffer params); - public void glTexParameteriv ( int target, int pname, IntBuffer params ); + public void glUniform1f (int location, float x); - public void glUniform1f ( int location, float x ); + public void glUniform1fv (int location, int count, FloatBuffer v); - public void glUniform1fv ( int location, int count, FloatBuffer v ); + public void glUniform1i (int location, int x); - public void glUniform1i ( int location, int x ); + public void glUniform1iv (int location, int count, IntBuffer v); - public void glUniform1iv ( int location, int count, IntBuffer v ); + public void glUniform2f (int location, float x, float y); - public void glUniform2f ( int location, float x, float y ); + public void glUniform2fv (int location, int count, FloatBuffer v); - public void glUniform2fv ( int location, int count, FloatBuffer v ); + public void glUniform2i (int location, int x, int y); - public void glUniform2i ( int location, int x, int y ); + public void glUniform2iv (int location, int count, IntBuffer v); - public void glUniform2iv ( int location, int count, IntBuffer v ); + public void glUniform3f (int location, float x, float y, float z); - public void glUniform3f ( int location, float x, float y, float z ); + public void glUniform3fv (int location, int count, FloatBuffer v); - public void glUniform3fv ( int location, int count, FloatBuffer v ); + public void glUniform3i (int location, int x, int y, int z); - public void glUniform3i ( int location, int x, int y, int z ); + public void glUniform3iv (int location, int count, IntBuffer v); - public void glUniform3iv ( int location, int count, IntBuffer v ); + public void glUniform4f (int location, float x, float y, float z, float w); - public void glUniform4f ( int location, float x, float y, float z, float w ); + public void glUniform4fv (int location, int count, FloatBuffer v); - public void glUniform4fv ( int location, int count, FloatBuffer v ); + public void glUniform4i (int location, int x, int y, int z, int w); - public void glUniform4i ( int location, int x, int y, int z, int w ); + public void glUniform4iv (int location, int count, IntBuffer v); - public void glUniform4iv ( int location, int count, IntBuffer v ); + public void glUniformMatrix2fv (int location, int count, boolean transpose, FloatBuffer value); - public void glUniformMatrix2fv ( int location, int count, boolean transpose, FloatBuffer value ); + public void glUniformMatrix3fv (int location, int count, boolean transpose, FloatBuffer value); - public void glUniformMatrix3fv ( int location, int count, boolean transpose, FloatBuffer value ); + public void glUniformMatrix4fv (int location, int count, boolean transpose, FloatBuffer value); - public void glUniformMatrix4fv ( int location, int count, boolean transpose, FloatBuffer value ); + public void glUseProgram (int program); - public void glUseProgram ( int program ); + public void glValidateProgram (int program); - public void glValidateProgram ( int program ); + public void glVertexAttrib1f (int indx, float x); - public void glVertexAttrib1f ( int indx, float x ); + public void glVertexAttrib1fv (int indx, FloatBuffer values); - public void glVertexAttrib1fv ( int indx, FloatBuffer values ); + public void glVertexAttrib2f (int indx, float x, float y); - public void glVertexAttrib2f ( int indx, float x, float y ); + public void glVertexAttrib2fv (int indx, FloatBuffer values); - public void glVertexAttrib2fv ( int indx, FloatBuffer values ); + public void glVertexAttrib3f (int indx, float x, float y, float z); - public void glVertexAttrib3f ( int indx, float x, float y, float z ); + public void glVertexAttrib3fv (int indx, FloatBuffer values); - public void glVertexAttrib3fv ( int indx, FloatBuffer values ); + public void glVertexAttrib4f (int indx, float x, float y, float z, float w); - public void glVertexAttrib4f ( int indx, float x, float y, float z, float w ); + public void glVertexAttrib4fv (int indx, FloatBuffer values); - public void glVertexAttrib4fv ( int indx, FloatBuffer values ); + public void glVertexAttribPointer (int indx, int size, int type, boolean normalized, int stride, Buffer ptr); - public void glVertexAttribPointer ( int indx, int size, int type, boolean normalized, int stride, Buffer ptr ); - - public void glVertexAttribPointer ( int indx, int size, int type, boolean normalized, int stride, int ptr ); + public void glVertexAttribPointer (int indx, int size, int type, boolean normalized, int stride, int ptr); } diff --git a/gdx/src/com/badlogic/gdx/graphics/GLCommon.java b/gdx/src/com/badlogic/gdx/graphics/GLCommon.java index 7b360b8bc..8228f900a 100644 --- a/gdx/src/com/badlogic/gdx/graphics/GLCommon.java +++ b/gdx/src/com/badlogic/gdx/graphics/GLCommon.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics; import java.nio.Buffer; @@ -6,89 +7,92 @@ import java.nio.IntBuffer; /** * This interface defines methods common to GL10, GL11 and GL20. * @author mzechner - * + * */ -public interface GLCommon -{ - public void glActiveTexture ( int texture ); +public interface GLCommon { + public void glActiveTexture (int texture); + + public void glBindTexture (int target, int texture); + + public void glBlendFunc (int sfactor, int dfactor); + + public void glClear (int mask); + + public void glClearColor (float red, float green, float blue, float alpha); + + public void glClearDepthf (float depth); + + public void glClearStencil (int s); + + public void glColorMask (boolean red, boolean green, boolean blue, boolean alpha); + + public void glCompressedTexImage2D (int target, int level, int internalformat, int width, int height, int border, + int imageSize, Buffer data); + + public void glCompressedTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, int format, + int imageSize, Buffer data); + + public void glCopyTexImage2D (int target, int level, int internalformat, int x, int y, int width, int height, int border); + + public void glCopyTexSubImage2D (int target, int level, int xoffset, int yoffset, int x, int y, int width, int height); + + public void glCullFace (int mode); - public void glBindTexture ( int target, int texture ); - - public void glBlendFunc ( int sfactor, int dfactor ); + public void glDeleteTextures (int n, IntBuffer textures); - public void glClear ( int mask ); + public void glDepthFunc (int func); - public void glClearColor ( float red, float green, float blue, float alpha ); - - public void glClearDepthf ( float depth ); - - public void glClearStencil ( int s ); + public void glDepthMask (boolean flag); - public void glColorMask ( boolean red, boolean green, boolean blue, boolean alpha ); + public void glDepthRangef (float zNear, float zFar); - public void glCompressedTexImage2D ( int target, int level, int internalformat, int width, int height, int border, int imageSize, Buffer data ); + public void glDisable (int cap); - public void glCompressedTexSubImage2D ( int target, int level, int xoffset, int yoffset, int width, int height, int format, int imageSize, Buffer data ); + public void glDrawArrays (int mode, int first, int count); - public void glCopyTexImage2D ( int target, int level, int internalformat, int x, int y, int width, int height, int border ); + public void glDrawElements (int mode, int count, int type, Buffer indices); - public void glCopyTexSubImage2D ( int target, int level, int xoffset, int yoffset, int x, int y, int width, int height ); - - public void glCullFace ( int mode ); + public void glEnable (int cap); - public void glDeleteTextures ( int n, IntBuffer textures ); + public void glFinish (); - public void glDepthFunc ( int func ); + public void glFlush (); - public void glDepthMask ( boolean flag ); + public void glFrontFace (int mode); - public void glDepthRangef ( float zNear, float zFar ); - - public void glDisable ( int cap ); - - public void glDrawArrays ( int mode, int first, int count ); + public void glGenTextures (int n, IntBuffer textures); - public void glDrawElements ( int mode, int count, int type, Buffer indices ); - - public void glEnable ( int cap ); - - public void glFinish ( ); + public int glGetError (); - public void glFlush ( ); - - public void glFrontFace ( int mode ); + public void glGetIntegerv (int pname, IntBuffer params); - public void glGenTextures ( int n, IntBuffer textures ); + public String glGetString (int name); - public int glGetError ( ); - - public void glGetIntegerv ( int pname, IntBuffer params ); - - public String glGetString ( int name ); - - public void glHint ( int target, int mode ); + public void glHint (int target, int mode); - public void glLineWidth ( float width ); + public void glLineWidth (float width); - public void glPixelStorei ( int pname, int param ); + public void glPixelStorei (int pname, int param); - public void glPolygonOffset ( float factor, float units ); + public void glPolygonOffset (float factor, float units); - public void glReadPixels ( int x, int y, int width, int height, int format, int type, Buffer pixels ); + public void glReadPixels (int x, int y, int width, int height, int format, int type, Buffer pixels); - public void glScissor ( int x, int y, int width, int height ); + public void glScissor (int x, int y, int width, int height); - public void glStencilFunc ( int func, int ref, int mask ); + public void glStencilFunc (int func, int ref, int mask); - public void glStencilMask ( int mask ); + public void glStencilMask (int mask); - public void glStencilOp ( int fail, int zfail, int zpass ); + public void glStencilOp (int fail, int zfail, int zpass); - public void glTexImage2D ( int target, int level, int internalformat, int width, int height, int border, int format, int type, Buffer pixels ); + public void glTexImage2D (int target, int level, int internalformat, int width, int height, int border, int format, int type, + Buffer pixels); - public void glTexParameterf ( int target, int pname, float param ); + public void glTexParameterf (int target, int pname, float param); - public void glTexSubImage2D ( int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, Buffer pixels ); + public void glTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, + Buffer pixels); - public void glViewport ( int x, int y, int width, int height ); + public void glViewport (int x, int y, int width, int height); } diff --git a/gdx/src/com/badlogic/gdx/graphics/ImmediateModeRenderer.java b/gdx/src/com/badlogic/gdx/graphics/ImmediateModeRenderer.java index bc8f8c8d0..99327bec6 100644 --- a/gdx/src/com/badlogic/gdx/graphics/ImmediateModeRenderer.java +++ b/gdx/src/com/badlogic/gdx/graphics/ImmediateModeRenderer.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics; import java.nio.ByteBuffer; @@ -23,104 +21,94 @@ import com.badlogic.gdx.Gdx; import com.badlogic.gdx.GdxRuntimeException; /** - * An ImmediateModeRenderer allows you to perform immediate mode rendering as you - * were accustomed to in your desktop OpenGL environment. In order to draw something - * you first have to call {@link ImmediateModeRenderer.begin()} with the primitive - * type you want to render. Next you specify as many vertices as you want by first - * defining the vertex color, normal and texture coordinates followed by the vertex - * position which finalizes the definition of a single vertex. When you are done - * specifying the geometry you have to call {@link ImmediateModeRenderer.end()} to - * make the renderer render the geometry. Internally the renderer uses vertex arrays - * to render the provided geometry. This is not the best performing way to do this - * so use this class only for non performance critical low vertex count geometries while - * debugging. + * An ImmediateModeRenderer allows you to perform immediate mode rendering as you were accustomed to in your desktop OpenGL + * environment. In order to draw something you first have to call {@link ImmediateModeRenderer.begin()} with the primitive type + * you want to render. Next you specify as many vertices as you want by first defining the vertex color, normal and texture + * coordinates followed by the vertex position which finalizes the definition of a single vertex. When you are done specifying the + * geometry you have to call {@link ImmediateModeRenderer.end()} to make the renderer render the geometry. Internally the renderer + * uses vertex arrays to render the provided geometry. This is not the best performing way to do this so use this class only for + * non performance critical low vertex count geometries while debugging. * * Note that this class of course only works with OpenGL ES 1.x. * * @author mzechner - * + * */ -public class ImmediateModeRenderer -{ +public class ImmediateModeRenderer { private static final int MAX_VERTICES = 2000 * 3; - + /** the primitive type **/ private int primitiveType; - + /** the vertex position array and buffer **/ private float[] positions; private FloatBuffer positionsBuffer; - + /** the vertex color array and buffer **/ private float[] colors; private FloatBuffer colorsBuffer; - + /** the vertex normal array and buffer **/ private float[] normals; private FloatBuffer normalsBuffer; - + /** the texture coordinate array and buffer **/ private float[] texCoords; - private FloatBuffer texCoordsBuffer; - + private FloatBuffer texCoordsBuffer; + /** the current vertex attribute indices **/ private int idxPos = 0; private int idxCols = 0; private int idxNors = 0; private int idxTexCoords = 0; - + /** which attributes have been defined **/ private boolean colorsDefined = false; private boolean normalsDefined = false; private boolean texCoordsDefined = false; - + /** * Constructs a new ImmediateModeRenderer * @param gl */ - public ImmediateModeRenderer( ) - { - if( Gdx.graphics.isGL20Available() ) - throw new GdxRuntimeException( "ImmediateModeRenderer can only be used with OpenGL ES 1.0/1.1" ); - - this.positions = new float[3*MAX_VERTICES]; - this.positionsBuffer = allocateBuffer( 3 * MAX_VERTICES ); + public ImmediateModeRenderer () { + if (Gdx.graphics.isGL20Available()) + throw new GdxRuntimeException("ImmediateModeRenderer can only be used with OpenGL ES 1.0/1.1"); + + this.positions = new float[3 * MAX_VERTICES]; + this.positionsBuffer = allocateBuffer(3 * MAX_VERTICES); this.colors = new float[4 * MAX_VERTICES]; - this.colorsBuffer = allocateBuffer( 4 * MAX_VERTICES ); - this.normals = new float[3*MAX_VERTICES]; - this.normalsBuffer = allocateBuffer( 3 * MAX_VERTICES ); + this.colorsBuffer = allocateBuffer(4 * MAX_VERTICES); + this.normals = new float[3 * MAX_VERTICES]; + this.normalsBuffer = allocateBuffer(3 * MAX_VERTICES); this.texCoords = new float[2 * MAX_VERTICES]; - this.texCoordsBuffer = allocateBuffer( 2 * MAX_VERTICES ); + this.texCoordsBuffer = allocateBuffer(2 * MAX_VERTICES); } - - private FloatBuffer allocateBuffer( int numFloats ) - { - ByteBuffer buffer = ByteBuffer.allocateDirect( numFloats * 4 ); + + private FloatBuffer allocateBuffer (int numFloats) { + ByteBuffer buffer = ByteBuffer.allocateDirect(numFloats * 4); buffer.order(ByteOrder.nativeOrder()); return buffer.asFloatBuffer(); } - + /** - * Starts a new list of primitives. The primitiveType - * specifies which primitives to draw. Can be any of - * GL10.GL_TRIANGLES, GL10.GL_LINES and so on. A maximum - * of 6000 vertices can be drawn at once. + * Starts a new list of primitives. The primitiveType specifies which primitives to draw. Can be any of GL10.GL_TRIANGLES, + * GL10.GL_LINES and so on. A maximum of 6000 vertices can be drawn at once. * * @param primitiveType the primitive type. */ - public void begin( int primitiveType ) - { - this.primitiveType = primitiveType; + public void begin (int primitiveType) { + this.primitiveType = primitiveType; idxPos = 0; idxCols = 0; idxNors = 0; idxTexCoords = 0; - + colorsDefined = false; normalsDefined = false; texCoordsDefined = false; } - + /** * Specifies the color of the current vertex * @param r the red component @@ -128,111 +116,98 @@ public class ImmediateModeRenderer * @param b the blue component * @param a the alpha component */ - public void color( float r, float g, float b, float a ) - { + public void color (float r, float g, float b, float a) { colors[idxCols] = r; - colors[idxCols+1] = g; - colors[idxCols+2] = b; - colors[idxCols+3] = a; + colors[idxCols + 1] = g; + colors[idxCols + 2] = b; + colors[idxCols + 3] = a; colorsDefined = true; } - + /** * Specifies the normal of the current vertex * @param x the x component * @param y the y component * @param z the z component */ - public void normal( float x, float y, float z ) - { + public void normal (float x, float y, float z) { normals[idxNors] = x; - normals[idxNors+1] = y; - normals[idxNors+2] = z; + normals[idxNors + 1] = y; + normals[idxNors + 2] = z; normalsDefined = true; } - + /** * Specifies the texture coordinates of the current vertex * @param u the u coordinate * @param v the v coordinate */ - public void texCoord( float u, float v ) - { + public void texCoord (float u, float v) { texCoords[idxTexCoords] = u; - texCoords[idxTexCoords+1] = v; + texCoords[idxTexCoords + 1] = v; texCoordsDefined = true; } - + /** - * Specifies the position of the current vertex and - * finalizes it. After a call to this method you will - * effectively define a new vertex afterwards. + * Specifies the position of the current vertex and finalizes it. After a call to this method you will effectively define a new + * vertex afterwards. * * @param x the x component * @param y the y component * @param z the z component */ - public void vertex( float x, float y, float z ) - { + public void vertex (float x, float y, float z) { positions[idxPos++] = x; positions[idxPos++] = y; positions[idxPos++] = z; - + idxCols += 4; idxNors += 3; - idxTexCoords += 2; + idxTexCoords += 2; } - + /** * Renders the primitives just defined. */ - public void end( ) - { - if( idxPos == 0 ) - return; - + public void end () { + if (idxPos == 0) return; + GL10 gl = Gdx.graphics.getGL10(); - gl.glEnableClientState( GL10.GL_VERTEX_ARRAY ); + gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); positionsBuffer.clear(); - positionsBuffer.put( positions, 0, idxPos ); + positionsBuffer.put(positions, 0, idxPos); positionsBuffer.flip(); - gl.glVertexPointer( 3, GL10.GL_FLOAT, 0, positionsBuffer ); - - if( colorsDefined ) - { - gl.glEnableClientState( GL10.GL_COLOR_ARRAY ); + gl.glVertexPointer(3, GL10.GL_FLOAT, 0, positionsBuffer); + + if (colorsDefined) { + gl.glEnableClientState(GL10.GL_COLOR_ARRAY); colorsBuffer.clear(); - colorsBuffer.put( colors, 0, idxCols ); + colorsBuffer.put(colors, 0, idxCols); colorsBuffer.flip(); - gl.glColorPointer( 4, GL10.GL_FLOAT, 0, colorsBuffer ); + gl.glColorPointer(4, GL10.GL_FLOAT, 0, colorsBuffer); } - - if( normalsDefined ) - { - gl.glEnableClientState( GL10.GL_NORMAL_ARRAY ); + + if (normalsDefined) { + gl.glEnableClientState(GL10.GL_NORMAL_ARRAY); normalsBuffer.clear(); - normalsBuffer.put( normals, 0, idxNors ); + normalsBuffer.put(normals, 0, idxNors); normalsBuffer.flip(); - gl.glNormalPointer( GL10.GL_FLOAT, 0, normalsBuffer ); + gl.glNormalPointer(GL10.GL_FLOAT, 0, normalsBuffer); } - - if( texCoordsDefined ) - { - gl.glClientActiveTexture( GL10.GL_TEXTURE0 ); - gl.glEnableClientState( GL10.GL_TEXTURE_COORD_ARRAY ); + + if (texCoordsDefined) { + gl.glClientActiveTexture(GL10.GL_TEXTURE0); + gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); texCoordsBuffer.clear(); - texCoordsBuffer.put( texCoords, 0, idxTexCoords ); + texCoordsBuffer.put(texCoords, 0, idxTexCoords); texCoordsBuffer.flip(); - gl.glTexCoordPointer( 2, GL10.GL_FLOAT, 0, texCoordsBuffer ); + gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, texCoordsBuffer); } - - gl.glDrawArrays( primitiveType, 0, idxPos / 3 ); - - if( colorsDefined ) - gl.glDisableClientState( GL10.GL_COLOR_ARRAY ); - if( normalsDefined ) - gl.glDisableClientState( GL10.GL_NORMAL_ARRAY ); - if( texCoordsDefined ) - gl.glDisableClientState( GL10.GL_TEXTURE_COORD_ARRAY ); + + gl.glDrawArrays(primitiveType, 0, idxPos / 3); + + if (colorsDefined) gl.glDisableClientState(GL10.GL_COLOR_ARRAY); + if (normalsDefined) gl.glDisableClientState(GL10.GL_NORMAL_ARRAY); + if (texCoordsDefined) gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); } } diff --git a/gdx/src/com/badlogic/gdx/graphics/Mesh.java b/gdx/src/com/badlogic/gdx/graphics/Mesh.java index 14a211772..96755820d 100644 --- a/gdx/src/com/badlogic/gdx/graphics/Mesh.java +++ b/gdx/src/com/badlogic/gdx/graphics/Mesh.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics; import java.nio.Buffer; @@ -16,94 +17,88 @@ import com.badlogic.gdx.utils.BufferUtils; /** *

- * A Mesh holds vertices composed of attributes specified by a - * {@link VertexAttributes} instance. The vertices are held either - * in VRAM in form of vertex buffer objects or in RAM in form of - * vertex arrays. The former variant is more performant and is prefered + * A Mesh holds vertices composed of attributes specified by a {@link VertexAttributes} instance. The vertices are held either in + * VRAM in form of vertex buffer objects or in RAM in form of vertex arrays. The former variant is more performant and is prefered * over vertex arrays if hardware supports it. *

* - *

Meshes are automatically managed. If the OpenGL context is lost all vertex buffer - * objects get invalidated and must be reloaded when the context is recreated. This - * only happens on Android when a user switches to another application or receives - * an incoming call. A managed Mesh will be reloaded automagically so you don't have - * to do this manually. + *

+ * Meshes are automatically managed. If the OpenGL context is lost all vertex buffer objects get invalidated and must be reloaded + * when the context is recreated. This only happens on Android when a user switches to another application or receives an incoming + * call. A managed Mesh will be reloaded automagically so you don't have to do this manually. *

* *

- * A Mesh consists of vertices and optionally indices which specify which vertices - * define a triangle. Each vertex is composed of attributes such as position, normal, - * color or texture coordinate. Note that not all of this attributes must be given, except - * for position which is non-optional. Each attribute has an alias which is used when - * rendering a Mesh in OpenGL ES 2.0. The alias is used to bind a specific vertex attribute - * to a shader attribute. The shader source and the alias of the attribute must match exactly - * for this to work. For OpenGL ES 1.x rendering this aliases are irrelevant. + * A Mesh consists of vertices and optionally indices which specify which vertices define a triangle. Each vertex is composed of + * attributes such as position, normal, color or texture coordinate. Note that not all of this attributes must be given, except + * for position which is non-optional. Each attribute has an alias which is used when rendering a Mesh in OpenGL ES 2.0. The alias + * is used to bind a specific vertex attribute to a shader attribute. The shader source and the alias of the attribute must match + * exactly for this to work. For OpenGL ES 1.x rendering this aliases are irrelevant. *

* *

* Meshes can be used with either OpenGL ES 1.x or OpenGL ES 2.0. - *

+ *

* * @author mzechner - * + * * */ -public class Mesh -{ +public class Mesh { /** list of all meshes **/ - private static final ArrayList meshes = new ArrayList( ); - + private static final ArrayList meshes = new ArrayList(); + /** the vertex attributes **/ private final VertexAttributes attributes; - + /** the maximum number of vertices **/ private final int maxVertices; - + /** the maximum number of indices **/ private final int maxIndices; - + /** the direct byte buffer that holds the vertices **/ private final Buffer vertices; - + /** a view of the vertices buffer for manipulating floats **/ private final FloatBuffer verticesFloat; - + /** a view of the vertices buffer for manipulating fixed point values **/ private final IntBuffer verticesFixed; - + /** the direct short buffer that holds the indices **/ private final ShortBuffer indices; - + /** the VBO handle **/ private int vertexBufferObjectHandle; - + /** the IBO handle **/ private int indexBufferObjectHandle; - + /** dirty flag **/ private boolean dirty = false; - + /** managed? **/ private final boolean managed; - + /** static? **/ private final boolean isStatic; - + /** fixed point? **/ - private final boolean useFixedPoint; - + private final boolean useFixedPoint; + /** whether this mesh was invalidated due to a context loss **/ private boolean invalidated = false; - - /** whether attempted to create buffer the first time**/ + + /** whether attempted to create buffer the first time **/ private boolean bufferCreatedFirstTime = false; - + /** whether we use direct buffers or not **/ private final boolean isDirect; - + /** whether VBOs are used or not **/ private final boolean useVBO; - + /** * Creates a new Mesh with the given attributes. * @@ -111,366 +106,324 @@ public class Mesh * @param useFixedPoint whether to use fixed point or floats * @param maxVertices the maximum number of vertices this mesh can hold * @param maxIndices the maximum number of indices this mesh can hold - * @param attributes the {@link VertexAttribute}s. Each vertex attribute defines one property of a vertex such as position, normal or texture coordinate + * @param attributes the {@link VertexAttribute}s. Each vertex attribute defines one property of a vertex such as position, + * normal or texture coordinate */ - public Mesh( boolean isStatic, boolean useFixedPoint, int maxVertices, int maxIndices, VertexAttribute ... attributes ) - { + public Mesh (boolean isStatic, boolean useFixedPoint, int maxVertices, int maxIndices, VertexAttribute... attributes) { this.managed = true; this.isStatic = isStatic; this.useFixedPoint = useFixedPoint; this.maxVertices = maxVertices; this.maxIndices = maxIndices; - this.attributes = new VertexAttributes( attributes ); - - if( Gdx.app.getType() != Application.ApplicationType.Android ) - { + this.attributes = new VertexAttributes(attributes); + + if (Gdx.app.getType() != Application.ApplicationType.Android) { useVBO = Gdx.graphics.isGL11Available() == true || Gdx.graphics.isGL20Available() == true; isDirect = true; - } - else - { + } else { useVBO = Gdx.graphics.isGL11Available() == true || Gdx.graphics.isGL20Available() == true; - if( useVBO ) - { - if( Gdx.app.getVersion() < 5 ) + if (useVBO) { + if (Gdx.app.getVersion() < 5) isDirect = false; else isDirect = true; - } - else + } else isDirect = true; } - - if( isDirect ) - { - ByteBuffer buffer = ByteBuffer.allocateDirect( maxVertices * this.attributes.vertexSize ); + + if (isDirect) { + ByteBuffer buffer = ByteBuffer.allocateDirect(maxVertices * this.attributes.vertexSize); buffer.order(ByteOrder.nativeOrder()); vertices = buffer; verticesFixed = buffer.asIntBuffer(); verticesFloat = buffer.asFloatBuffer(); - buffer = ByteBuffer.allocateDirect( maxIndices * 2 ); - buffer.order( ByteOrder.nativeOrder() ); + buffer = ByteBuffer.allocateDirect(maxIndices * 2); + buffer.order(ByteOrder.nativeOrder()); indices = buffer.asShortBuffer(); - } - else - { - - if( useFixedPoint ) - { - verticesFixed = IntBuffer.allocate( maxVertices * this.attributes.vertexSize / 4 ); + } else { + + if (useFixedPoint) { + verticesFixed = IntBuffer.allocate(maxVertices * this.attributes.vertexSize / 4); verticesFloat = null; vertices = verticesFixed; - } - else - { - verticesFloat = FloatBuffer.allocate( maxVertices * this.attributes.vertexSize / 4 ); + } else { + verticesFloat = FloatBuffer.allocate(maxVertices * this.attributes.vertexSize / 4); verticesFixed = null; vertices = verticesFloat; } - indices = ShortBuffer.allocate( maxIndices ); + indices = ShortBuffer.allocate(maxIndices); } - + bufferCreatedFirstTime = false; - if( managed ) - meshes.add( this ); + if (managed) meshes.add(this); } - - private void createBuffers( ) - { + + private void createBuffers () { // FIXME this is a hack as there's no way to support fixed point VBOs - if( useFixedPoint && Gdx.graphics.getType() == GraphicsType.JoglGL) - return; - - if( !useVBO ) - return; - - if( Gdx.graphics.isGL20Available() ) - constructBufferObjects( Gdx.graphics.getGL20() ); + if (useFixedPoint && Gdx.graphics.getType() == GraphicsType.JoglGL) return; + + if (!useVBO) return; + + if (Gdx.graphics.isGL20Available()) + constructBufferObjects(Gdx.graphics.getGL20()); else - constructBufferObjects( Gdx.graphics.getGL11() ); + constructBufferObjects(Gdx.graphics.getGL11()); } - - private void constructBufferObjects( GL11 gl ) - { - ByteBuffer tmp = ByteBuffer.allocateDirect( 4 ); - tmp.order( ByteOrder.nativeOrder() ); + + private void constructBufferObjects (GL11 gl) { + ByteBuffer tmp = ByteBuffer.allocateDirect(4); + tmp.order(ByteOrder.nativeOrder()); IntBuffer handle = tmp.asIntBuffer(); - - gl.glGenBuffers( 1, handle ); - vertexBufferObjectHandle = handle.get(0); + + gl.glGenBuffers(1, handle); + vertexBufferObjectHandle = handle.get(0); int oldLimit = vertices.limit(); int oldPosition = vertices.position(); vertices.position(0); - vertices.limit(vertices.capacity()); - gl.glBindBuffer( GL11.GL_ARRAY_BUFFER, vertexBufferObjectHandle ); - gl.glBufferData( GL11.GL_ARRAY_BUFFER, getNumVertices() * attributes.vertexSize, vertices, isStatic?GL11.GL_STATIC_DRAW:GL11.GL_DYNAMIC_DRAW ); - gl.glBindBuffer( GL11.GL_ARRAY_BUFFER, 0 ); + vertices.limit(vertices.capacity()); + gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, vertexBufferObjectHandle); + gl.glBufferData(GL11.GL_ARRAY_BUFFER, getNumVertices() * attributes.vertexSize, vertices, isStatic ? GL11.GL_STATIC_DRAW + : GL11.GL_DYNAMIC_DRAW); + gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0); vertices.position(oldPosition); vertices.limit(oldLimit); - - if( maxIndices > 0 ) - { - gl.glGenBuffers( 1, handle ); - indexBufferObjectHandle = handle.get(0); + + if (maxIndices > 0) { + gl.glGenBuffers(1, handle); + indexBufferObjectHandle = handle.get(0); oldPosition = indices.position(); oldLimit = indices.limit(); indices.position(0); indices.limit(indices.capacity()); - gl.glBindBuffer( GL11.GL_ELEMENT_ARRAY_BUFFER, indexBufferObjectHandle ); - gl.glBufferData( GL11.GL_ELEMENT_ARRAY_BUFFER, indices.limit() * 2, indices, isStatic?GL11.GL_STATIC_DRAW:GL11.GL_DYNAMIC_DRAW ); - gl.glBindBuffer( GL11.GL_ELEMENT_ARRAY_BUFFER, 0 ); + gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, indexBufferObjectHandle); + gl.glBufferData(GL11.GL_ELEMENT_ARRAY_BUFFER, indices.limit() * 2, indices, isStatic ? GL11.GL_STATIC_DRAW + : GL11.GL_DYNAMIC_DRAW); + gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0); indices.position(oldPosition); indices.limit(oldLimit); } - + dirty = false; } - - private void constructBufferObjects( GL20 gl ) - { - ByteBuffer tmp = ByteBuffer.allocateDirect( 4 ); - tmp.order( ByteOrder.nativeOrder() ); + + private void constructBufferObjects (GL20 gl) { + ByteBuffer tmp = ByteBuffer.allocateDirect(4); + tmp.order(ByteOrder.nativeOrder()); IntBuffer handle = tmp.asIntBuffer(); - - gl.glGenBuffers( 1, handle ); - vertexBufferObjectHandle = handle.get(0); + + gl.glGenBuffers(1, handle); + vertexBufferObjectHandle = handle.get(0); int oldLimit = vertices.limit(); int oldPosition = vertices.position(); vertices.position(0); vertices.limit(vertices.capacity()); - gl.glBindBuffer( GL20.GL_ARRAY_BUFFER, vertexBufferObjectHandle ); - gl.glBufferData( GL20.GL_ARRAY_BUFFER, getNumVertices() * attributes.vertexSize, vertices, isStatic?GL20.GL_STATIC_DRAW:GL20.GL_DYNAMIC_DRAW ); - gl.glBindBuffer( GL20.GL_ARRAY_BUFFER, 0 ); + gl.glBindBuffer(GL20.GL_ARRAY_BUFFER, vertexBufferObjectHandle); + gl.glBufferData(GL20.GL_ARRAY_BUFFER, getNumVertices() * attributes.vertexSize, vertices, isStatic ? GL20.GL_STATIC_DRAW + : GL20.GL_DYNAMIC_DRAW); + gl.glBindBuffer(GL20.GL_ARRAY_BUFFER, 0); vertices.position(oldPosition); vertices.limit(oldLimit); - - if( maxIndices > 0 ) - { - gl.glGenBuffers( 1, handle ); - indexBufferObjectHandle = handle.get(0); + + if (maxIndices > 0) { + gl.glGenBuffers(1, handle); + indexBufferObjectHandle = handle.get(0); oldPosition = indices.position(); oldLimit = indices.limit(); indices.position(0); indices.limit(indices.capacity()); - gl.glBindBuffer( GL11.GL_ELEMENT_ARRAY_BUFFER, indexBufferObjectHandle ); - gl.glBufferData( GL11.GL_ELEMENT_ARRAY_BUFFER, indices.limit() * 2, indices, isStatic?GL20.GL_STATIC_DRAW:GL20.GL_DYNAMIC_DRAW ); - gl.glBindBuffer( GL11.GL_ELEMENT_ARRAY_BUFFER, 0 ); + gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, indexBufferObjectHandle); + gl.glBufferData(GL11.GL_ELEMENT_ARRAY_BUFFER, indices.limit() * 2, indices, isStatic ? GL20.GL_STATIC_DRAW + : GL20.GL_DYNAMIC_DRAW); + gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0); indices.position(oldPosition); indices.limit(oldLimit); } - - dirty = false; + + dirty = false; } - - private void fillBuffers( ) - { + + private void fillBuffers () { dirty = false; - if( Gdx.graphics.isGL11Available() == false && Gdx.graphics.isGL20Available() == false ) - return; - - if( Gdx.graphics.isGL20Available() ) - fillBuffers( Gdx.graphics.getGL20() ); + if (Gdx.graphics.isGL11Available() == false && Gdx.graphics.isGL20Available() == false) return; + + if (Gdx.graphics.isGL20Available()) + fillBuffers(Gdx.graphics.getGL20()); else - fillBuffers( Gdx.graphics.getGL11() ); + fillBuffers(Gdx.graphics.getGL11()); } - - private void fillBuffers( GL11 gl ) - { - gl.glBindBuffer( GL11.GL_ARRAY_BUFFER, vertexBufferObjectHandle ); + + private void fillBuffers (GL11 gl) { + gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, vertexBufferObjectHandle); // FIXME FUCK YOU QUALCOMM, your glBufferSubData is the slowest shit on earth... // Does not have a lot of impact on the Droid with 2.1 (2-3 frames for MD5Test) but still shitty. - if( Gdx.graphics.getType() == GraphicsType.AndroidGL ) - gl.glBufferData( GL11.GL_ARRAY_BUFFER, getNumVertices() * attributes.vertexSize, vertices, isStatic?GL11.GL_STATIC_DRAW:GL11.GL_DYNAMIC_DRAW); + if (Gdx.graphics.getType() == GraphicsType.AndroidGL) + gl.glBufferData(GL11.GL_ARRAY_BUFFER, getNumVertices() * attributes.vertexSize, vertices, isStatic ? GL11.GL_STATIC_DRAW + : GL11.GL_DYNAMIC_DRAW); else - gl.glBufferSubData( GL11.GL_ARRAY_BUFFER, 0, getNumVertices() * attributes.vertexSize, vertices ); - gl.glBindBuffer( GL11.GL_ARRAY_BUFFER, 0 ); - - if( maxIndices > 0 ) - { - gl.glBindBuffer( GL11.GL_ELEMENT_ARRAY_BUFFER, indexBufferObjectHandle ); + gl.glBufferSubData(GL11.GL_ARRAY_BUFFER, 0, getNumVertices() * attributes.vertexSize, vertices); + gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0); + + if (maxIndices > 0) { + gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, indexBufferObjectHandle); // FIXME FUCK YOU QUALCOMM, your glBufferSubData is the slowest shit on earth... - if( Gdx.graphics.getType() == GraphicsType.AndroidGL ) - gl.glBufferData( GL11.GL_ELEMENT_ARRAY_BUFFER, indices.limit() * 2, indices, isStatic?GL11.GL_STATIC_DRAW:GL11.GL_DYNAMIC_DRAW ); + if (Gdx.graphics.getType() == GraphicsType.AndroidGL) + gl.glBufferData(GL11.GL_ELEMENT_ARRAY_BUFFER, indices.limit() * 2, indices, isStatic ? GL11.GL_STATIC_DRAW + : GL11.GL_DYNAMIC_DRAW); else - gl.glBufferSubData( GL11.GL_ELEMENT_ARRAY_BUFFER, 0, indices.limit() * 2, indices ); - gl.glBindBuffer( GL11.GL_ELEMENT_ARRAY_BUFFER, 0 ); + gl.glBufferSubData(GL11.GL_ELEMENT_ARRAY_BUFFER, 0, indices.limit() * 2, indices); + gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0); } } - - private void fillBuffers( GL20 gl ) - { - gl.glBindBuffer( GL20.GL_ARRAY_BUFFER, vertexBufferObjectHandle ); - if( Gdx.graphics.getType() == GraphicsType.AndroidGL ) - gl.glBufferData( GL20.GL_ARRAY_BUFFER, getNumVertices() * attributes.vertexSize, vertices, isStatic?GL20.GL_STATIC_DRAW:GL20.GL_DYNAMIC_DRAW); + + private void fillBuffers (GL20 gl) { + gl.glBindBuffer(GL20.GL_ARRAY_BUFFER, vertexBufferObjectHandle); + if (Gdx.graphics.getType() == GraphicsType.AndroidGL) + gl.glBufferData(GL20.GL_ARRAY_BUFFER, getNumVertices() * attributes.vertexSize, vertices, isStatic ? GL20.GL_STATIC_DRAW + : GL20.GL_DYNAMIC_DRAW); else - gl.glBufferSubData( GL20.GL_ARRAY_BUFFER, 0, getNumVertices() * attributes.vertexSize, vertices ); - gl.glBindBuffer( GL20.GL_ARRAY_BUFFER, 0 ); - - if( maxIndices > 0 ) - { - gl.glBindBuffer( GL20.GL_ELEMENT_ARRAY_BUFFER, indexBufferObjectHandle ); - if( Gdx.graphics.getType() == GraphicsType.AndroidGL ) - gl.glBufferData( GL20.GL_ELEMENT_ARRAY_BUFFER, indices.limit() * 2, indices, isStatic?GL20.GL_STATIC_DRAW:GL20.GL_DYNAMIC_DRAW ); + gl.glBufferSubData(GL20.GL_ARRAY_BUFFER, 0, getNumVertices() * attributes.vertexSize, vertices); + gl.glBindBuffer(GL20.GL_ARRAY_BUFFER, 0); + + if (maxIndices > 0) { + gl.glBindBuffer(GL20.GL_ELEMENT_ARRAY_BUFFER, indexBufferObjectHandle); + if (Gdx.graphics.getType() == GraphicsType.AndroidGL) + gl.glBufferData(GL20.GL_ELEMENT_ARRAY_BUFFER, indices.limit() * 2, indices, isStatic ? GL20.GL_STATIC_DRAW + : GL20.GL_DYNAMIC_DRAW); else - gl.glBufferSubData( GL20.GL_ELEMENT_ARRAY_BUFFER, 0, indices.limit() * 2, indices ); - gl.glBindBuffer( GL20.GL_ELEMENT_ARRAY_BUFFER, 0 ); + gl.glBufferSubData(GL20.GL_ELEMENT_ARRAY_BUFFER, 0, indices.limit() * 2, indices); + gl.glBindBuffer(GL20.GL_ELEMENT_ARRAY_BUFFER, 0); } } - + /** - * Sets the vertices of this Mesh. The attributes are assumed to be given - * in float format. If this mesh is configured to use fixed point an - * IllegalArgumentException will be thrown. + * Sets the vertices of this Mesh. The attributes are assumed to be given in float format. If this mesh is configured to use + * fixed point an IllegalArgumentException will be thrown. * * @param vertices the vertices. */ - public void setVertices( float[] vertices ) - { - if( useFixedPoint ) - throw new IllegalArgumentException( "can't set float vertices for fixed point mesh" ); - - if( isDirect ) - { - BufferUtils.copy( vertices, this.vertices, vertices.length, 0 ); - this.verticesFloat.limit(this.vertices.limit() >> 2); - this.verticesFloat.position(0); - } - else - { + public void setVertices (float[] vertices) { + if (useFixedPoint) throw new IllegalArgumentException("can't set float vertices for fixed point mesh"); + + if (isDirect) { + BufferUtils.copy(vertices, this.vertices, vertices.length, 0); + this.verticesFloat.limit(this.vertices.limit() >> 2); + this.verticesFloat.position(0); + } else { this.verticesFloat.clear(); - this.verticesFloat.put( vertices ); - this.verticesFloat.limit( vertices.length ); - this.verticesFloat.position(0); + this.verticesFloat.put(vertices); + this.verticesFloat.limit(vertices.length); + this.verticesFloat.position(0); } - + dirty = true; } - + /** - * Sets the vertices of this Mesh. The attributes are assumed to be given - * in float format. If this mesh is configured to use fixed point an - * IllegalArgumentException will be thrown. + * Sets the vertices of this Mesh. The attributes are assumed to be given in float format. If this mesh is configured to use + * fixed point an IllegalArgumentException will be thrown. * * @param vertices the vertices. * @param offset the offset into the vertices array * @param count the number of floats to use */ - public void setVertices(float[] vertices, int offset, int count) - { - if( useFixedPoint ) - throw new IllegalArgumentException( "can't set float vertices for fixed point mesh" ); - - if( isDirect ) - { - BufferUtils.copy( vertices, this.vertices, count, offset ); - this.verticesFloat.limit(this.vertices.limit()>>2); + public void setVertices (float[] vertices, int offset, int count) { + if (useFixedPoint) throw new IllegalArgumentException("can't set float vertices for fixed point mesh"); + + if (isDirect) { + BufferUtils.copy(vertices, this.vertices, count, offset); + this.verticesFloat.limit(this.vertices.limit() >> 2); this.verticesFloat.position(0); - } - else - { + } else { this.verticesFloat.clear(); - this.verticesFloat.put( vertices, offset, count ); - this.verticesFloat.limit( count ); - this.verticesFloat.position(0); + this.verticesFloat.put(vertices, offset, count); + this.verticesFloat.limit(count); + this.verticesFloat.position(0); } - + dirty = true; } - + /** - * Sets the vertices of this Mesh. The attributes are assumed to be given - * in fixed point format. If this mesh is configured to use floats an - * IllegalArgumentException will be thrown. + * Sets the vertices of this Mesh. The attributes are assumed to be given in fixed point format. If this mesh is configured to + * use floats an IllegalArgumentException will be thrown. * * @param vertices the vertices. */ - public void setVertices( int[] vertices ) - { - if( !useFixedPoint ) - throw new IllegalArgumentException( "can't set fixed point vertices for float mesh" ); - + public void setVertices (int[] vertices) { + if (!useFixedPoint) throw new IllegalArgumentException("can't set fixed point vertices for float mesh"); + verticesFixed.clear(); - verticesFixed.put( vertices ); - verticesFixed.limit( vertices.length ); - verticesFixed.position(0); - - if( isDirect ) - { - this.vertices.limit(verticesFixed.limit()<<2); + verticesFixed.put(vertices); + verticesFixed.limit(vertices.length); + verticesFixed.position(0); + + if (isDirect) { + this.vertices.limit(verticesFixed.limit() << 2); this.vertices.position(0); } dirty = true; } - + /** - * Sets the vertices of this Mesh. The attributes are assumed to be given - * in fixed point format. If this mesh is configured to use floats an - * IllegalArgumentException will be thrown. + * Sets the vertices of this Mesh. The attributes are assumed to be given in fixed point format. If this mesh is configured to + * use floats an IllegalArgumentException will be thrown. * * @param vertices the vertices. * @param offset the offset into the vertices array * @param count the number of floats to use */ - public void setVertices( int[] vertices, int offset, int count ) - { - if( !useFixedPoint ) - throw new IllegalArgumentException( "can't set fixed point vertices for float mesh" ); - + public void setVertices (int[] vertices, int offset, int count) { + if (!useFixedPoint) throw new IllegalArgumentException("can't set fixed point vertices for float mesh"); + verticesFixed.clear(); - verticesFixed.put( vertices, offset, count ); + verticesFixed.put(vertices, offset, count); verticesFixed.limit(count); - verticesFixed.position(0); - - if( isDirect ) - { - this.vertices.limit(verticesFixed.limit()*4); + verticesFixed.position(0); + + if (isDirect) { + this.vertices.limit(verticesFixed.limit() * 4); this.vertices.position(0); } dirty = true; } - + /** * Sets the indices of this Mesh * * @param indices the indices */ - public void setIndices( short[] indices ) - { - this.indices.put( indices ); - this.indices.limit( indices.length ); + public void setIndices (short[] indices) { + this.indices.put(indices); + this.indices.limit(indices.length); this.indices.position(0); dirty = true; } - + /** * @return the number of defined indices */ - public int getNumIndices( ) - { + public int getNumIndices () { return indices.limit(); } - + /** * @return the number of defined vertices */ - public int getNumVertices( ) - { - return vertices.limit() / attributes.vertexSize * (isDirect?1:4); + public int getNumVertices () { + return vertices.limit() / attributes.vertexSize * (isDirect ? 1 : 4); } - + /** * @return the size of a single vertex in bytes */ - public int getVertexSize( ) - { + public int getVertexSize () { return attributes.vertexSize; } - + /** *

- * Renders the mesh using the given primitive type. If indices - * are set for this mesh then getNumIndices() / #vertices per primitive - * primitives are rendered. If no indices are set then getNumVertices() / #vertices per primitive are rendered. + * Renders the mesh using the given primitive type. If indices are set for this mesh then getNumIndices() / #vertices per + * primitive primitives are rendered. If no indices are set then getNumVertices() / #vertices per primitive are rendered. *

* *

@@ -479,18 +432,15 @@ public class Mesh * * @param primitiveType the primitive type */ - public void render( int primitiveType ) - { - render( primitiveType, 0, maxIndices > 0? getNumIndices(): getNumVertices() ); + public void render (int primitiveType) { + render(primitiveType, 0, maxIndices > 0 ? getNumIndices() : getNumVertices()); } - + /** *

- * Renders the mesh using the given primitive type. offset specifies the - * offset into either the vertex buffer or the index buffer depending on - * whether indices are defined. count specifies the number of - * vertices or indices to use thus count / #vertices per primitive primitives - * are rendered. + * Renders the mesh using the given primitive type. offset specifies the offset into either the vertex buffer or the index + * buffer depending on whether indices are defined. count specifies the number of vertices or indices to use thus count / + * #vertices per primitive primitives are rendered. *

* *

@@ -501,187 +451,158 @@ public class Mesh * @param offset the offset into the vertex or index buffer * @param count number of vertices or indices to use */ - public void render( int primitiveType, int offset, int count ) - { - if( Gdx.graphics.isGL20Available() ) - throw new IllegalStateException( "can't use this render method with OpenGL ES 2.0" ); - + public void render (int primitiveType, int offset, int count) { + if (Gdx.graphics.isGL20Available()) throw new IllegalStateException("can't use this render method with OpenGL ES 2.0"); + checkManagedAndDirty(); - - if( vertexBufferObjectHandle != 0 ) - renderVBO( primitiveType, offset, count ); + + if (vertexBufferObjectHandle != 0) + renderVBO(primitiveType, offset, count); else - renderVA( primitiveType, offset, count ); + renderVA(primitiveType, offset, count); } - - private void renderVBO( int primitiveType, int offset, int count ) - { + + private void renderVBO (int primitiveType, int offset, int count) { GL11 gl = Gdx.graphics.getGL11(); - gl.glBindBuffer( GL11.GL_ARRAY_BUFFER, vertexBufferObjectHandle ); - + gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, vertexBufferObjectHandle); + int numAttributes = attributes.size(); - int type = useFixedPoint?GL11.GL_FIXED:GL11.GL_FLOAT; + int type = useFixedPoint ? GL11.GL_FIXED : GL11.GL_FLOAT; int textureUnit = 0; - - for( int i = 0; i < numAttributes; i++ ) - { - VertexAttribute attribute = attributes.get( i ); - if( attribute.usage == Usage.Position ) - { - gl.glEnableClientState( GL11.GL_VERTEX_ARRAY ); - gl.glVertexPointer( attribute.numComponents, type, attributes.vertexSize, attribute.offset ); + + for (int i = 0; i < numAttributes; i++) { + VertexAttribute attribute = attributes.get(i); + if (attribute.usage == Usage.Position) { + gl.glEnableClientState(GL11.GL_VERTEX_ARRAY); + gl.glVertexPointer(attribute.numComponents, type, attributes.vertexSize, attribute.offset); continue; } - - if( attribute.usage == Usage.Color || attribute.usage == Usage.ColorPacked ) - { + + if (attribute.usage == Usage.Color || attribute.usage == Usage.ColorPacked) { int colorType = type; - if( attribute.usage == Usage.ColorPacked ) - colorType = GL11.GL_UNSIGNED_BYTE; - gl.glEnableClientState( GL11.GL_COLOR_ARRAY ); - gl.glColorPointer( attribute.numComponents, colorType, attributes.vertexSize, attribute.offset ); + if (attribute.usage == Usage.ColorPacked) colorType = GL11.GL_UNSIGNED_BYTE; + gl.glEnableClientState(GL11.GL_COLOR_ARRAY); + gl.glColorPointer(attribute.numComponents, colorType, attributes.vertexSize, attribute.offset); continue; } - - if( attribute.usage == Usage.Normal ) - { - gl.glEnableClientState( GL11.GL_NORMAL_ARRAY ); - gl.glNormalPointer( type, attributes.vertexSize, attribute.offset ); + + if (attribute.usage == Usage.Normal) { + gl.glEnableClientState(GL11.GL_NORMAL_ARRAY); + gl.glNormalPointer(type, attributes.vertexSize, attribute.offset); continue; } - - if( attribute.usage == Usage.TextureCoordinates ) - { - gl.glClientActiveTexture( GL11.GL_TEXTURE0 + textureUnit ); - gl.glEnableClientState( GL11.GL_TEXTURE_COORD_ARRAY ); - gl.glTexCoordPointer( attribute.numComponents, type, attributes.vertexSize, attribute.offset ); + + if (attribute.usage == Usage.TextureCoordinates) { + gl.glClientActiveTexture(GL11.GL_TEXTURE0 + textureUnit); + gl.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY); + gl.glTexCoordPointer(attribute.numComponents, type, attributes.vertexSize, attribute.offset); textureUnit++; continue; } } - - if( maxIndices > 0 ) - { - gl.glBindBuffer( GL11.GL_ELEMENT_ARRAY_BUFFER, indexBufferObjectHandle ); - gl.glDrawElements( primitiveType, count, GL10.GL_UNSIGNED_SHORT, offset * 2 ); - } - else - { - gl.glDrawArrays( primitiveType, offset, count); + + if (maxIndices > 0) { + gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, indexBufferObjectHandle); + gl.glDrawElements(primitiveType, count, GL10.GL_UNSIGNED_SHORT, offset * 2); + } else { + gl.glDrawArrays(primitiveType, offset, count); } - + textureUnit--; - - for( int i = 0; i < numAttributes; i++ ) - { - VertexAttribute attribute = attributes.get( i ); - if( attribute.usage == Usage.Color || attribute.usage == Usage.ColorPacked ) - gl.glDisableClientState( GL11.GL_COLOR_ARRAY ); - if( attribute.usage == Usage.Normal ) - gl.glDisableClientState( GL11.GL_NORMAL_ARRAY ); - if( attribute.usage == Usage.TextureCoordinates ) - { - gl.glClientActiveTexture( GL11.GL_TEXTURE0 + textureUnit ); - gl.glDisableClientState( GL11.GL_TEXTURE_COORD_ARRAY ); + + for (int i = 0; i < numAttributes; i++) { + VertexAttribute attribute = attributes.get(i); + if (attribute.usage == Usage.Color || attribute.usage == Usage.ColorPacked) + gl.glDisableClientState(GL11.GL_COLOR_ARRAY); + if (attribute.usage == Usage.Normal) gl.glDisableClientState(GL11.GL_NORMAL_ARRAY); + if (attribute.usage == Usage.TextureCoordinates) { + gl.glClientActiveTexture(GL11.GL_TEXTURE0 + textureUnit); + gl.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY); textureUnit--; - } + } } - - gl.glBindBuffer( GL20.GL_ARRAY_BUFFER, 0 ); - if( maxIndices > 0 ) - gl.glBindBuffer( GL20.GL_ELEMENT_ARRAY_BUFFER, 0 ); - } - - private void renderVA( int primitiveType, int offset, int count ) - { + + gl.glBindBuffer(GL20.GL_ARRAY_BUFFER, 0); + if (maxIndices > 0) gl.glBindBuffer(GL20.GL_ELEMENT_ARRAY_BUFFER, 0); + } + + private void renderVA (int primitiveType, int offset, int count) { GL10 gl = Gdx.graphics.getGL10(); - + int numAttributes = attributes.size(); - int type = useFixedPoint?GL11.GL_FIXED:GL11.GL_FLOAT; + int type = useFixedPoint ? GL11.GL_FIXED : GL11.GL_FLOAT; int textureUnit = 0; - - for( int i = 0; i < numAttributes; i++ ) - { - VertexAttribute attribute = attributes.get( i ); - if( attribute.usage == Usage.Position ) - { - gl.glEnableClientState( GL11.GL_VERTEX_ARRAY ); - vertices.position( attribute.offset ); - gl.glVertexPointer( attribute.numComponents, type, attributes.vertexSize, vertices ); + + for (int i = 0; i < numAttributes; i++) { + VertexAttribute attribute = attributes.get(i); + if (attribute.usage == Usage.Position) { + gl.glEnableClientState(GL11.GL_VERTEX_ARRAY); + vertices.position(attribute.offset); + gl.glVertexPointer(attribute.numComponents, type, attributes.vertexSize, vertices); continue; } - - if( attribute.usage == Usage.Color || attribute.usage == Usage.ColorPacked ) - { + + if (attribute.usage == Usage.Color || attribute.usage == Usage.ColorPacked) { int colorType = type; - if( attribute.usage == Usage.ColorPacked ) - colorType = GL11.GL_UNSIGNED_BYTE; - gl.glEnableClientState( GL11.GL_COLOR_ARRAY ); - vertices.position( attribute.offset ); - gl.glColorPointer( attribute.numComponents, colorType, attributes.vertexSize, vertices ); + if (attribute.usage == Usage.ColorPacked) colorType = GL11.GL_UNSIGNED_BYTE; + gl.glEnableClientState(GL11.GL_COLOR_ARRAY); + vertices.position(attribute.offset); + gl.glColorPointer(attribute.numComponents, colorType, attributes.vertexSize, vertices); continue; } - - if( attribute.usage == Usage.Normal ) - { - gl.glEnableClientState( GL11.GL_NORMAL_ARRAY ); - vertices.position( attribute.offset ); - gl.glNormalPointer( type, attributes.vertexSize, vertices ); + + if (attribute.usage == Usage.Normal) { + gl.glEnableClientState(GL11.GL_NORMAL_ARRAY); + vertices.position(attribute.offset); + gl.glNormalPointer(type, attributes.vertexSize, vertices); continue; } - - if( attribute.usage == Usage.TextureCoordinates ) - { - gl.glClientActiveTexture( GL11.GL_TEXTURE0 + textureUnit ); - gl.glEnableClientState( GL11.GL_TEXTURE_COORD_ARRAY ); - vertices.position( attribute.offset ); - gl.glTexCoordPointer( attribute.numComponents, type, attributes.vertexSize, vertices ); + + if (attribute.usage == Usage.TextureCoordinates) { + gl.glClientActiveTexture(GL11.GL_TEXTURE0 + textureUnit); + gl.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY); + vertices.position(attribute.offset); + gl.glTexCoordPointer(attribute.numComponents, type, attributes.vertexSize, vertices); textureUnit++; continue; } } - - if( maxIndices > 0 ) - gl.glDrawElements( primitiveType, count, GL10.GL_UNSIGNED_SHORT, indices ); + + if (maxIndices > 0) + gl.glDrawElements(primitiveType, count, GL10.GL_UNSIGNED_SHORT, indices); else - gl.glDrawArrays( primitiveType, offset, count); - + gl.glDrawArrays(primitiveType, offset, count); + textureUnit--; - - for( int i = 0; i < numAttributes; i++ ) - { - VertexAttribute attribute = attributes.get( i ); - if( attribute.usage == Usage.Color || attribute.usage == Usage.ColorPacked ) - gl.glDisableClientState( GL11.GL_COLOR_ARRAY ); - if( attribute.usage == Usage.Normal ) - gl.glDisableClientState( GL11.GL_NORMAL_ARRAY ); - if( attribute.usage == Usage.TextureCoordinates ) - { - //gl.glClientActiveTexture( GL11.GL_TEXTURE0 + textureUnit ); - gl.glDisableClientState( GL11.GL_TEXTURE_COORD_ARRAY ); + + for (int i = 0; i < numAttributes; i++) { + VertexAttribute attribute = attributes.get(i); + if (attribute.usage == Usage.Color || attribute.usage == Usage.ColorPacked) + gl.glDisableClientState(GL11.GL_COLOR_ARRAY); + if (attribute.usage == Usage.Normal) gl.glDisableClientState(GL11.GL_NORMAL_ARRAY); + if (attribute.usage == Usage.TextureCoordinates) { + // gl.glClientActiveTexture( GL11.GL_TEXTURE0 + textureUnit ); + gl.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY); textureUnit--; - } + } } - + vertices.position(0); } /** *

- * Renders the mesh using the given primitive type. If indices - * are set for this mesh then getNumIndices() / #vertices per primitive - * primitives are rendered. If no indices are set then getNumVertices() / #vertices per primitive are rendered. + * Renders the mesh using the given primitive type. If indices are set for this mesh then getNumIndices() / #vertices per + * primitive primitives are rendered. If no indices are set then getNumVertices() / #vertices per primitive are rendered. *

* *

- * This method will automatically bind each vertex attribute as specified at - * construction time via {@link VertexAttributes} to the respective shader - * attributes. The binding is based on the alias defined for each VertexAttribute. + * This method will automatically bind each vertex attribute as specified at construction time via {@link VertexAttributes} to + * the respective shader attributes. The binding is based on the alias defined for each VertexAttribute. *

* *

- * This method must only be called after the {@link ShaderProgram.begin()} method has been - * called! + * This method must only be called after the {@link ShaderProgram.begin()} method has been called! *

* *

@@ -690,29 +611,24 @@ public class Mesh * * @param primitiveType the primitive type */ - public void render( ShaderProgram shader, int primitiveType ) - { - render( shader, primitiveType, 0, maxIndices > 0? getNumIndices(): getNumVertices() ); + public void render (ShaderProgram shader, int primitiveType) { + render(shader, primitiveType, 0, maxIndices > 0 ? getNumIndices() : getNumVertices()); } /** *

- * Renders the mesh using the given primitive type. offset specifies the - * offset into either the vertex buffer or the index buffer depending on - * whether indices are defined. count specifies the number of - * vertices or indices to use thus count / #vertices per primitive primitives - * are rendered. + * Renders the mesh using the given primitive type. offset specifies the offset into either the vertex buffer or the index + * buffer depending on whether indices are defined. count specifies the number of vertices or indices to use thus count / + * #vertices per primitive primitives are rendered. *

* *

- * This method will automatically bind each vertex attribute as specified at - * construction time via {@link VertexAttributes} to the respective shader - * attributes. The binding is based on the alias defined for each VertexAttribute. + * This method will automatically bind each vertex attribute as specified at construction time via {@link VertexAttributes} to + * the respective shader attributes. The binding is based on the alias defined for each VertexAttribute. *

* *

- * This method must only be called after the {@link ShaderProgram.begin()} method has been - * called! + * This method must only be called after the {@link ShaderProgram.begin()} method has been called! *

* *

@@ -724,202 +640,174 @@ public class Mesh * @param offset the offset into the vertex or index buffer * @param count number of vertices or indices to use */ - public void render( ShaderProgram shader, int primitiveType, int offset, int count ) - { - if( !Gdx.graphics.isGL20Available() ) - throw new IllegalStateException( "can't use this render method with OpenGL ES 1.x" ); - + public void render (ShaderProgram shader, int primitiveType, int offset, int count) { + if (!Gdx.graphics.isGL20Available()) throw new IllegalStateException("can't use this render method with OpenGL ES 1.x"); + checkManagedAndDirty(); - + GL20 gl = Gdx.graphics.getGL20(); - gl.glBindBuffer( GL11.GL_ARRAY_BUFFER, vertexBufferObjectHandle ); - + gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, vertexBufferObjectHandle); + int numAttributes = attributes.size(); - int type = useFixedPoint?GL11.GL_FIXED:GL11.GL_FLOAT; + int type = useFixedPoint ? GL11.GL_FIXED : GL11.GL_FLOAT; int textureUnit = 0; - - for( int i = 0; i < numAttributes; i++ ) - { - VertexAttribute attribute = attributes.get( i ); - shader.enableVertexAttribute( attribute.alias ); + + for (int i = 0; i < numAttributes; i++) { + VertexAttribute attribute = attributes.get(i); + shader.enableVertexAttribute(attribute.alias); int colorType = type; boolean normalize = false; - if( attribute.usage == Usage.ColorPacked ) - { + if (attribute.usage == Usage.ColorPacked) { colorType = GL20.GL_UNSIGNED_BYTE; normalize = true; } - shader.setVertexAttribute( attribute.alias, attribute.numComponents, colorType, normalize, attributes.vertexSize, attribute.offset ); + shader.setVertexAttribute(attribute.alias, attribute.numComponents, colorType, normalize, attributes.vertexSize, + attribute.offset); } - - if( maxIndices > 0 ) - { - gl.glBindBuffer( GL11.GL_ELEMENT_ARRAY_BUFFER, indexBufferObjectHandle ); - gl.glDrawElements( primitiveType, count, GL10.GL_UNSIGNED_SHORT, offset * 2 ); - } - else - { - gl.glDrawArrays( primitiveType, offset, count); + + if (maxIndices > 0) { + gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, indexBufferObjectHandle); + gl.glDrawElements(primitiveType, count, GL10.GL_UNSIGNED_SHORT, offset * 2); + } else { + gl.glDrawArrays(primitiveType, offset, count); } - + textureUnit--; - - for( int i = 0; i < numAttributes; i++ ) - { - VertexAttribute attribute = attributes.get( i ); - shader.disableVertexAttribute( attribute.alias ); + + for (int i = 0; i < numAttributes; i++) { + VertexAttribute attribute = attributes.get(i); + shader.disableVertexAttribute(attribute.alias); } - - gl.glBindBuffer( GL20.GL_ARRAY_BUFFER, 0 ); - if( maxIndices > 0 ) - gl.glBindBuffer( GL20.GL_ELEMENT_ARRAY_BUFFER, 0 ); - } - - private void checkManagedAndDirty( ) - { - if( ! bufferCreatedFirstTime ){ + + gl.glBindBuffer(GL20.GL_ARRAY_BUFFER, 0); + if (maxIndices > 0) gl.glBindBuffer(GL20.GL_ELEMENT_ARRAY_BUFFER, 0); + } + + private void checkManagedAndDirty () { + if (!bufferCreatedFirstTime) { createBuffers(); bufferCreatedFirstTime = true; } - - if(vertexBufferObjectHandle == 0 ) - return; - - if( managed && invalidated || !bufferCreatedFirstTime) - { - if( Gdx.graphics.isGL11Available() ) - { + + if (vertexBufferObjectHandle == 0) return; + + if (managed && invalidated || !bufferCreatedFirstTime) { + if (Gdx.graphics.isGL11Available()) { createBuffers(); - fillBuffers( ); + fillBuffers(); } - if( Gdx.graphics.isGL20Available() ) - { + if (Gdx.graphics.isGL20Available()) { createBuffers(); - fillBuffers( ); - } + fillBuffers(); + } } - - + invalidated = false; - if( dirty ) - fillBuffers( ); + if (dirty) fillBuffers(); } - + /** * Frees all resources associated with this Mesh */ - public void dispose( ) - { + public void dispose () { meshes.remove(this); - - if( Gdx.graphics.isGL11Available() == false && Gdx.graphics.isGL20Available() == false ) - return; - - if( Gdx.graphics.isGL20Available() ) - dispose( Gdx.graphics.getGL20() ); + + if (Gdx.graphics.isGL11Available() == false && Gdx.graphics.isGL20Available() == false) return; + + if (Gdx.graphics.isGL20Available()) + dispose(Gdx.graphics.getGL20()); else - dispose( Gdx.graphics.getGL11() ); + dispose(Gdx.graphics.getGL11()); } - - private void dispose( GL11 gl ) - { + + private void dispose (GL11 gl) { int handle[] = new int[1]; handle[0] = vertexBufferObjectHandle; - gl.glDeleteBuffers( 1, handle, 0 ); - - if( maxIndices > 0 ) - { + gl.glDeleteBuffers(1, handle, 0); + + if (maxIndices > 0) { handle[0] = indexBufferObjectHandle; - gl.glDeleteBuffers( 1, handle, 0 ); + gl.glDeleteBuffers(1, handle, 0); } } - - private void dispose( GL20 gl ) - { - ByteBuffer tmp = ByteBuffer.allocateDirect( 4 ); - tmp.order( ByteOrder.nativeOrder() ); + + private void dispose (GL20 gl) { + ByteBuffer tmp = ByteBuffer.allocateDirect(4); + tmp.order(ByteOrder.nativeOrder()); IntBuffer handle = tmp.asIntBuffer(); - handle.put( vertexBufferObjectHandle ); + handle.put(vertexBufferObjectHandle); handle.position(0); - gl.glDeleteBuffers( 1, handle ); - - if( maxIndices > 0 ) - { + gl.glDeleteBuffers(1, handle); + + if (maxIndices > 0) { handle.clear(); - handle.put( indexBufferObjectHandle ); + handle.put(indexBufferObjectHandle); handle.position(0); - gl.glDeleteBuffers( 1, handle ); + gl.glDeleteBuffers(1, handle); } } - + /** * @return whether Q16 fixed point is used */ - public boolean usesFixedPoint( ) - { + public boolean usesFixedPoint () { return useFixedPoint; } - + /** * @return the maximum number of vertices this mesh can hold */ - public int getMaxVertices( ) - { + public int getMaxVertices () { return maxVertices; } - + /** * @return the maximum number of indices this mesh can hold */ - public int getMaxIndices( ) - { - return maxIndices; + public int getMaxIndices () { + return maxIndices; } /** - * Returns the first {@link VertexAttribute} having the given - * {@link Usage}. + * Returns the first {@link VertexAttribute} having the given {@link Usage}. * * @param usage the Usage. * @return the VertexAttribute or null if no attribute with that usage was found. */ - public VertexAttribute getVertexAttribute(int usage) - { - for( int i = 0; i < attributes.size(); i++ ) - if( attributes.get(i).usage == usage ) - return attributes.get(i); - + public VertexAttribute getVertexAttribute (int usage) { + for (int i = 0; i < attributes.size(); i++) + if (attributes.get(i).usage == usage) return attributes.get(i); + return null; } - + /** * @return the vertex attributes of this Mesh */ - public VertexAttributes getVertexAttributes( ) - { + public VertexAttributes getVertexAttributes () { return attributes; } - + /** - * @return the backing FloatBuffer holding the vertices. Will be null if this is a fixed point mesh. Does not have to be a direct buffer on Android! + * @return the backing FloatBuffer holding the vertices. Will be null if this is a fixed point mesh. Does not have to be a + * direct buffer on Android! */ - public FloatBuffer getVerticesBufferFloat( ) - { + public FloatBuffer getVerticesBufferFloat () { return verticesFloat; } + /** - * @return the backing IntBuffer holding the vertices. Will be null if this is a floating point mesh. Does not have to be a direct buffer on Android! + * @return the backing IntBuffer holding the vertices. Will be null if this is a floating point mesh. Does not have to be a + * direct buffer on Android! */ - public IntBuffer getVerticesBufferFixed( ) - { + public IntBuffer getVerticesBufferFixed () { return verticesFixed; } - + /** - * @return the backing shortbuffer holding the indices. Does not have to be a direct buffer on Android! + * @return the backing shortbuffer holding the indices. Does not have to be a direct buffer on Android! */ - public ShortBuffer getIndicesBuffer( ) - { + public ShortBuffer getIndicesBuffer () { return indices; } @@ -927,64 +815,53 @@ public class Mesh * Returns getNumVertices() vertices in the float array * @param vertices the destination array */ - public void getVertices(float[] vertices) - { - if( useFixedPoint ) - throw new IllegalArgumentException( "can't get float vertices from fixed point mesh" ); - + public void getVertices (float[] vertices) { + if (useFixedPoint) throw new IllegalArgumentException("can't get float vertices from fixed point mesh"); + verticesFloat.get(vertices); verticesFloat.position(0); } - + /** * Returns getNumVertices() vertices in the fixed point array * @param vertices the destination array */ - public void getVertices( int[] vertices ) - { - if( !useFixedPoint ) - throw new IllegalArgumentException( "can't get fixed point vertices from float mesh" ); - + public void getVertices (int[] vertices) { + if (!useFixedPoint) throw new IllegalArgumentException("can't get fixed point vertices from float mesh"); + verticesFixed.get(vertices); verticesFixed.position(0); } - + /** * Returns getNumIndices() indices in the short array * @param indices the destination array */ - public void getIndices( short[] indices ) - { + public void getIndices (short[] indices) { this.indices.get(indices); this.indices.position(0); } - + /** - * Invalidates all meshes so the next time they are rendered - * new VBO handles are generated. + * Invalidates all meshes so the next time they are rendered new VBO handles are generated. */ - public static void invalidateAllMeshes( ) - { + public static void invalidateAllMeshes () { // FIXME, this is evil in the test environment. WE - - for( int i = 0; i < meshes.size(); i++ ) - { + + for (int i = 0; i < meshes.size(); i++) { meshes.get(i).invalidated = true; - meshes.get(i).checkManagedAndDirty(); + meshes.get(i).checkManagedAndDirty(); } } - + /** - * Will clear the managed mesh cache. I wouldn't use this - * if i was you :) + * Will clear the managed mesh cache. I wouldn't use this if i was you :) */ - public static void clearAllMeshes( ) - { + public static void clearAllMeshes () { meshes.clear(); } - public void setDirty() - { - dirty = true; + public void setDirty () { + dirty = true; } } diff --git a/gdx/src/com/badlogic/gdx/graphics/ModelLoader.java b/gdx/src/com/badlogic/gdx/graphics/ModelLoader.java index 9057bcb0c..394dcbd98 100644 --- a/gdx/src/com/badlogic/gdx/graphics/ModelLoader.java +++ b/gdx/src/com/badlogic/gdx/graphics/ModelLoader.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics; import java.io.BufferedInputStream; @@ -26,104 +24,90 @@ import com.badlogic.gdx.graphics.loaders.OctLoader; import com.badlogic.gdx.math.Vector3; /** - * A class for loading various model formats such as - * Wavefront OBJ or the Quake II MD2 format. Ties in - * all the loaders from the loaders package. + * A class for loading various model formats such as Wavefront OBJ or the Quake II MD2 format. Ties in all the loaders from the + * loaders package. * * @author mzechner - * + * */ -public class ModelLoader -{ +public class ModelLoader { /** - * Loads a Wavefront OBJ file from the given - * InputStream. The OBJ file must only contain - * triangulated meshes. Materials are ignored. + * Loads a Wavefront OBJ file from the given InputStream. The OBJ file must only contain triangulated meshes. Materials are + * ignored. * * @param in the InputStream * @param useFloats whether to use floats or fixed point * @return a Mesh holding the OBJ data or null in case something went wrong. */ - public static Mesh loadObj( InputStream in, boolean useFloats ) - { - return ObjLoader.loadObj( in, useFloats); + public static Mesh loadObj (InputStream in, boolean useFloats) { + return ObjLoader.loadObj(in, useFloats); } - + /** - * Loads an OCT file as can be found in many of Paul Nettle's - * demo programs. See the source at http://www.paulnettle.com/pub/FluidStudios/CollisionDetection/Fluid_Studios_Collision_Detection_Demo_and_Source.zip - * for more information. + * Loads an OCT file as can be found in many of Paul Nettle's demo programs. See the source at + * http://www.paulnettle.com/pub/FluidStudios/CollisionDetection/Fluid_Studios_Collision_Detection_Demo_and_Source.zip for more + * information. * * @param in the InputStream * @param useFloats whether to return a {@link FloatMesh} or a {@link FixedPointMesh} * @param start the start position as defined in the map * @return a Mesh holding the OCT data or null in case something went wrong. */ - public static Mesh loadOct( InputStream in, boolean useFloats, Vector3 start ) - { - return OctLoader.loadOct( in, useFloats, start ); + public static Mesh loadOct (InputStream in, boolean useFloats, Vector3 start) { + return OctLoader.loadOct(in, useFloats, start); } - + /** * Loads a GDX3D file previously written with {@link ModelWriter.writeGdx3D}. * * @param in the InputStream * @return a Mesh holding the Gdx3D data or null in case something went wrong. */ - public static Mesh loadGdx3D( InputStream in ) - { - try - { - DataInputStream din = new DataInputStream( new BufferedInputStream( in ) ); + public static Mesh loadGdx3D (InputStream in) { + try { + DataInputStream din = new DataInputStream(new BufferedInputStream(in)); int numAttributes = din.readInt(); ArrayList attributes = new ArrayList(); - for( int i = 0; i < numAttributes; i++ ) - { + for (int i = 0; i < numAttributes; i++) { int usage = din.readInt(); int numComponents = din.readInt(); int strlen = din.readInt(); byte[] bytes = new byte[strlen]; din.readFully(bytes); - String alias = new String( bytes, "UTF8" ); - - VertexAttribute attribute = new VertexAttribute( usage, numComponents, alias); - attributes.add( attribute ); + String alias = new String(bytes, "UTF8"); + + VertexAttribute attribute = new VertexAttribute(usage, numComponents, alias); + attributes.add(attribute); } - + boolean usesFixedPoint = din.readBoolean(); int numVertices = din.readInt(); int numElements = din.readInt(); int numIndices = din.readInt(); - - Mesh mesh = new Mesh( true, usesFixedPoint, numVertices, numIndices, attributes.toArray( new VertexAttribute[0] ) ); - - if( usesFixedPoint ) - { + + Mesh mesh = new Mesh(true, usesFixedPoint, numVertices, numIndices, attributes.toArray(new VertexAttribute[0])); + + if (usesFixedPoint) { int[] vertices = new int[numElements]; - for( int i = 0; i < numElements; i++ ) + for (int i = 0; i < numElements; i++) vertices[i] = din.readInt(); - mesh.setVertices( vertices ); - } - else - { + mesh.setVertices(vertices); + } else { float[] vertices = new float[numElements]; - for( int i = 0; i < numElements; i++ ) + for (int i = 0; i < numElements; i++) vertices[i] = din.readFloat(); - mesh.setVertices( vertices ); + mesh.setVertices(vertices); } - - if( numIndices > 0 ) - { + + if (numIndices > 0) { short[] indices = new short[numIndices]; - for( int i = 0; i < numIndices; i++ ) + for (int i = 0; i < numIndices; i++) indices[i] = din.readShort(); - mesh.setIndices( indices ); + mesh.setIndices(indices); } - + return mesh; - } - catch( IOException ex ) - { + } catch (IOException ex) { ex.printStackTrace(); return null; } diff --git a/gdx/src/com/badlogic/gdx/graphics/ModelWriter.java b/gdx/src/com/badlogic/gdx/graphics/ModelWriter.java index 66eb8c4b0..190a911a8 100644 --- a/gdx/src/com/badlogic/gdx/graphics/ModelWriter.java +++ b/gdx/src/com/badlogic/gdx/graphics/ModelWriter.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics; import java.io.BufferedOutputStream; @@ -23,79 +21,68 @@ import java.io.OutputStream; /** * Class that exports a mesh to a specific file format * @author mzechner - * + * */ -public class ModelWriter -{ +public class ModelWriter { /** - * Writes the given mesh to the gdx3D format. Does not - * close the output stream. + * Writes the given mesh to the gdx3D format. Does not close the output stream. * * @param mesh The mesh * @param out The OutputStream to write to. * @return whether the conversion worked or not. */ - public static boolean writeGdx3D( Mesh mesh, OutputStream out ) - { - try - { - DataOutputStream dout = new DataOutputStream( new BufferedOutputStream( out ) ); - + public static boolean writeGdx3D (Mesh mesh, OutputStream out) { + try { + DataOutputStream dout = new DataOutputStream(new BufferedOutputStream(out)); + // output vertex attributes - dout.writeInt( mesh.getVertexAttributes().size() ); - for( int i = 0; i < mesh.getVertexAttributes().size(); i++ ) - { + dout.writeInt(mesh.getVertexAttributes().size()); + for (int i = 0; i < mesh.getVertexAttributes().size(); i++) { VertexAttribute attribute = mesh.getVertexAttributes().get(i); - dout.writeInt( attribute.usage ); - dout.writeInt( attribute.numComponents ); - byte[] bytes = attribute.alias.getBytes( "UTF8" ); - dout.writeInt( bytes.length ); - dout.write( bytes ); + dout.writeInt(attribute.usage); + dout.writeInt(attribute.numComponents); + byte[] bytes = attribute.alias.getBytes("UTF8"); + dout.writeInt(bytes.length); + dout.write(bytes); } - + // output whether this mesh uses fixed point or not. - dout.writeBoolean( mesh.usesFixedPoint() ); - + dout.writeBoolean(mesh.usesFixedPoint()); + // output the number of vertices and indices - dout.writeInt( mesh.getNumVertices() ); - dout.writeInt( mesh.getNumVertices() * mesh.getVertexSize() / 4 ); - dout.writeInt( mesh.getNumIndices() ); - + dout.writeInt(mesh.getNumVertices()); + dout.writeInt(mesh.getNumVertices() * mesh.getVertexSize() / 4); + dout.writeInt(mesh.getNumIndices()); + // output vertices - if( mesh.usesFixedPoint() ) - { + if (mesh.usesFixedPoint()) { int[] vertices = new int[mesh.getNumVertices() * mesh.getVertexSize() / 4]; - mesh.getVertices( vertices ); - for( int i = 0; i < vertices.length; i++ ) - dout.writeInt( vertices[i] ); - } - else - { + mesh.getVertices(vertices); + for (int i = 0; i < vertices.length; i++) + dout.writeInt(vertices[i]); + } else { float[] vertices = new float[mesh.getNumVertices() * mesh.getVertexSize() / 4]; - mesh.getVertices( vertices ); - for( int i = 0; i < vertices.length; i++ ) - dout.writeFloat( vertices[i] ); + mesh.getVertices(vertices); + for (int i = 0; i < vertices.length; i++) + dout.writeFloat(vertices[i]); } - + dout.flush(); - + // output indices if any - if( mesh.getNumIndices() > 0 ) - { + if (mesh.getNumIndices() > 0) { short[] indices = new short[mesh.getNumIndices()]; - mesh.getIndices( indices ); - for( int i = 0; i < indices.length; i++ ) - dout.writeShort(indices[i] ); + mesh.getIndices(indices); + for (int i = 0; i < indices.length; i++) + dout.writeShort(indices[i]); } - + dout.flush(); - + return true; - } - catch( IOException ex ) - { + } catch (IOException ex) { ex.printStackTrace(); return false; - } + } } } diff --git a/gdx/src/com/badlogic/gdx/graphics/OrthographicCamera.java b/gdx/src/com/badlogic/gdx/graphics/OrthographicCamera.java index 7e9f3bc89..c0ece12ed 100644 --- a/gdx/src/com/badlogic/gdx/graphics/OrthographicCamera.java +++ b/gdx/src/com/badlogic/gdx/graphics/OrthographicCamera.java @@ -1,342 +1,299 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Graphics; +import com.badlogic.gdx.graphics.OrthographicCamera.Side; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.collision.Ray; /** - * An orthographic camera having a position and a scale value for zooming. Looks - * at one of the sides given in the {@link Side} enums, default is front, looking - * along the z-Axis. Generally you will want to alter the camera's scale and position - * and then set its matrices via a call to {@link OrthographicCamera.setMatrices()} which - * takes a {@link Graphics} instance from which it retrieves an GL10 instance to - * set the matrices. You can get a picking ray via a call to {@link OrthographicCamera.getPickRay()}. - * For OpenGL ES 2.0 you can get the matrices via {@link OrthographicCamera.getCombinedMatrix()} to - * set them as a uniform. For this you have to call {@link OrthographicCamera.update()} before you - * retrieve the matrices. + * An orthographic camera having a position and a scale value for zooming. Looks at one of the sides given in the {@link Side} + * enums, default is front, looking along the z-Axis. Generally you will want to alter the camera's scale and position and then + * set its matrices via a call to {@link OrthographicCamera.setMatrices()} which takes a {@link Graphics} instance from which it + * retrieves an GL10 instance to set the matrices. You can get a picking ray via a call to {@link OrthographicCamera.getPickRay()} + * . For OpenGL ES 2.0 you can get the matrices via {@link OrthographicCamera.getCombinedMatrix()} to set them as a uniform. For + * this you have to call {@link OrthographicCamera.update()} before you retrieve the matrices. * * @author badlogicgames@gmail.com - * + * */ -public final class OrthographicCamera -{ - public enum Side - { - FRONT, - BACK, - TOP, - BOTTOM, - LEFT, - RIGHT +public final class OrthographicCamera { + public enum Side { + FRONT, BACK, TOP, BOTTOM, LEFT, RIGHT } - + private Side side; - private Vector3 position = new Vector3( ); - private Vector3 direction = new Vector3( 0, 0, -1 ); - private Vector3 up = new Vector3( 0, 0, -1 ); - private Vector3 axis = new Vector3( 0, 1, 0 ); + private Vector3 position = new Vector3(); + private Vector3 direction = new Vector3(0, 0, -1); + private Vector3 up = new Vector3(0, 0, -1); + private Vector3 axis = new Vector3(0, 1, 0); private float near = -1000; private float far = 1000; private float scale = 1.0f; private float viewportWidth = 0; private float viewportHeight = 0; - + private final Matrix4 proj = new Matrix4(); private final Matrix4 model = new Matrix4(); private final Matrix4 combined = new Matrix4(); private final Matrix4 rotationMatrix = new Matrix4(); - + /** * Constructor, sets side to {@link Side.FRONT} */ - public OrthographicCamera( ) - { + public OrthographicCamera () { setSide(Side.FRONT); } - + /** * @return Which side the camera looks at */ - public Side getSide() { + public Side getSide () { return side; } - + /** * Sets the side the camera looks at. * @param side The side. */ - public void setSide(Side side) { + public void setSide (Side side) { this.side = side; - calculateRotationMatrix( ); + calculateRotationMatrix(); } - + /** * @return The near plane. */ - public float getNear() { + public float getNear () { return near; } - + /** * Sets the near plane. * * @param near The near plane */ - public void setNear(float near) { + public void setNear (float near) { this.near = near; } - + /** * @return The far plane. */ - public float getFar() { + public float getFar () { return far; } - + /** * Sets the far plane * @param far the far plane */ - public void setFar(float far) { + public void setFar (float far) { this.far = far; } - + /** * @return The scale */ - public float getScale() { + public float getScale () { return scale; } - + /** * @param scale Sets the scale */ - public void setScale(float scale) { + public void setScale (float scale) { this.scale = scale; } - + /** * @return The position */ - public Vector3 getPosition() { + public Vector3 getPosition () { return position; } - + /** * Sets the viewport - * + * * @param width The viewport width in pixels * @param height The viewport height in pixels */ - public void setViewport( float width, float height ) - { + public void setViewport (float width, float height) { this.viewportWidth = width; this.viewportHeight = height; } - - Vector3 tmp = new Vector3( ); - + + Vector3 tmp = new Vector3(); + /** - * Updates the frustum as well as the matrices of the camera - * based on the near and far plane, the position, the side and - * the scale. + * Updates the frustum as well as the matrices of the camera based on the near and far plane, the position, the side and the + * scale. */ - public void update( ) - { - proj.setToOrtho2D(0, 0, (viewportWidth * scale), (viewportHeight * scale), near, far ); + public void update () { + proj.setToOrtho2D(0, 0, (viewportWidth * scale), (viewportHeight * scale), near, far); model.idt(); - model.setToTranslation( tmp.set( (-position.x + (viewportWidth / 2) * scale), (-position.y + (viewportHeight / 2) * scale), (-position.z) ) ); - combined.set( proj ); - combined.mul( model ); - combined.mul( rotationMatrix ); + model.setToTranslation(tmp.set((-position.x + (viewportWidth / 2) * scale), (-position.y + (viewportHeight / 2) * scale), + (-position.z))); + combined.set(proj); + combined.mul(model); + combined.mul(rotationMatrix); } - + /** - * Sets the projection matrix that also incorporates the camera's scale - * and position and loads an identity to the model view matrix of OpenGL ES 1.x. - * The current matrices get overwritten. The matrix mode will be left in the model view state after - * a call to this. + * Sets the projection matrix that also incorporates the camera's scale and position and loads an identity to the model view + * matrix of OpenGL ES 1.x. The current matrices get overwritten. The matrix mode will be left in the model view state after a + * call to this. */ - public void setMatrices( ) - { + public void setMatrices () { update(); GL10 gl = Gdx.graphics.getGL10(); - gl.glMatrixMode( GL10.GL_PROJECTION ); - gl.glLoadMatrixf( getCombinedMatrix().val, 0 ); - gl.glMatrixMode( GL10.GL_MODELVIEW ); + gl.glMatrixMode(GL10.GL_PROJECTION); + gl.glLoadMatrixf(getCombinedMatrix().val, 0); + gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); } - - private Matrix4 calculateRotationMatrix( ) - { + + private Matrix4 calculateRotationMatrix () { float rotation = 0; - if( side == Side.FRONT ) - { - direction.set( 0, 0, -1 ); - up.set( 0, 1, 0 ); - } - else if( side == Side.BACK ) - { - axis.set( 0, 1, 0 ); + if (side == Side.FRONT) { + direction.set(0, 0, -1); + up.set(0, 1, 0); + } else if (side == Side.BACK) { + axis.set(0, 1, 0); rotation = 180; - direction.set( 0, 0, 1 ); - up.set( 0, 1, 0 ); - } - else if( side == Side.TOP ) - { - axis.set( 1, 0, 0 ); + direction.set(0, 0, 1); + up.set(0, 1, 0); + } else if (side == Side.TOP) { + axis.set(1, 0, 0); rotation = 90; - direction.set( 0, -1, 0 ); - up.set( 0, 0, -1 ); - } - else if( side == Side.BOTTOM ) - { - axis.set( 1, 0, 0 ); + direction.set(0, -1, 0); + up.set(0, 0, -1); + } else if (side == Side.BOTTOM) { + axis.set(1, 0, 0); rotation = -90; - direction.set( 0, 1, 0 ); - up.set( 0, 0, -1 ); - } - else if( side == Side.LEFT ) - { - axis.set( 0, 1, 0 ); + direction.set(0, 1, 0); + up.set(0, 0, -1); + } else if (side == Side.LEFT) { + axis.set(0, 1, 0); rotation = 90; - direction.set( -1, 0, 0 ); - up.set( 0, 1, 0 ); - } - else if( side == Side.RIGHT ) - { - axis.set( 0, 1, 0 ); + direction.set(-1, 0, 0); + up.set(0, 1, 0); + } else if (side == Side.RIGHT) { + axis.set(0, 1, 0); rotation = -90; - direction.set( 1, 0, 0 ); - up.set( 0, 1, 0 ); + direction.set(1, 0, 0); + up.set(0, 1, 0); } - + rotationMatrix.setToRotation(axis, rotation); return rotationMatrix; } - + /** - * Calculates the world coordinates of the given screen coordinates and stores - * the result in world + * Calculates the world coordinates of the given screen coordinates and stores the result in world * @param screenX the x-coordinate of the screen position * @param screenY the y-coordinate of the screen position * @param world the vector to store the result in */ - public void getScreenToWorld( float screenX, float screenY, Vector2 world ) - { + public void getScreenToWorld (float screenX, float screenY, Vector2 world) { screenX = screenX / Gdx.graphics.getWidth() * viewportWidth; screenY = screenY / Gdx.graphics.getHeight() * viewportHeight; - - world.set( ( screenX * scale ) - ( viewportWidth * scale ) / 2 + position.x, - ( (viewportHeight -screenY) * scale ) - ( viewportHeight * scale ) / 2 + position.y ); + + world.set((screenX * scale) - (viewportWidth * scale) / 2 + position.x, ((viewportHeight - screenY) * scale) + - (viewportHeight * scale) / 2 + position.y); } - + /** * Calculates the screen coordinates of the given world coordinates - * + * * @param worldX world x-coordinate * @param worldY world y-coordinate * @param screen the screen coordinates get stored here */ - public void getWorldToScreen( float worldX, float worldY, Vector2 screen ) - { - screen.x = (int)((worldX + ( viewportWidth * scale ) / 2 - position.x) / scale); - screen.y = (int)(-( -worldY + (viewportHeight * scale ) / 2 + position.y - viewportHeight * scale ) / scale); + public void getWorldToScreen (float worldX, float worldY, Vector2 screen) { + screen.x = (int)((worldX + (viewportWidth * scale) / 2 - position.x) / scale); + screen.y = (int)(-(-worldY + (viewportHeight * scale) / 2 + position.y - viewportHeight * scale) / scale); } - + /** * Returns the given screen x-coordinates as a world x-coordinate * @param screenX The screen x-coordinate * @return The world x-coordinate */ - public float getScreenToWorldX( float screenX ) - { - return ( screenX * scale ) - ( viewportWidth * scale ) / 2 + position.x; - } - + public float getScreenToWorldX (float screenX) { + return (screenX * scale) - (viewportWidth * scale) / 2 + position.x; + } + /** * Returns the given world x-coordinate as a screen x-coordinate * @param worldX The world x-coordinate * @return The screen x-coordinate */ - public int getWorldToScreenX( float worldX ) - { - return (int)((worldX + ( viewportWidth * scale ) / 2 - position.x) / scale); - } - + public int getWorldToScreenX (float worldX) { + return (int)((worldX + (viewportWidth * scale) / 2 - position.x) / scale); + } + /** * Returns the given screen y-coordinates as a world y-coordinate * @param screenY The screen y-coordinate * @return The world y-coordinate */ - public float getScreenToWorldY( float screenY ) - { - return ( (viewportHeight - screenY-1) * scale ) - ( viewportHeight * scale ) / 2 + position.y; + public float getScreenToWorldY (float screenY) { + return ((viewportHeight - screenY - 1) * scale) - (viewportHeight * scale) / 2 + position.y; } - + /** * Returns the given world y-coordinate as a screen x-coordinate * @param worldY The world y-coordinate * @return The screen y-coordinate */ - public int getWorldToScreenY( float worldY ) - { - return (int)(-( -worldY + (viewportHeight * scale ) / 2 + position.y - viewportHeight * scale ) / scale); - } - - Ray ray = new Ray( new Vector3( ), new Vector3( ) ); - Vector3 tmp2 = new Vector3( ); - + public int getWorldToScreenY (float worldY) { + return (int)(-(-worldY + (viewportHeight * scale) / 2 + position.y - viewportHeight * scale) / scale); + } + + Ray ray = new Ray(new Vector3(), new Vector3()); + Vector3 tmp2 = new Vector3(); + /** - * Returns a ray in world space form the given screen coordinates. - * This can be used for picking. The returned Ray is an internal - * member of this class to reduce memory allocations. Do not reuse - * it outside of this class. + * Returns a ray in world space form the given screen coordinates. This can be used for picking. The returned Ray is an + * internal member of this class to reduce memory allocations. Do not reuse it outside of this class. * * @param screenX The screen x-coordinate * @param screenY The screen y-coordinate * @return The picking ray. */ - public Ray getPickRay( int screenX, int screenY ) - { - float x = getScreenToWorldX( screenX ); - float y = getScreenToWorldY( screenY ); - - if( side == Side.TOP ) - { - return ray.set( x, 1000 / 2, -y , 0, -1, 0 ); - } - else if( side == Side.BOTTOM ) - { - return ray.set( x, 1000 / 2, y, 0, 1, 0 ); - } - else - return ray.set( tmp2.set( x, y, 10000 / 2 ).mul( rotationMatrix ), tmp.set( 0, 0, -1 ).mul(rotationMatrix) ); + public Ray getPickRay (int screenX, int screenY) { + float x = getScreenToWorldX(screenX); + float y = getScreenToWorldY(screenY); + + if (side == Side.TOP) { + return ray.set(x, 1000 / 2, -y, 0, -1, 0); + } else if (side == Side.BOTTOM) { + return ray.set(x, 1000 / 2, y, 0, 1, 0); + } else + return ray.set(tmp2.set(x, y, 10000 / 2).mul(rotationMatrix), tmp.set(0, 0, -1).mul(rotationMatrix)); } /** * @return The combined matrix. */ - public Matrix4 getCombinedMatrix() - { + public Matrix4 getCombinedMatrix () { return combined; } } diff --git a/gdx/src/com/badlogic/gdx/graphics/PerspectiveCamera.java b/gdx/src/com/badlogic/gdx/graphics/PerspectiveCamera.java index 6e05190f2..f9b253e98 100644 --- a/gdx/src/com/badlogic/gdx/graphics/PerspectiveCamera.java +++ b/gdx/src/com/badlogic/gdx/graphics/PerspectiveCamera.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics; import com.badlogic.gdx.Gdx; @@ -22,230 +20,209 @@ import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.collision.Ray; - - /** - * A perspective camera, having a position, a direction an up vector, - * a near plane, a far plane and a field of view. Use the {@link PerspectiveCamera.setViewport()} - * method to set the viewport from which the aspect ratio is derrived from, then - * call {@link PerspectiveCamera.update()} to update all the camera matrices as well as the - * {@link Frustum}. The combined matrix (projection, modelview) can be retrieved via a call - * to {@link PerspectiveCamera.getCombinedMatrix()} and directly passed to OpenGL. A convenience - * method called {@link PerspectiveCamera.setMatrices()} exists for OpenGL ES 1.x that will - * update the matrices and set them via a {@link Graphics} instance to OpenGL. - * You can also get a picking ray via {@link PerspectiveCamera.getPickRay()}. + * A perspective camera, having a position, a direction an up vector, a near plane, a far plane and a field of view. Use the + * {@link PerspectiveCamera.setViewport()} method to set the viewport from which the aspect ratio is derrived from, then call + * {@link PerspectiveCamera.update()} to update all the camera matrices as well as the {@link Frustum}. The combined matrix + * (projection, modelview) can be retrieved via a call to {@link PerspectiveCamera.getCombinedMatrix()} and directly passed to + * OpenGL. A convenience method called {@link PerspectiveCamera.setMatrices()} exists for OpenGL ES 1.x that will update the + * matrices and set them via a {@link Graphics} instance to OpenGL. You can also get a picking ray via {@link + * PerspectiveCamera.getPickRay()}. * * @author badlogicgames@gmail.com - * + * */ -public final class PerspectiveCamera -{ - protected Matrix4 tmp = new Matrix4( ); - protected Matrix4 proj = new Matrix4( ); - protected Matrix4 model = new Matrix4( ); - protected Matrix4 comb = new Matrix4( ); - private final Vector3 direction = new Vector3( 0, 0, -1 ); - private final Vector3 up = new Vector3( 0, 1, 0 ); - private final Vector3 right = new Vector3( 1, 0, 0 ); - private final Vector3 position = new Vector3( ); - private final Frustum frustum = new Frustum( ); - +public final class PerspectiveCamera { + protected Matrix4 tmp = new Matrix4(); + protected Matrix4 proj = new Matrix4(); + protected Matrix4 model = new Matrix4(); + protected Matrix4 comb = new Matrix4(); + private final Vector3 direction = new Vector3(0, 0, -1); + private final Vector3 up = new Vector3(0, 1, 0); + private final Vector3 right = new Vector3(1, 0, 0); + private final Vector3 position = new Vector3(); + private final Frustum frustum = new Frustum(); + private float near = 1; private float far = 1000; - private float fov = 90; + private float fov = 90; private float viewportWidth = 640; private float viewportHeight = 480; - + /** * @return The near plane. */ - public float getNear( ) - { + public float getNear () { return near; } - + /** * Sets the near plane. * @param near The near plane */ - public void setNear( float near ) - { + public void setNear (float near) { this.near = near; } - + /** * @return The far plane */ - public float getFar( ) - { + public float getFar () { return far; } - + /** * Sets the far plane * @param far The far plane */ - public void setFar( float far ) - { + public void setFar (float far) { this.far = far; } - + /** * @return The field of view in degrees */ - public float getFov() { + public float getFov () { return fov; } - + /** * Sets the field of view in degrees * @param fov The field of view */ - public void setFov(float fov) { + public void setFov (float fov) { this.fov = fov; } - + /** * @return The viewport height */ - public float getViewportWidth() { + public float getViewportWidth () { return viewportWidth; } - + /** - * Sets the viewport dimensions. + * Sets the viewport dimensions. * @param viewportWidth The viewport width in pixels. * @param viewportHeight The viewport height in pixels. */ - public void setViewport(float viewportWidth, float viewportHeight) { + public void setViewport (float viewportWidth, float viewportHeight) { this.viewportWidth = viewportWidth; this.viewportHeight = viewportHeight; - } - + } + /** * @return The projection matrix. */ - public Matrix4 getProjectionMatrix() - { + public Matrix4 getProjectionMatrix () { return proj; } - + /** * @return The modelview matrix. */ - public Matrix4 getModelviewMatrix() - { + public Matrix4 getModelviewMatrix () { return model; } - + /** * @return The combined matrix, projection * modelview */ - public Matrix4 getCombinedMatrix( ) - { + public Matrix4 getCombinedMatrix () { return comb; } - + /** * @return The {@link Frustum} */ - public Frustum getFrustum( ) - { + public Frustum getFrustum () { return frustum; } - + Vector3 tmp2 = new Vector3(); + /** - * Updates all matrices as well as the Frustum based on the - * last set parameters for position, direction, up vector, - * field of view, near and far plane and viewport. - */ - public void update( ) - { + * Updates all matrices as well as the Frustum based on the last set parameters for position, direction, up vector, field of + * view, near and far plane and viewport. + */ + public void update () { float aspect = viewportWidth / viewportHeight; - - frustum.setCameraParameters( fov, aspect, near, far ); + + frustum.setCameraParameters(fov, aspect, near, far); frustum.setCameraOrientation(position, direction, up); - right.set( direction ).crs( up ); - - proj.setToProjection( near, far, fov, aspect ); - model.setToLookAt( position, tmp2.set(position).add(direction), up ); -// model.mul( tmp.setToTranslation( tmp2.set(position).mul(-1) ) ); - comb.set( proj ).mul( model ); + right.set(direction).crs(up); + + proj.setToProjection(near, far, fov, aspect); + model.setToLookAt(position, tmp2.set(position).add(direction), up); +// model.mul( tmp.setToTranslation( tmp2.set(position).mul(-1) ) ); + comb.set(proj).mul(model); } - + /** - * Sets the projection and model view matrix of OpenGL ES 1.x to - * this camera's projection and model view matrix. Any previously set - * matrices are overwritten. Upon returning from this - * method the matrix mode will be GL10.GL_MODELVIEW. + * Sets the projection and model view matrix of OpenGL ES 1.x to this camera's projection and model view matrix. Any previously + * set matrices are overwritten. Upon returning from this method the matrix mode will be GL10.GL_MODELVIEW. * */ - public void setMatrices( ) - { + public void setMatrices () { setViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); update(); GL10 gl = Gdx.graphics.getGL10(); - gl.glMatrixMode( GL10.GL_PROJECTION ); - gl.glLoadMatrixf( getCombinedMatrix().val, 0 ); - gl.glMatrixMode( GL10.GL_MODELVIEW ); - gl.glLoadIdentity(); + gl.glMatrixMode(GL10.GL_PROJECTION); + gl.glLoadMatrixf(getCombinedMatrix().val, 0); + gl.glMatrixMode(GL10.GL_MODELVIEW); + gl.glLoadIdentity(); } - + /** * @return The direction vector. */ - public Vector3 getDirection() { + public Vector3 getDirection () { return direction; } - + /** * @return The right vector */ - public Vector3 getRight() { + public Vector3 getRight () { return right; } - + /** - * @return The up vector. + * @return The up vector. */ - public Vector3 getUp() { + public Vector3 getUp () { return up; } - + /** * @return The position. */ - public Vector3 getPosition() { + public Vector3 getPosition () { return position; - } - + } + /** - * Returns a ray in world space form the given screen coordinates. - * This can be used for picking. The returned Ray is an internal - * member of this class to reduce memory allocations. Do not reuse - * it outside of this class. + * Returns a ray in world space form the given screen coordinates. This can be used for picking. The returned Ray is an + * internal member of this class to reduce memory allocations. Do not reuse it outside of this class. * * @param screenX The screen x-coordinate * @param mouse_y The screen y-coordinate * @return The picking ray */ - public Ray getPickRay( int screenX, int screenY ) - { - return frustum.calculatePickRay( viewportWidth, viewportHeight, screenX, viewportHeight - screenY - 1, position, direction, up ); + public Ray getPickRay (int screenX, int screenY) { + return frustum.calculatePickRay(viewportWidth, viewportHeight, screenX, viewportHeight - screenY - 1, position, direction, + up); } - + /** - * Projects the given vector in world space to screen space, overwritting - * the x- and y-coordinate of the provided vector. + * Projects the given vector in world space to screen space, overwritting the x- and y-coordinate of the provided vector. * @param pos The vector to project */ - public void project( Vector3 pos ) - { - Matrix4 m = getCombinedMatrix(); - pos.prj( m ); - pos.x = viewportWidth * ( pos.x + 1 ) / 2; - pos.y = viewportHeight * ( pos.y + 1 ) / 2; + public void project (Vector3 pos) { + Matrix4 m = getCombinedMatrix(); + pos.prj(m); + pos.x = viewportWidth * (pos.x + 1) / 2; + pos.y = viewportHeight * (pos.y + 1) / 2; } } diff --git a/gdx/src/com/badlogic/gdx/graphics/Pixmap.java b/gdx/src/com/badlogic/gdx/graphics/Pixmap.java index e5e477185..aa59d5f93 100644 --- a/gdx/src/com/badlogic/gdx/graphics/Pixmap.java +++ b/gdx/src/com/badlogic/gdx/graphics/Pixmap.java @@ -1,48 +1,38 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics; /** - * A Pixmap represents a plattform specific bitmap. On Android it - * encapsulates a Bitmap on the desktop it encapsulates a BufferedImage. - * Various methods are available to manipulate the Pixmap. This uses - * the common bitmap coordinate system with the origin being in the - * top left corner and the y-axis pointing downwards. Bitmaps can - * be disposed to free all related resources. Use after disposing - * will result in nasty exceptions. + * A Pixmap represents a plattform specific bitmap. On Android it encapsulates a Bitmap on the desktop it encapsulates a + * BufferedImage. Various methods are available to manipulate the Pixmap. This uses the common bitmap coordinate system with the + * origin being in the top left corner and the y-axis pointing downwards. Bitmaps can be disposed to free all related resources. + * Use after disposing will result in nasty exceptions. * * @author badlogicgames@gmail.com - * + * */ -public interface Pixmap -{ +public interface Pixmap { /** * Different pixel formats. * * @author mzechner - * - */ - public enum Format - { - Alpha, - RGB565, - RGBA4444, - RGBA8888 + * + */ + public enum Format { + Alpha, RGB565, RGBA4444, RGBA8888 } - + /** * Sets the color for the following drawing operations. * @@ -51,20 +41,20 @@ public interface Pixmap * @param b The blue component. * @param a The alpha component. */ - public void setColor( float r, float g, float b, float a ); - + public void setColor (float r, float g, float b, float a); + /** * Fills the complete bitmap with the currently set color. */ - public void fill( ); - + public void fill (); + /** * Sets the width in pixels of strokes. * * @param width The stroke width in pixels. */ - public void setStrokeWidth( int width ); - + public void setStrokeWidth (int width); + /** * Draws a line between the given coordinates using the currently set color and stroke width. * @param x The x-coodinate of the first point @@ -72,20 +62,19 @@ public interface Pixmap * @param x2 The x-coordinate of the first point * @param y2 The y-coordinate of the first point */ - public void drawLine( int x, int y, int x2, int y2 ); - + public void drawLine (int x, int y, int x2, int y2); + /** - * Draws a rectangle outline starting at x, y extending by width to the right - * and by height downwards (y-axis points downwards) using the current color - * and stroke width. + * Draws a rectangle outline starting at x, y extending by width to the right and by height downwards (y-axis points downwards) + * using the current color and stroke width. * * @param x The x coordinate * @param y The y coordinate * @param width The width in pixels * @param height The height in pixels */ - public void drawRectangle( int x, int y, int width, int height ); - + public void drawRectangle (int x, int y, int width, int height); + /** * Draws an area form another Pixmap to this Pixmap. * @@ -97,74 +86,70 @@ public interface Pixmap * @param width The width of the area form the other Pixmap in pixels * @param height The height of the area form the other Pixmap in pixles */ - public void drawPixmap( Pixmap Pixmap, int x, int y, int srcx, int srcy, int width, int height ); - - + public void drawPixmap (Pixmap Pixmap, int x, int y, int srcx, int srcy, int width, int height); + /** - * Fills a rectangle starting at x, y extending by width to the right - * and by height downwards (y-axis points downwards) using the current color. + * Fills a rectangle starting at x, y extending by width to the right and by height downwards (y-axis points downwards) using + * the current color. * @param x The x coordinate * @param y The y coordinate * @param width The width in pixels * @param height The height in pixels */ - public void fillRectangle( int x, int y, int width, int height ); - + public void fillRectangle (int x, int y, int width, int height); + /** - * Draws a circle outline with the center at x,y and a radius using the - * current color and stroke width. + * Draws a circle outline with the center at x,y and a radius using the current color and stroke width. * - * @param x The x-coordinate of the center + * @param x The x-coordinate of the center * @param y The y-coordinate of the center * @param radius The radius in pixels */ - public void drawCircle( int x, int y, int radius ); - + public void drawCircle (int x, int y, int radius); + /** - * Fills a circle with the center at x,y and a radius using the - * current color. + * Fills a circle with the center at x,y and a radius using the current color. * - * @param x The x-coordinate of the center + * @param x The x-coordinate of the center * @param y The y-coordinate of the center * @param radius The radius in pixels */ - public void fillCircle( int x, int y, int radius ); - + public void fillCircle (int x, int y, int radius); + /** * Returns the 32-bit argb value of the pixel at x, y * @param x The x-coordinate * @param y The y-coordinate * @return The pixel color in 32-bit argb format. */ - public int getPixel( int x, int y ); - + public int getPixel (int x, int y); + /** - * Returns the yth row of pixels form the Pixmap in the provided - * pixels array. The pixels array must have at least Pixmap.getWidth() - * elements. The values are returned as 32-bit argb values. + * Returns the yth row of pixels form the Pixmap in the provided pixels array. The pixels array must have at least + * Pixmap.getWidth() elements. The values are returned as 32-bit argb values. * * @param pixels The array to store the pixels in. * @param y The y-coordinate of the row. */ - public void getPixelRow( int[] pixels, int y ); - + public void getPixelRow (int[] pixels, int y); + /** * @return The native bitmap object that backs this interface, Bitmap on Android, BufferedImage on PC */ - public Object getNativePixmap( ); + public Object getNativePixmap (); /** * @return The width of the Pixmap in pixels. */ - public int getWidth(); + public int getWidth (); /** * @return The height of the Pixmap in pixels. */ - public int getHeight( ); - + public int getHeight (); + /** * Releases all resources associated with this Pixmap. */ - public void dispose( ); + public void dispose (); } diff --git a/gdx/src/com/badlogic/gdx/graphics/ShaderProgram.java b/gdx/src/com/badlogic/gdx/graphics/ShaderProgram.java index 070cb9ac1..d921fff7b 100644 --- a/gdx/src/com/badlogic/gdx/graphics/ShaderProgram.java +++ b/gdx/src/com/badlogic/gdx/graphics/ShaderProgram.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics; import java.nio.ByteBuffer; @@ -27,20 +25,16 @@ import com.badlogic.gdx.math.Matrix4; /** *

- * A shader program encapsulates a vertex and fragment shader - * pair linked to form a shader program useable with OpenGL ES 2.0. + * A shader program encapsulates a vertex and fragment shader pair linked to form a shader program useable with OpenGL ES 2.0. *

* *

- * After construction a ShaderProgram can be used to draw {@link Meshes} - * or sprites via a {@link SpriteBatch}. To make the GPU use a specific - * ShaderProgram the programs {@link ShaderProgram.begin()} method must be - * used which effectively binds the program. + * After construction a ShaderProgram can be used to draw {@link Meshes} or sprites via a {@link SpriteBatch}. To make the GPU use + * a specific ShaderProgram the programs {@link ShaderProgram.begin()} method must be used which effectively binds the program. *

* *

- * When a ShaderProgram is bound one can set uniforms, vertex attributes - * and attributes as needed via the respective methods. + * When a ShaderProgram is bound one can set uniforms, vertex attributes and attributes as needed via the respective methods. *

* *

@@ -48,500 +42,446 @@ import com.badlogic.gdx.math.Matrix4; *

* *

- * A ShaderProgram must be disposed via a call to {@link ShaderProgram.dispose()} when - * it is no longer needed + * A ShaderProgram must be disposed via a call to {@link ShaderProgram.dispose()} when it is no longer needed *

* *

- * ShaderPrograms are managed. In case the OpenGL context is lost all shaders get - * invalidated and have to be reloaded. This happens on Android when a user switches - * to another application or receives an incoming call. Managed ShaderPrograms are - * automatically reloaded when the OpenGL context is recreated so you don't have to - * do this manually. + * ShaderPrograms are managed. In case the OpenGL context is lost all shaders get invalidated and have to be reloaded. This + * happens on Android when a user switches to another application or receives an incoming call. Managed ShaderPrograms are + * automatically reloaded when the OpenGL context is recreated so you don't have to do this manually. *

* * @author mzechner - * + * */ -public class ShaderProgram -{ +public class ShaderProgram { /** the list of currently available shaders **/ - private final static ArrayList shaders = new ArrayList( ); + private final static ArrayList shaders = new ArrayList(); /** the log **/ private String log = ""; - + /** whether this program compiled succesfully **/ private boolean isCompiled; - + /** uniform lookup **/ private final HashMap uniforms = new HashMap(); - + /** attribute lookup **/ - private final HashMap attributes = new HashMap( ); + private final HashMap attributes = new HashMap(); /** program handle **/ private int program; - + /** vertex shader handle **/ private int vertexShaderHandle; - + /** fragment shader handle **/ private int fragmentShaderHandle; - + /** matrix float buffer **/ private final FloatBuffer matrix; - + /** managed? **/ private final boolean managed; - + /** vertex shader source **/ private final String vertexShaderSource; - + /** fragment shader source **/ private final String fragmentShaderSource; - + /** whether this shader was invalidated **/ private boolean invalidated; - + /** - * Construcs a new JOglShaderProgram and immediatly compiles it. + * Construcs a new JOglShaderProgram and immediatly compiles it. * * @param gl the GL20 instance * @param vertexShader the vertex shader * @param fragmentShader the fragment shader */ - - public ShaderProgram( String vertexShader, String fragmentShader ) - { - if( vertexShader == null ) - throw new IllegalArgumentException( "vertex shader must not be null" ); - if( fragmentShader == null ) - throw new IllegalArgumentException( "fragment shader must not be null" ); - + + public ShaderProgram (String vertexShader, String fragmentShader) { + if (vertexShader == null) throw new IllegalArgumentException("vertex shader must not be null"); + if (fragmentShader == null) throw new IllegalArgumentException("fragment shader must not be null"); + this.managed = true; this.vertexShaderSource = vertexShader; this.fragmentShaderSource = fragmentShader; - - compileShaders( vertexShader, fragmentShader ); - - ByteBuffer buffer = ByteBuffer.allocateDirect( 4 * 16 ); + + compileShaders(vertexShader, fragmentShader); + + ByteBuffer buffer = ByteBuffer.allocateDirect(4 * 16); buffer.order(ByteOrder.nativeOrder()); matrix = buffer.asFloatBuffer(); - if( managed ) - shaders.add( this ); + if (managed) shaders.add(this); } - + /** * Loads and compiles the shaders, creates a new program and links the shaders. * @param vertexShader * @param fragmentShader */ - private void compileShaders( String vertexShader, String fragmentShader ) - { - vertexShaderHandle = loadShader( GL20.GL_VERTEX_SHADER, vertexShader ); - fragmentShaderHandle = loadShader( GL20.GL_FRAGMENT_SHADER, fragmentShader ); - - if( vertexShaderHandle == -1 || fragmentShaderHandle == -1 ) - { + private void compileShaders (String vertexShader, String fragmentShader) { + vertexShaderHandle = loadShader(GL20.GL_VERTEX_SHADER, vertexShader); + fragmentShaderHandle = loadShader(GL20.GL_FRAGMENT_SHADER, fragmentShader); + + if (vertexShaderHandle == -1 || fragmentShaderHandle == -1) { isCompiled = false; return; } - - program = linkProgram( ); - if( program == -1 ) - { + + program = linkProgram(); + if (program == -1) { isCompiled = false; return; } - + isCompiled = true; } - - private int loadShader( int type, String source ) - { + + private int loadShader (int type, String source) { GL20 gl = Gdx.graphics.getGL20(); ByteBuffer tmp = ByteBuffer.allocateDirect(4); tmp.order(ByteOrder.nativeOrder()); IntBuffer intbuf = tmp.asIntBuffer(); - - int shader = gl.glCreateShader( type ); - if( shader == 0 ) - return -1; - - gl.glShaderSource( shader, source ); - gl.glCompileShader( shader ); - gl.glGetShaderiv( shader, GL20.GL_COMPILE_STATUS, intbuf ); - + + int shader = gl.glCreateShader(type); + if (shader == 0) return -1; + + gl.glShaderSource(shader, source); + gl.glCompileShader(shader); + gl.glGetShaderiv(shader, GL20.GL_COMPILE_STATUS, intbuf); + int compiled = intbuf.get(0); - if( compiled == 0 ) - { - gl.glGetShaderiv( shader, GL20.GL_INFO_LOG_LENGTH, intbuf ); + if (compiled == 0) { + gl.glGetShaderiv(shader, GL20.GL_INFO_LOG_LENGTH, intbuf); int infoLogLength = intbuf.get(0); - if( infoLogLength > 1 ) - { - String infoLog = gl.glGetShaderInfoLog( shader ); + if (infoLogLength > 1) { + String infoLog = gl.glGetShaderInfoLog(shader); log += infoLog; } return -1; } - + return shader; } - - private int linkProgram( ) - { + + private int linkProgram () { GL20 gl = Gdx.graphics.getGL20(); int program = gl.glCreateProgram(); - if( program == 0 ) - return -1; - - gl.glAttachShader( program, vertexShaderHandle ); - gl.glAttachShader( program, fragmentShaderHandle ); - gl.glLinkProgram( program ); - + if (program == 0) return -1; + + gl.glAttachShader(program, vertexShaderHandle); + gl.glAttachShader(program, fragmentShaderHandle); + gl.glLinkProgram(program); + ByteBuffer tmp = ByteBuffer.allocateDirect(4); tmp.order(ByteOrder.nativeOrder()); IntBuffer intbuf = tmp.asIntBuffer(); - - gl.glGetProgramiv( program, GL20.GL_LINK_STATUS, intbuf ); + + gl.glGetProgramiv(program, GL20.GL_LINK_STATUS, intbuf); int linked = intbuf.get(0); - if( linked == 0 ) - { - gl.glGetProgramiv( program, GL20.GL_INFO_LOG_LENGTH, intbuf ); + if (linked == 0) { + gl.glGetProgramiv(program, GL20.GL_INFO_LOG_LENGTH, intbuf); int infoLogLength = intbuf.get(0); - if( infoLogLength > 1 ) - log += gl.glGetProgramInfoLog( program ); - + if (infoLogLength > 1) log += gl.glGetProgramInfoLog(program); + return -1; } - + return program; } - + /** - * @return the log info for the shader compilation and program linking stage. Returns an empty string if the shader program compiled successfully. - */ - public String getLog() - { + * @return the log info for the shader compilation and program linking stage. Returns an empty string if the shader program + * compiled successfully. + */ + public String getLog () { return log; } /** * @return whether this ShaderProgram compiled successfully. - */ - public boolean isCompiled() - { + */ + public boolean isCompiled () { return isCompiled; } - private int fetchAttributeLocation( String name ) - { + private int fetchAttributeLocation (String name) { GL20 gl = Gdx.graphics.getGL20(); Integer location; - if( (location = attributes.get( name )) == null ) - { - location = gl.glGetAttribLocation( program, name ); - if( location != - 1 ) - attributes.put( name, location ); + if ((location = attributes.get(name)) == null) { + location = gl.glGetAttribLocation(program, name); + if (location != -1) attributes.put(name, location); } return location; } - - private int fetchUniformLocation( String name ) - { + + private int fetchUniformLocation (String name) { GL20 gl = Gdx.graphics.getGL20(); Integer location; - if( (location = uniforms.get( name )) == null ) - { - location = gl.glGetUniformLocation( program, name ); - if( location == - 1 ) - throw new IllegalArgumentException( "no uniform with name '" + name + "' in shader" ); - uniforms.put( name, location ); + if ((location = uniforms.get(name)) == null) { + location = gl.glGetUniformLocation(program, name); + if (location == -1) throw new IllegalArgumentException("no uniform with name '" + name + "' in shader"); + uniforms.put(name, location); } return location; } - + /** - * Sets the uniform with the given name. Throws an IllegalArgumentException in case - * it is not called in between a {@link begin()}/{@link end()} block. + * Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a {@link + * begin()}/{@link end()} block. * * @param name the name of the uniform * @param value the value - */ - public void setUniformi(String name, int value) - { + */ + public void setUniformi (String name, int value) { GL20 gl = Gdx.graphics.getGL20(); - checkManaged( ); - int location = fetchUniformLocation(name); - gl.glUniform1i( location, value ); + checkManaged(); + int location = fetchUniformLocation(name); + gl.glUniform1i(location, value); } /** - * Sets the uniform with the given name. Throws an IllegalArgumentException in case - * it is not called in between a {@link begin()}/{@link end()} block. + * Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a {@link + * begin()}/{@link end()} block. * * @param name the name of the uniform * @param value1 the first value - * @param value2 the second value + * @param value2 the second value */ - public void setUniformi(String name, int value1, int value2) - { + public void setUniformi (String name, int value1, int value2) { GL20 gl = Gdx.graphics.getGL20(); - checkManaged( ); + checkManaged(); int location = fetchUniformLocation(name); - gl.glUniform2i( location, value1, value2 ); + gl.glUniform2i(location, value1, value2); } /** - * Sets the uniform with the given name. Throws an IllegalArgumentException in case - * it is not called in between a {@link begin()}/{@link end()} block. + * Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a {@link + * begin()}/{@link end()} block. * * @param name the name of the uniform * @param value1 the first value * @param value2 the second value - * @param value3 the third value + * @param value3 the third value */ - public void setUniformi(String name, int value1, int value2, int value3) - { + public void setUniformi (String name, int value1, int value2, int value3) { GL20 gl = Gdx.graphics.getGL20(); - checkManaged( ); + checkManaged(); int location = fetchUniformLocation(name); - gl.glUniform3i( location, value1, value2, value3 ); + gl.glUniform3i(location, value1, value2, value3); } /** - * Sets the uniform with the given name. Throws an IllegalArgumentException in case - * it is not called in between a {@link begin()}/{@link end()} block. + * Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a {@link + * begin()}/{@link end()} block. * * @param name the name of the uniform * @param value1 the first value * @param value2 the second value - * @param value3 the third value + * @param value3 the third value * @param value4 the fourth value */ - public void setUniformi(String name, int value1, int value2, int value3, int value4) - { + public void setUniformi (String name, int value1, int value2, int value3, int value4) { GL20 gl = Gdx.graphics.getGL20(); - checkManaged( ); + checkManaged(); int location = fetchUniformLocation(name); - gl.glUniform4i( location, value1, value2, value3, value4 ); + gl.glUniform4i(location, value1, value2, value3, value4); } /** - * Sets the uniform with the given name. Throws an IllegalArgumentException in case - * it is not called in between a {@link begin()}/{@link end()} block. + * Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a {@link + * begin()}/{@link end()} block. * * @param name the name of the uniform * @param value the value - */ - public void setUniformf(String name, float value) - { + */ + public void setUniformf (String name, float value) { GL20 gl = Gdx.graphics.getGL20(); - checkManaged( ); + checkManaged(); int location = fetchUniformLocation(name); - gl.glUniform1f( location, value ); + gl.glUniform1f(location, value); } /** - * Sets the uniform with the given name. Throws an IllegalArgumentException in case - * it is not called in between a {@link begin()}/{@link end()} block. + * Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a {@link + * begin()}/{@link end()} block. * * @param name the name of the uniform * @param value1 the first value - * @param value2 the second value + * @param value2 the second value */ - public void setUniformf(String name, float value1, float value2) - { + public void setUniformf (String name, float value1, float value2) { GL20 gl = Gdx.graphics.getGL20(); - checkManaged( ); + checkManaged(); int location = fetchUniformLocation(name); - gl.glUniform2f( location, value1, value2 ); + gl.glUniform2f(location, value1, value2); } /** - * Sets the uniform with the given name. Throws an IllegalArgumentException in case - * it is not called in between a {@link begin()}/{@link end()} block. + * Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a {@link + * begin()}/{@link end()} block. * * @param name the name of the uniform * @param value1 the first value * @param value2 the second value - * @param value3 the third value + * @param value3 the third value */ - public void setUniformf(String name, float value1, float value2, float value3) - { + public void setUniformf (String name, float value1, float value2, float value3) { GL20 gl = Gdx.graphics.getGL20(); - checkManaged( ); + checkManaged(); int location = fetchUniformLocation(name); - gl.glUniform3f( location, value1, value2, value3 ); + gl.glUniform3f(location, value1, value2, value3); } /** - * Sets the uniform with the given name. Throws an IllegalArgumentException in case - * it is not called in between a {@link begin()}/{@link end()} block. + * Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a {@link + * begin()}/{@link end()} block. * * @param name the name of the uniform * @param value1 the first value * @param value2 the second value - * @param value3 the third value + * @param value3 the third value * @param value4 the fourth value */ - public void setUniformf(String name, float value1, float value2, float value3, float value4) - { + public void setUniformf (String name, float value1, float value2, float value3, float value4) { GL20 gl = Gdx.graphics.getGL20(); - checkManaged( ); + checkManaged(); int location = fetchUniformLocation(name); - gl.glUniform4f( location, value1, value2, value3, value4 ); + gl.glUniform4f(location, value1, value2, value3, value4); } /** - * Sets the uniform matrix with the given name. Throws an IllegalArgumentException in case - * it is not called in between a {@link begin()}/{@link end()} block. + * Sets the uniform matrix with the given name. Throws an IllegalArgumentException in case it is not called in between a + * {@link begin()}/{@link end()} block. * @param name the name of the uniform * @param matrix the matrix */ - public void setUniformMatrix(String name, Matrix4 matrix) - { + public void setUniformMatrix (String name, Matrix4 matrix) { GL20 gl = Gdx.graphics.getGL20(); - checkManaged( ); + checkManaged(); int location = fetchUniformLocation(name); - this.matrix.put( matrix.val ); + this.matrix.put(matrix.val); this.matrix.position(0); - gl.glUniformMatrix4fv(location, 1, false, this.matrix ); + gl.glUniformMatrix4fv(location, 1, false, this.matrix); } /** - * Sets the vertex attribute with the given name. Throws an IllegalArgumentException in case - * it is not called in between a {@link begin()}/{@link end()} block. + * Sets the vertex attribute with the given name. Throws an IllegalArgumentException in case it is not called in between a + * {@link begin()}/{@link end()} block. * * @param name the attribute name * @param size the number of components, must be >= 1 and <= 4 - * @param type the type, must be one of GL20.GL_BYTE, GL20.GL_UNSIGNED_BYTE, GL20.GL_SHORT, GL20.GL_UNSIGNED_SHORT,GL20.GL_FIXED, or GL20.GL_FLOAT. GL_FIXED will not work on the desktop + * @param type the type, must be one of GL20.GL_BYTE, GL20.GL_UNSIGNED_BYTE, GL20.GL_SHORT, + * GL20.GL_UNSIGNED_SHORT,GL20.GL_FIXED, or GL20.GL_FLOAT. GL_FIXED will not work on the desktop * @param normalize whether fixed point data should be normalized. Will not work on the desktop * @param stride the stride in bytes between successive attributes * @param buffer the buffer containing the vertex attributes. */ - public void setVertexAttribute(String name, int size, int type, boolean normalize, int stride, FloatBuffer buffer) - { + public void setVertexAttribute (String name, int size, int type, boolean normalize, int stride, FloatBuffer buffer) { GL20 gl = Gdx.graphics.getGL20(); - checkManaged( ); + checkManaged(); int location = fetchAttributeLocation(name); - gl.glVertexAttribPointer( location, size, type, normalize, stride, buffer ); + gl.glVertexAttribPointer(location, size, type, normalize, stride, buffer); } /** - * Sets the vertex attribute with the given name. Throws an IllegalArgumentException in case - * it is not called in between a {@link begin()}/{@link end()} block. + * Sets the vertex attribute with the given name. Throws an IllegalArgumentException in case it is not called in between a + * {@link begin()}/{@link end()} block. * * @param name the attribute name * @param size the number of components, must be >= 1 and <= 4 - * @param type the type, must be one of GL20.GL_BYTE, GL20.GL_UNSIGNED_BYTE, GL20.GL_SHORT, GL20.GL_UNSIGNED_SHORT,GL20.GL_FIXED, or GL20.GL_FLOAT. GL_FIXED will not work on the desktop + * @param type the type, must be one of GL20.GL_BYTE, GL20.GL_UNSIGNED_BYTE, GL20.GL_SHORT, + * GL20.GL_UNSIGNED_SHORT,GL20.GL_FIXED, or GL20.GL_FLOAT. GL_FIXED will not work on the desktop * @param normalize whether fixed point data should be normalized. Will not work on the desktop * @param stride the stride in bytes between successive attributes * @param offset byte offset into the vertex buffer object bound to GL20.GL_ARRAY_BUFFER. */ - public void setVertexAttribute(String name, int size, int type, boolean normalize, int stride, int offset) - { + public void setVertexAttribute (String name, int size, int type, boolean normalize, int stride, int offset) { GL20 gl = Gdx.graphics.getGL20(); - checkManaged( ); + checkManaged(); int location = fetchAttributeLocation(name); - if( location == -1 ) - return; - gl.glVertexAttribPointer( location, size, type, normalize, stride, offset ); + if (location == -1) return; + gl.glVertexAttribPointer(location, size, type, normalize, stride, offset); } - + /** - * Makes OpenGL ES 2.0 use this vertex and fragment - * shader pair. When you are done with this shader you - * have to call {@link ShaderProgram.end()}. + * Makes OpenGL ES 2.0 use this vertex and fragment shader pair. When you are done with this shader you have to call {@link + * ShaderProgram.end()}. */ - public void begin() - { + public void begin () { GL20 gl = Gdx.graphics.getGL20(); - checkManaged( ); - gl.glUseProgram( program ); + checkManaged(); + gl.glUseProgram(program); } /** - * Disables this shader. Must be called when one is done - * with the shader. Don't mix it with dispose, that will - * release the shader resources. + * Disables this shader. Must be called when one is done with the shader. Don't mix it with dispose, that will release the + * shader resources. */ - public void end() - { + public void end () { GL20 gl = Gdx.graphics.getGL20(); - gl.glUseProgram( 0 ); + gl.glUseProgram(0); } - + /** - * Disposes all resources associated with this shader. Must be - * called when the shader is no longer used. + * Disposes all resources associated with this shader. Must be called when the shader is no longer used. */ - public void dispose() - { + public void dispose () { GL20 gl = Gdx.graphics.getGL20(); gl.glDeleteShader(vertexShaderHandle); gl.glDeleteShader(fragmentShaderHandle); - gl.glDeleteProgram( program ); - shaders.remove( this ); + gl.glDeleteProgram(program); + shaders.remove(this); } /** * Disables the vertex attribute with the given name * @param name the vertex attribute name */ - public void disableVertexAttribute(String name) - { + public void disableVertexAttribute (String name) { GL20 gl = Gdx.graphics.getGL20(); - checkManaged( ); - int location = fetchAttributeLocation( name ); - if( location == -1 ) - return; - gl.glDisableVertexAttribArray( location ); + checkManaged(); + int location = fetchAttributeLocation(name); + if (location == -1) return; + gl.glDisableVertexAttribArray(location); } /** * Enables the vertex attribute with the given name * @param name the vertex attribute name */ - public void enableVertexAttribute(String name) - { + public void enableVertexAttribute (String name) { GL20 gl = Gdx.graphics.getGL20(); - checkManaged( ); - int location = fetchAttributeLocation( name ); - if( location == -1 ) - return; - gl.glEnableVertexAttribArray( location ); + checkManaged(); + int location = fetchAttributeLocation(name); + if (location == -1) return; + gl.glEnableVertexAttribArray(location); } - - private void checkManaged( ) - { - if( !managed ) - return; - - if( invalidated ) - compileShaders(vertexShaderSource, fragmentShaderSource ); + + private void checkManaged () { + if (!managed) return; + + if (invalidated) compileShaders(vertexShaderSource, fragmentShaderSource); invalidated = false; } - + /** - * Invalidates all shaders so the next time they are used - * new handles are generated + * Invalidates all shaders so the next time they are used new handles are generated */ - public static void invalidateAllShaderPrograms( ) - { - if( Gdx.graphics.getGL20() == null ) - return; - - for( int i = 0; i < shaders.size(); i++ ) - { + public static void invalidateAllShaderPrograms () { + if (Gdx.graphics.getGL20() == null) return; + + for (int i = 0; i < shaders.size(); i++) { shaders.get(i).invalidated = true; shaders.get(i).checkManaged(); } } - - public static void clearAllShaderPrograms( ) - { + + public static void clearAllShaderPrograms () { shaders.clear(); } @@ -551,13 +491,12 @@ public class ShaderProgram * @param name the name of the attribute * @param value1 the first value * @param value2 the second value - * @param value3 the third value + * @param value3 the third value * @param value4 the fourth value */ - public void setAttributef(String name, float value1, float value2, float value3, float value4 ) - { + public void setAttributef (String name, float value1, float value2, float value3, float value4) { GL20 gl = Gdx.graphics.getGL20(); - int location = fetchAttributeLocation( name ); - gl.glVertexAttrib4f( location, value1, value2, value3, value4 ); + int location = fetchAttributeLocation(name); + gl.glVertexAttrib4f(location, value1, value2, value3, value4); } } diff --git a/gdx/src/com/badlogic/gdx/graphics/SpriteBatch.java b/gdx/src/com/badlogic/gdx/graphics/SpriteBatch.java index 075db2a11..461317152 100644 --- a/gdx/src/com/badlogic/gdx/graphics/SpriteBatch.java +++ b/gdx/src/com/badlogic/gdx/graphics/SpriteBatch.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics; import com.badlogic.gdx.Gdx; @@ -24,30 +22,25 @@ import com.badlogic.gdx.utils.MathUtils; /** *

- * A SpriteBatch is used to draw 2D rectangles that reference a - * texture (region). The class will batch the drawing commands and optimize - * them for processing by the GPU. + * A SpriteBatch is used to draw 2D rectangles that reference a texture (region). The class will batch the drawing commands and + * optimize them for processing by the GPU. *

* *

- * To draw something with a SpriteBatch one has to first call the - * {@link SpriteBatch.begin()} method which will setup appropriate - * render states. When you are done with drawing you have to call - * {@link SpriteBatch.end()} which will actually draw the things you - * specified. + * To draw something with a SpriteBatch one has to first call the {@link SpriteBatch.begin()} method which will setup appropriate + * render states. When you are done with drawing you have to call {@link SpriteBatch.end()} which will actually draw the things + * you specified. *

* *

- * All drawing commands of the SpriteBatch operate in screen coordinates. - * The screen coordinate system has an x-axis pointing to the right, an - * y-axis pointing upwards and the origin is in the lower left corner of - * the screen. You can also provide your own transformation and projection - * matrices if you so wish. + * All drawing commands of the SpriteBatch operate in screen coordinates. The screen coordinate system has an x-axis pointing to + * the right, an y-axis pointing upwards and the origin is in the lower left corner of the screen. You can also provide your own + * transformation and projection matrices if you so wish. *

* *

- * A sprite rendered via this batch has an origin relative to it's - * top left corner and a position in screen coordinates for that origin. + * A sprite rendered via this batch has an origin relative to it's top left corner and a position in screen coordinates for that + * origin. *

* *

@@ -57,7 +50,7 @@ import com.badlogic.gdx.utils.MathUtils; *

* A sprite can be scaled on the x and y axis. *

- * + * *

* A sprite can be rotated around the origin by some angle. *

@@ -66,10 +59,10 @@ import com.badlogic.gdx.utils.MathUtils; * A sprite references a portion of a texture where the portion is specified in texels. *

* - *

A SpriteBatch can be managed. In case the OpenGL context is lost all OpenGL resources - * a SpriteBatch uses internally get invalidated. A context is lost when a user switches to - * another application or receives an incoming call. A managed SpriteBatch will be automatically - * reloaded after the OpenGL context is restored. + *

+ * A SpriteBatch can be managed. In case the OpenGL context is lost all OpenGL resources a SpriteBatch uses internally get + * invalidated. A context is lost when a user switches to another application or receives an incoming call. A managed SpriteBatch + * will be automatically reloaded after the OpenGL context is restored. *

* *

@@ -77,9 +70,8 @@ import com.badlogic.gdx.utils.MathUtils; *

* *

- * A SpriteBatch works with OpenGL ES 1.x and 2.0. In the case of a 2.0 context it will use - * its own custom shader to draw all provided sprites. Specifying your own shader does not work - * (yet). + * A SpriteBatch works with OpenGL ES 1.x and 2.0. In the case of a 2.0 context it will use its own custom shader to draw all + * provided sprites. Specifying your own shader does not work (yet). *

* *

@@ -87,230 +79,196 @@ import com.badlogic.gdx.utils.MathUtils; *

* * @author mzechner - * + * */ -public class SpriteBatch -{ +public class SpriteBatch { private static final int VERTEX_SIZE = 2 + 1 + 2; private static final int SPRITE_SIZE = 4 * VERTEX_SIZE; - + /** the mesh used to transfer the data to the GPU **/ private final Mesh mesh; - + /** the transform to be applied to all sprites **/ protected final Matrix4 transformMatrix = new Matrix4(); - + /** the view matrix holding the orthogonal projection **/ protected final Matrix4 projectionMatrix = new Matrix4(); - + /** the combined transform and view matrix **/ - protected final Matrix4 combinedMatrix = new Matrix4( ); - + protected final Matrix4 combinedMatrix = new Matrix4(); + /** the vertex storage **/ protected final float[] vertices; - + /** last texture **/ protected Texture lastTexture = null; - + /** current index into vertices **/ protected int idx = 0; - + /** drawing flag **/ protected boolean drawing = false; - + /** inverse texture width and height **/ protected float invTexWidth = 0; protected float invTexHeight = 0; - + /** whether to use the blend mode for text or for sprites **/ protected boolean useTextBlend = false; - + /** blend function src & target **/ private int blendSrcFunc = GL11.GL_SRC_ALPHA; private int blendDstFunc = GL11.GL_ONE_MINUS_SRC_ALPHA; - + /** the shader for opengl 2.0 **/ protected ShaderProgram shader; - + /** number of render calls **/ public int renderCalls = 0; /** whether blending is enabled or not **/ - protected boolean blendingDisabled=false; - + protected boolean blendingDisabled = false; + /** - * Constructs a new SpriteBatch. Sets the projection matrix to an orthographic projection - * with y-axis point upwards, x-axis point to the right and the origin being in the bottome - * left corner of the screen. The projection will be pixel perfect with respect to the - * screen resolution. + * Constructs a new SpriteBatch. Sets the projection matrix to an orthographic projection with y-axis point upwards, x-axis + * point to the right and the origin being in the bottome left corner of the screen. The projection will be pixel perfect with + * respect to the screen resolution. */ - public SpriteBatch( ) - { - this( 1000 ); + public SpriteBatch () { + this(1000); } /** - *

Constructs a new SpriteBatch. Sets the projection matrix to an orthographic projection - * with y-axis point upwards, x-axis point to the right and the origin being in the bottome - * left corner of the screen. The projection will be pixel perfect with respect to the - * screen resolution.

+ *

+ * Constructs a new SpriteBatch. Sets the projection matrix to an orthographic projection with y-axis point upwards, x-axis + * point to the right and the origin being in the bottome left corner of the screen. The projection will be pixel perfect with + * respect to the screen resolution. + *

* - *

The size parameter specifies the maximum size of a single batch in number of sprites

+ *

+ * The size parameter specifies the maximum size of a single batch in number of sprites + *

* * @param size the batch size in number of sprites */ - public SpriteBatch( int size ) - { - this.mesh = new Mesh( false, false, size * 4, size * 6, - new VertexAttribute( Usage.Position, 2, "a_position" ), - new VertexAttribute( Usage.ColorPacked, 4, "a_color" ), - new VertexAttribute( Usage.TextureCoordinates, 2, "a_texCoords" ) ); - projectionMatrix.setToOrtho2D( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - + public SpriteBatch (int size) { + this.mesh = new Mesh(false, false, size * 4, size * 6, new VertexAttribute(Usage.Position, 2, "a_position"), + new VertexAttribute(Usage.ColorPacked, 4, "a_color"), new VertexAttribute(Usage.TextureCoordinates, 2, "a_texCoords")); + projectionMatrix.setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + vertices = new float[size * SPRITE_SIZE]; - - short[] indices = new short[size*6]; + + short[] indices = new short[size * 6]; int len = size * 6; short j = 0; - for( int i = 0; i < len; i+=6, j+=4 ) - { - indices[i+0] = (short)(j + 0); - indices[i+1] = (short)(j + 1); - indices[i+2] = (short)(j + 2); - indices[i+3] = (short)(j + 2); - indices[i+4] = (short)(j + 3); - indices[i+5] = (short)(j + 0); + for (int i = 0; i < len; i += 6, j += 4) { + indices[i + 0] = (short)(j + 0); + indices[i + 1] = (short)(j + 1); + indices[i + 2] = (short)(j + 2); + indices[i + 3] = (short)(j + 2); + indices[i + 4] = (short)(j + 3); + indices[i + 5] = (short)(j + 0); } - mesh.setIndices( indices ); - - if( Gdx.graphics.isGL20Available() ) - createShader( ); + mesh.setIndices(indices); + + if (Gdx.graphics.isGL20Available()) createShader(); } - - private void createShader( ) - { - String vertexShader = "attribute vec4 a_position; \n" + - "attribute vec4 a_color; \n" + - "attribute vec2 a_texCoords; \n" + - "uniform mat4 u_projectionViewMatrix; \n" + - "varying vec4 v_color; \n" + - "varying vec2 v_texCoords; \n" + - " \n" + - "void main() \n" + - "{ \n" + - " v_color = a_color; \n" + - " v_texCoords = a_texCoords; \n" + - " gl_Position = u_projectionViewMatrix * a_position; \n" + - "} \n"; - String fragmentShader = "precision mediump float;\n" + - "varying vec4 v_color;\n" + - "varying vec2 v_texCoords;\n" + - "uniform sampler2D u_texture;\n" + - "void main() \n" + - "{ \n" + - " gl_FragColor = v_color * texture2D(u_texture, v_texCoords); \n" + - "}"; - - shader = new ShaderProgram( vertexShader, fragmentShader ); - if( shader.isCompiled() == false ) - throw new IllegalArgumentException( "couldn't compile shader: " + shader.getLog() ); + + private void createShader () { + String vertexShader = "attribute vec4 a_position; \n" + "attribute vec4 a_color; \n" + "attribute vec2 a_texCoords; \n" + + "uniform mat4 u_projectionViewMatrix; \n" + "varying vec4 v_color; \n" + "varying vec2 v_texCoords; \n" + " \n" + + "void main() \n" + "{ \n" + " v_color = a_color; \n" + + " v_texCoords = a_texCoords; \n" + " gl_Position = u_projectionViewMatrix * a_position; \n" + "} \n"; + String fragmentShader = "precision mediump float;\n" + "varying vec4 v_color;\n" + "varying vec2 v_texCoords;\n" + + "uniform sampler2D u_texture;\n" + "void main() \n" + + "{ \n" + " gl_FragColor = v_color * texture2D(u_texture, v_texCoords); \n" + + "}"; + + shader = new ShaderProgram(vertexShader, fragmentShader); + if (shader.isCompiled() == false) throw new IllegalArgumentException("couldn't compile shader: " + shader.getLog()); } - + /** - * Sets up the SpriteBatch for drawing. This will disable - * depth buffer testing and writting, culling and lighting. - * It enables blending and alpha testing. If you have more texture units enabled than - * the first one you have to disable them before calling this. Applies - * the given transformation {@link Matrix4} to all subsequently specified sprites. Uses - * the provided projection matrix and therefore does not necessarily work - * in screen coordinates anymore. You have to know what you do if you use this. + * Sets up the SpriteBatch for drawing. This will disable depth buffer testing and writting, culling and lighting. It enables + * blending and alpha testing. If you have more texture units enabled than the first one you have to disable them before + * calling this. Applies the given transformation {@link Matrix4} to all subsequently specified sprites. Uses the provided + * projection matrix and therefore does not necessarily work in screen coordinates anymore. You have to know what you do if you + * use this. * * @param projection the projection matrix; * @param transform the transformation matrix. */ - public void begin( ) - { + public void begin () { renderCalls = 0; - - if( Gdx.graphics.isGL20Available() == false ) - { + + if (Gdx.graphics.isGL20Available() == false) { GL10 gl = Gdx.graphics.getGL10(); - gl.glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - gl.glDisable( GL10.GL_LIGHTING ); - gl.glDisable( GL10.GL_DEPTH_TEST ); - gl.glDisable( GL10.GL_CULL_FACE ); - gl.glDepthMask ( false ); - - gl.glEnable( GL10.GL_TEXTURE_2D ); - //gl.glActiveTexture( GL10.GL_TEXTURE0 ); - - gl.glMatrixMode( GL10.GL_PROJECTION ); - gl.glLoadMatrixf( projectionMatrix.val, 0 ); - gl.glMatrixMode( GL10.GL_MODELVIEW ); - gl.glLoadMatrixf( transformMatrix.val, 0 ); - } - else - { + gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + gl.glDisable(GL10.GL_LIGHTING); + gl.glDisable(GL10.GL_DEPTH_TEST); + gl.glDisable(GL10.GL_CULL_FACE); + gl.glDepthMask(false); + + gl.glEnable(GL10.GL_TEXTURE_2D); + // gl.glActiveTexture( GL10.GL_TEXTURE0 ); + + gl.glMatrixMode(GL10.GL_PROJECTION); + gl.glLoadMatrixf(projectionMatrix.val, 0); + gl.glMatrixMode(GL10.GL_MODELVIEW); + gl.glLoadMatrixf(transformMatrix.val, 0); + } else { combinedMatrix.set(projectionMatrix).mul(transformMatrix); GL20 gl = Gdx.graphics.getGL20(); - gl.glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - gl.glDisable( GL20.GL_DEPTH_TEST ); - gl.glDisable( GL20.GL_CULL_FACE ); - gl.glDepthMask ( false ); + gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + gl.glDisable(GL20.GL_DEPTH_TEST); + gl.glDisable(GL20.GL_CULL_FACE); + gl.glDepthMask(false); - gl.glEnable( GL20.GL_TEXTURE_2D ); - //gl.glActiveTexture( GL20.GL_TEXTURE0 ); + gl.glEnable(GL20.GL_TEXTURE_2D); + // gl.glActiveTexture( GL20.GL_TEXTURE0 ); shader.begin(); - shader.setUniformMatrix( "u_projectionViewMatrix", combinedMatrix ); - shader.setUniformi( "u_texture", 0 ); + shader.setUniformMatrix("u_projectionViewMatrix", combinedMatrix); + shader.setUniformi("u_texture", 0); } - + idx = 0; lastTexture = null; drawing = true; } - - + /** * Finishes off rendering of the last batch of sprites */ - public void end( ) - { - if( idx > 0 ) - renderMesh(); + public void end () { + if (idx > 0) renderMesh(); lastTexture = null; idx = 0; drawing = false; - - if( Gdx.graphics.isGL20Available() == false ) - { + + if (Gdx.graphics.isGL20Available() == false) { GL10 gl = Gdx.graphics.getGL10(); - gl.glDepthMask ( true ); - gl.glDisable( GL10.GL_BLEND ); - gl.glDisable( GL10.GL_TEXTURE_2D ); - } - else - { + gl.glDepthMask(true); + gl.glDisable(GL10.GL_BLEND); + gl.glDisable(GL10.GL_TEXTURE_2D); + } else { shader.end(); GL20 gl = Gdx.graphics.getGL20(); - gl.glDepthMask ( true ); - gl.glDisable( GL20.GL_BLEND ); - gl.glDisable( GL20.GL_TEXTURE_2D ); + gl.glDepthMask(true); + gl.glDisable(GL20.GL_BLEND); + gl.glDisable(GL20.GL_TEXTURE_2D); } - } - + } + /** - * Draws a rectangle with the top left corner at x,y having - * the given width and height in pixels. The rectangle is offset by originX, originY relative to the - * origin. Scale specifies the scaling factor by which the rectangle should be scaled around originX,originY. - * Rotation specifies the angle of counter clockwise rotation of the rectangle around originX, originY. - * The portion of the {@link Texture} - * given by srcX, srcY and srcWidth, srcHeight is used. These coordinates and - * sizes are given in texels. The rectangle will have the given tint {@link Color}. FlipX - * and flipY specify whether the texture portion should be fliped horizontally or vertically. - * + * Draws a rectangle with the top left corner at x,y having the given width and height in pixels. The rectangle is offset by + * originX, originY relative to the origin. Scale specifies the scaling factor by which the rectangle should be scaled around + * originX,originY. Rotation specifies the angle of counter clockwise rotation of the rectangle around originX, originY. The + * portion of the {@link Texture} given by srcX, srcY and srcWidth, srcHeight is used. These coordinates and sizes are given in + * texels. The rectangle will have the given tint {@link Color}. FlipX and flipY specify whether the texture portion should be + * fliped horizontally or vertically. + * * @param texture the Texture * @param x the x-coordinate in screen space * @param y the y-coordinate in screen space @@ -329,21 +287,19 @@ public class SpriteBatch * @param flipX whether to flip the sprite horizontally * @param flipY whether to flip the sprite vertically */ - public void draw(Texture texture, float x, float y, float originX, float originY, float width, float height, float scaleX, float scaleY, float rotation, int srcX, int srcY, int srcWidth, int srcHeight, Color tint, boolean flipX, boolean flipY ) - { - if( !drawing ) - throw new IllegalStateException( "you have to call SpriteBatch.begin() first" ); - - if( texture != lastTexture ) - { - renderMesh( ); + public void draw (Texture texture, float x, float y, float originX, float originY, float width, float height, float scaleX, + float scaleY, float rotation, int srcX, int srcY, int srcWidth, int srcHeight, Color tint, boolean flipX, boolean flipY) { + if (!drawing) throw new IllegalStateException("you have to call SpriteBatch.begin() first"); + + if (texture != lastTexture) { + renderMesh(); lastTexture = texture; invTexWidth = 1.0f / texture.getWidth(); invTexHeight = 1.0f / texture.getHeight(); } - - useTextBlend = false; - + + useTextBlend = false; + // bottom left and top right corner points relative to origin final float worldOriginX = x + originX; final float worldOriginY = y + originY; @@ -351,16 +307,15 @@ public class SpriteBatch float fy = -originY; float fx2 = width - originX; float fy2 = height - originY; - + // scale - if( scaleX != 1 || scaleY != 1 ) - { + if (scaleX != 1 || scaleY != 1) { fx *= scaleX; fy *= scaleY; fx2 *= scaleX; fy2 *= scaleY; } - + // construct corner points, start from top left and go counter clockwise final float p1x = fx; final float p1y = fy; @@ -370,7 +325,7 @@ public class SpriteBatch final float p3y = fy2; final float p4x = fx2; final float p4y = fy; - + float x1; float y1; float x2; @@ -379,98 +334,98 @@ public class SpriteBatch float y3; float x4; float y4; - - + // rotate - if( rotation != 0 ) - { - final float cos = MathUtils.cosDeg( rotation ); - final float sin = MathUtils.sinDeg( rotation ); - + if (rotation != 0) { + final float cos = MathUtils.cosDeg(rotation); + final float sin = MathUtils.sinDeg(rotation); + x1 = cos * p1x - sin * p1y; y1 = sin * p1x + cos * p1y; - + x2 = cos * p2x - sin * p2y; y2 = sin * p2x + cos * p2y; - + x3 = cos * p3x - sin * p3y; y3 = sin * p3x + cos * p3y; - + x4 = x1 + (x3 - x2); - y4 = y3 - (y2 - y1); - } - else - { + y4 = y3 - (y2 - y1); + } else { x1 = p1x; y1 = p1y; - + x2 = p2x; y2 = p2y; - + x3 = p3x; y3 = p3y; - + x4 = p4x; y4 = p4y; - } - - x1 += worldOriginX; y1 += worldOriginY; - x2 += worldOriginX; y2 += worldOriginY; - x3 += worldOriginX; y3 += worldOriginY; - x4 += worldOriginX; y4 += worldOriginY; - + } + + x1 += worldOriginX; + y1 += worldOriginY; + x2 += worldOriginX; + y2 += worldOriginY; + x3 += worldOriginX; + y3 += worldOriginY; + x4 += worldOriginX; + y4 += worldOriginY; + float u = srcX * invTexWidth; float v = (srcY + srcHeight) * invTexHeight; float u2 = (srcX + srcWidth) * invTexWidth; float v2 = srcY * invTexHeight; - - if( flipX ) - { + + if (flipX) { float tmp = u; u = u2; u2 = tmp; } - - if( flipY ) - { + + if (flipY) { float tmp = v; v = v2; v2 = tmp; - } - + } + final float color = tint.toFloatBits(); - + vertices[idx++] = x1; vertices[idx++] = y1; vertices[idx++] = color; - vertices[idx++] = u; vertices[idx++] = v; - + vertices[idx++] = u; + vertices[idx++] = v; + vertices[idx++] = x2; vertices[idx++] = y2; vertices[idx++] = color; - vertices[idx++] = u; vertices[idx++] = v2; - + vertices[idx++] = u; + vertices[idx++] = v2; + vertices[idx++] = x3; vertices[idx++] = y3; - vertices[idx++] = color; - vertices[idx++] = u2; vertices[idx++] = v2; - + vertices[idx++] = color; + vertices[idx++] = u2; + vertices[idx++] = v2; + vertices[idx++] = x4; vertices[idx++] = y4; vertices[idx++] = color; - vertices[idx++] = u2; vertices[idx++] = v; - - if( idx == vertices.length ) - renderMesh(); + vertices[idx++] = u2; + vertices[idx++] = v; + + if (idx == vertices.length) renderMesh(); } - + /** - * Draws a rectangle with the top left corner at x,y having - * the given width and height in pixels. The portion of the {@link Texture} - * given by srcX, srcY and srcWidth, srcHeight is used. These coordinates and - * sizes are given in texels. The rectangle will have the given tint {@link Color}. FlipX - * and flipY specify whether the texture portion should be fliped horizontally or vertically. - * + * Draws a rectangle with the top left corner at x,y having the given width and height in pixels. The portion of the + * {@link Texture} given by srcX, srcY and srcWidth, srcHeight is used. These coordinates and sizes are given in texels. The + * rectangle will have the given tint {@link Color}. FlipX and flipY specify whether the texture portion should be fliped + * horizontally or vertically. + * * @param texture the Texture * @param x the x-coordinate in screen space * @param y the y-coordinate in screen space @@ -484,74 +439,72 @@ public class SpriteBatch * @param flipX whether to flip the sprite horizontally * @param flipY whether to flip the sprite vertically */ - public void draw(Texture texture, float x, float y, float width, float height, int srcX, int srcY, int srcWidth, int srcHeight, Color tint, boolean flipX, boolean flipY ) - { - if( !drawing ) - throw new IllegalStateException( "you have to call SpriteBatch.begin() first" ); - - if( texture != lastTexture ) - { - renderMesh( ); + public void draw (Texture texture, float x, float y, float width, float height, int srcX, int srcY, int srcWidth, + int srcHeight, Color tint, boolean flipX, boolean flipY) { + if (!drawing) throw new IllegalStateException("you have to call SpriteBatch.begin() first"); + + if (texture != lastTexture) { + renderMesh(); lastTexture = texture; invTexWidth = 1.0f / texture.getWidth(); invTexHeight = 1.0f / texture.getHeight(); } - + useTextBlend = false; - + float u = srcX * invTexWidth; float v = (srcY + srcHeight) * invTexHeight; float u2 = (srcX + srcWidth) * invTexWidth; - float v2 = srcY * invTexHeight; - final float fx2 = x + width; + float v2 = srcY * invTexHeight; + final float fx2 = x + width; final float fy2 = y + height; - - if( flipX ) - { + + if (flipX) { float tmp = u; u = u2; u2 = tmp; } - - if( flipY ) - { + + if (flipY) { float tmp = v; v = v2; v2 = tmp; - } - + } + final float color = tint.toFloatBits(); - + vertices[idx++] = x; vertices[idx++] = y; vertices[idx++] = color; - vertices[idx++] = u; vertices[idx++] = v; - + vertices[idx++] = u; + vertices[idx++] = v; + vertices[idx++] = x; vertices[idx++] = fy2; vertices[idx++] = color; - vertices[idx++] = u; vertices[idx++] = v2; - + vertices[idx++] = u; + vertices[idx++] = v2; + vertices[idx++] = fx2; vertices[idx++] = fy2; vertices[idx++] = color; - vertices[idx++] = u2; vertices[idx++] = v2; - + vertices[idx++] = u2; + vertices[idx++] = v2; + vertices[idx++] = fx2; vertices[idx++] = y; vertices[idx++] = color; - vertices[idx++] = u2; vertices[idx++] = v; - - if( idx == vertices.length ) - renderMesh(); + vertices[idx++] = u2; + vertices[idx++] = v; + + if (idx == vertices.length) renderMesh(); } - + /** - * Draws a rectangle with the top left corner at x,y having - * the given width and height in pixels. The portion of the {@link Texture} - * given by srcX, srcY and srcWidth, srcHeight are used. These coordinates and - * sizes are given in texels. The rectangle will have the given tint {@link Color}. - * + * Draws a rectangle with the top left corner at x,y having the given width and height in pixels. The portion of the + * {@link Texture} given by srcX, srcY and srcWidth, srcHeight are used. These coordinates and sizes are given in texels. The + * rectangle will have the given tint {@link Color}. + * * @param texture the Texture * @param x the x-coordinate in screen space * @param y the y-coordinate in screen space @@ -560,137 +513,115 @@ public class SpriteBatch * @param srcWidth the source with in texels * @param srcHeight the source height in texels * @param tint the tint Color - */ - public void draw( Texture texture, float x, float y, int srcX, int srcY, int srcWidth, int srcHeight, Color tint ) - { - if( !drawing ) - throw new IllegalStateException( "you have to call SpriteBatch.begin() first" ); - - if( texture != lastTexture ) - { - renderMesh( ); + */ + public void draw (Texture texture, float x, float y, int srcX, int srcY, int srcWidth, int srcHeight, Color tint) { + if (!drawing) throw new IllegalStateException("you have to call SpriteBatch.begin() first"); + + if (texture != lastTexture) { + renderMesh(); lastTexture = texture; invTexWidth = 1.0f / texture.getWidth(); invTexHeight = 1.0f / texture.getHeight(); } - + useTextBlend = false; - + final float u = srcX * invTexWidth; final float v = (srcY + srcHeight) * invTexHeight; final float u2 = (srcX + srcWidth) * invTexWidth; - final float v2 = srcY * invTexHeight; - final float fx2 = x + srcWidth; + final float v2 = srcY * invTexHeight; + final float fx2 = x + srcWidth; final float fy2 = y + srcHeight; - + final float color = tint.toFloatBits(); - + vertices[idx++] = x; vertices[idx++] = y; vertices[idx++] = color; - vertices[idx++] = u; vertices[idx++] = v; - + vertices[idx++] = u; + vertices[idx++] = v; + vertices[idx++] = x; vertices[idx++] = fy2; vertices[idx++] = color; - vertices[idx++] = u; vertices[idx++] = v2; - + vertices[idx++] = u; + vertices[idx++] = v2; + vertices[idx++] = fx2; vertices[idx++] = fy2; vertices[idx++] = color; - vertices[idx++] = u2; vertices[idx++] = v2; - + vertices[idx++] = u2; + vertices[idx++] = v2; + vertices[idx++] = fx2; vertices[idx++] = y; vertices[idx++] = color; - vertices[idx++] = u2; vertices[idx++] = v; - - if( idx == vertices.length ) + vertices[idx++] = u2; + vertices[idx++] = v; + + if (idx == vertices.length) renderMesh(); + } + + public void draw (Texture texture, float[] spriteVertices, int offset, int length) { + if (!drawing) throw new IllegalStateException("you have to call SpriteBatch.begin() first"); + + if (texture != lastTexture) { renderMesh(); - } - - public void draw( Texture texture, float[] spriteVertices, int offset, int length ) - { - if( !drawing ) - throw new IllegalStateException( "you have to call SpriteBatch.begin() first" ); - - if( texture != lastTexture ) - { - renderMesh( ); lastTexture = texture; invTexWidth = 1.0f / texture.getWidth(); invTexHeight = 1.0f / texture.getHeight(); } - + useTextBlend = false; - if( idx + length >= vertices.length ) - renderMesh(); + if (idx + length >= vertices.length) renderMesh(); System.arraycopy(spriteVertices, offset, vertices, idx, length); idx += length; } - protected void renderMesh( ) - { - if( idx == 0 ) - return; - + protected void renderMesh () { + if (idx == 0) return; + renderCalls++; - - lastTexture.bind(); - mesh.setVertices(vertices, 0, idx); - - if( Gdx.graphics.isGL20Available() ) - { - if( useTextBlend ) - { - Gdx.graphics.getGL20().glBlendFunc( GL20.GL_ONE, GL20.GL_ONE_MINUS_SRC_ALPHA ); - Gdx.graphics.getGL20().glEnable( GL20.GL_BLEND ); - } - else - { - if( blendingDisabled ) - { - Gdx.graphics.getGL20().glDisable( GL20.GL_BLEND ); - } - else - { - Gdx.graphics.getGL20().glEnable( GL20.GL_BLEND ); - Gdx.graphics.getGL20().glBlendFunc( blendSrcFunc, blendDstFunc ); + + lastTexture.bind(); + mesh.setVertices(vertices, 0, idx); + + if (Gdx.graphics.isGL20Available()) { + if (useTextBlend) { + Gdx.graphics.getGL20().glBlendFunc(GL20.GL_ONE, GL20.GL_ONE_MINUS_SRC_ALPHA); + Gdx.graphics.getGL20().glEnable(GL20.GL_BLEND); + } else { + if (blendingDisabled) { + Gdx.graphics.getGL20().glDisable(GL20.GL_BLEND); + } else { + Gdx.graphics.getGL20().glEnable(GL20.GL_BLEND); + Gdx.graphics.getGL20().glBlendFunc(blendSrcFunc, blendDstFunc); } } - - mesh.render( shader, GL10.GL_TRIANGLES, 0, idx / 20 * 6 ); - } - else - { - if( useTextBlend ) - { - Gdx.graphics.getGL10().glBlendFunc( GL10.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA ); - Gdx.graphics.getGL10().glEnable( GL10.GL_BLEND ); - } - else - { - if( blendingDisabled ) - { - Gdx.graphics.getGL10().glDisable( GL10.GL_BLEND ); - } - else - { - Gdx.graphics.getGL10().glEnable( GL10.GL_BLEND ); - Gdx.graphics.getGL10().glBlendFunc( blendSrcFunc, blendDstFunc ); + + mesh.render(shader, GL10.GL_TRIANGLES, 0, idx / 20 * 6); + } else { + if (useTextBlend) { + Gdx.graphics.getGL10().glBlendFunc(GL10.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA); + Gdx.graphics.getGL10().glEnable(GL10.GL_BLEND); + } else { + if (blendingDisabled) { + Gdx.graphics.getGL10().glDisable(GL10.GL_BLEND); + } else { + Gdx.graphics.getGL10().glEnable(GL10.GL_BLEND); + Gdx.graphics.getGL10().glBlendFunc(blendSrcFunc, blendDstFunc); } } - mesh.render( GL10.GL_TRIANGLES, 0, idx / 20 * 6 ); + mesh.render(GL10.GL_TRIANGLES, 0, idx / 20 * 6); } idx = 0; - } - + } + /** - * Draws a text with its bounding box's top left corner at x,y using - * the given {@link Font}. This will ignore any newlines, tabs and - * other special characters. + * Draws a text with its bounding box's top left corner at x,y using the given {@link Font}. This will ignore any newlines, + * tabs and other special characters. * * @param font the Font * @param text the text @@ -698,157 +629,140 @@ public class SpriteBatch * @param y the y-coordinate of the strings bounding box's upper left corner * @param tint the tint of the text */ - public void drawText( Font font, String text, float x, float y, Color tint ) - { - if( !drawing ) - throw new IllegalStateException( "you have to call SpriteBatch.begin() first" ); - - if( font.getTexture() != lastTexture ) - { - renderMesh( ); - lastTexture = font.getTexture(); - } - - useTextBlend = true; - + public void drawText (Font font, String text, float x, float y, Color tint) { + if (!drawing) throw new IllegalStateException("you have to call SpriteBatch.begin() first"); + + if (font.getTexture() != lastTexture) { + renderMesh(); + lastTexture = font.getTexture(); + } + + useTextBlend = true; + final float color = tint.toFloatBits(); - - int len = text.length(); - for( int i = 0; i < len; i++ ) - { + + int len = text.length(); + for (int i = 0; i < len; i++) { char c = text.charAt(i); Glyph g = font.getGlyph(c); - + final float fx = x; - final float fx2 = x + g.width; + final float fx2 = x + g.width; final float fy2 = y + g.height; final float u = g.u; final float v = g.v + g.vHeight; final float u2 = g.u + g.uWidth; final float v2 = g.v; - + vertices[idx++] = fx; vertices[idx++] = y; vertices[idx++] = color; - vertices[idx++] = u; vertices[idx++] = v; - + vertices[idx++] = u; + vertices[idx++] = v; + vertices[idx++] = fx; vertices[idx++] = fy2; vertices[idx++] = color; - vertices[idx++] = u; vertices[idx++] = v2; - + vertices[idx++] = u; + vertices[idx++] = v2; + vertices[idx++] = fx2; vertices[idx++] = fy2; vertices[idx++] = color; - vertices[idx++] = u2; vertices[idx++] = v2; - + vertices[idx++] = u2; + vertices[idx++] = v2; + vertices[idx++] = fx2; vertices[idx++] = y; vertices[idx++] = color; - vertices[idx++] = u2; vertices[idx++] = v; - + vertices[idx++] = u2; + vertices[idx++] = v; + x += g.advance; - - if( idx == vertices.length ) - renderMesh(); + + if (idx == vertices.length) renderMesh(); } - } - + } + /** * Disables blending for drawing sprites. Does not disable blending for text rendering */ - public void disableBlending( ) - { + public void disableBlending () { renderMesh(); - blendingDisabled = true; + blendingDisabled = true; } - + /** * Enables blending for sprites */ - public void enableBlending( ) - { + public void enableBlending () { renderMesh(); blendingDisabled = false; } - + /** - * Sets the blending function to be used when rendering sprites. This will - * have no effect on the blend function used for text rendering! + * Sets the blending function to be used when rendering sprites. This will have no effect on the blend function used for text + * rendering! * * @param srcFunc the source function, e.g. GL11.GL_SRC_ALPHA * @param dstFunc the destination function, e.g. GL11.GL_ONE_MINUS_SRC_ALPHA */ - public void setBlendFunction( int srcFunc, int dstFunc ) - { - renderMesh( ); + public void setBlendFunction (int srcFunc, int dstFunc) { + renderMesh(); blendSrcFunc = srcFunc; blendDstFunc = dstFunc; } - + /** * Disposes all resources associated with this SpriteBatch */ - public void dispose( ) - { + public void dispose () { mesh.dispose(); - if( shader != null ) - shader.dispose(); + if (shader != null) shader.dispose(); } - + /** - * Returns the current projection matrix. Changing this - * will result in undefined behaviour. + * Returns the current projection matrix. Changing this will result in undefined behaviour. * * @return the currently set projection matrix */ - public Matrix4 getProjectionMatrix( ) - { + public Matrix4 getProjectionMatrix () { return projectionMatrix; } - + /** - * Returns the current transform matrix. Changing this - * will result in undefined behaviour. + * Returns the current transform matrix. Changing this will result in undefined behaviour. * * @return the currently set transform matrix */ - public Matrix4 getTransformMatrix( ) - { + public Matrix4 getTransformMatrix () { return transformMatrix; } - + /** - * Sets the projection matrix to be used by this SpriteBatch. Can - * only be set outside a {@link #begin()}/{@link #end()} block. + * Sets the projection matrix to be used by this SpriteBatch. Can only be set outside a {@link #begin()}/{@link #end()} block. * @param projection the projection matrix */ - public void setProjectionMatrix( Matrix4 projection ) - { - if( drawing ) - throw new GdxRuntimeException( "Can't set the matrix within begin()/end() block" ); - - projectionMatrix.set( projection ); + public void setProjectionMatrix (Matrix4 projection) { + if (drawing) throw new GdxRuntimeException("Can't set the matrix within begin()/end() block"); + + projectionMatrix.set(projection); } - + /** - * Sets the transform matrix to be used by this SpriteBatch. Can - * only be set outside a {@link #begin()}/{@link #end()} block. + * Sets the transform matrix to be used by this SpriteBatch. Can only be set outside a {@link #begin()}/{@link #end()} block. * @param projection the projection matrix */ - public void setTransformMatrix( Matrix4 transform ) - { - if( drawing ) - throw new GdxRuntimeException( "Can't set the matrix within begin()/end() block" ); - - transformMatrix.set( transform ); + public void setTransformMatrix (Matrix4 transform) { + if (drawing) throw new GdxRuntimeException("Can't set the matrix within begin()/end() block"); + + transformMatrix.set(transform); } /** * @return whether blending for sprites is enabled */ - public boolean isBlendingEnabled() - { + public boolean isBlendingEnabled () { return !blendingDisabled; } } diff --git a/gdx/src/com/badlogic/gdx/graphics/Texture.java b/gdx/src/com/badlogic/gdx/graphics/Texture.java index e4543385d..67250f339 100644 --- a/gdx/src/com/badlogic/gdx/graphics/Texture.java +++ b/gdx/src/com/badlogic/gdx/graphics/Texture.java @@ -1,39 +1,39 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics; /** - *

A Texture wraps a standard OpenGL ES texture.

- * - *

It is constructed by an {@link Graphics} via one of the - * {@link Graphics.newTexture()} methods.

+ *

+ * A Texture wraps a standard OpenGL ES texture. + *

* - *

A Texture can be managed. If the OpenGL context is lost - * all textures get invalidated. This happens when a user switches - * to another application or receives an incoming call. Managed - * textures get reloaded automatically. + *

+ * It is constructed by an {@link Graphics} via one of the {@link Graphics.newTexture()} methods. + *

+ * + *

+ * A Texture can be managed. If the OpenGL context is lost all textures get invalidated. This happens when a user switches to + * another application or receives an incoming call. Managed textures get reloaded automatically. *

* *

* A Texture has to be bound via the {@link Texture.bind()} method in order for it to be applied to geometry. *

* - *

- * You can draw {@link Pixmap}s to a texture at any time. The changes will be automatically uploaded to - * texture memory. This is of course not extremely fast so use it with care. + *

+ * You can draw {@link Pixmap}s to a texture at any time. The changes will be automatically uploaded to texture memory. This is of + * course not extremely fast so use it with care. *

* *

@@ -41,40 +41,33 @@ package com.badlogic.gdx.graphics; *

* * @author badlogicgames@gmail.com - * + * */ -public interface Texture -{ +public interface Texture { /** * Texture filter enum featuring the 3 most used filters. * @author badlogicgames@gmail.com - * + * */ - public enum TextureFilter - { - Nearest, - Linear, - MipMap + public enum TextureFilter { + Nearest, Linear, MipMap } - + /** * Texture wrap enum * * @author badlogicgames@gmail.com - * + * */ - public enum TextureWrap - { - ClampToEdge, - Repeat + public enum TextureWrap { + ClampToEdge, Repeat } - + /** - * Binds this texture. You have to enable texturing via - * {@link Application.enable( RenderState.Texturing )} in - * order for the texture to actually be applied to geometry. + * Binds this texture. You have to enable texturing via {@link Application.enable( RenderState.Texturing )} in order for the + * texture to actually be applied to geometry. */ - public void bind( ); + public void bind (); /** * Draws the given {@link Pixmap} to the texture at position x, y. @@ -83,33 +76,33 @@ public interface Texture * @param x The x coordinate in pixels * @param y The y coordinate in pixels */ - public void draw( Pixmap pixmap, int x, int y ); - + public void draw (Pixmap pixmap, int x, int y); + /** * * @return the width of the texture in pixels */ - public int getWidth( ); - + public int getWidth (); + /** * * @return the height of the texture in pixels */ - public int getHeight( ); + public int getHeight (); /** * @return whether this texture is managed or not. */ - public boolean isManaged( ); - + public boolean isManaged (); + /** * Disposes all resources associated with the texture * @return */ - public void dispose( ); - + public void dispose (); + /** * @return the OpenGL texture object handle so you can change texture parameters. */ - public int getTextureObjectHandle( ); + public int getTextureObjectHandle (); } diff --git a/gdx/src/com/badlogic/gdx/graphics/TextureAtlas.java b/gdx/src/com/badlogic/gdx/graphics/TextureAtlas.java index 2f8098155..5c2c19f2a 100644 --- a/gdx/src/com/badlogic/gdx/graphics/TextureAtlas.java +++ b/gdx/src/com/badlogic/gdx/graphics/TextureAtlas.java @@ -1,79 +1,69 @@ + package com.badlogic.gdx.graphics; import java.util.HashMap; import java.util.Map; /** - * A TextureAtlas is composed of a single {@link Texture} and - * named {@link TextureRegion}s. You can add new regions at any - * time either programmatically or by reading them in from a file. + * A TextureAtlas is composed of a single {@link Texture} and named {@link TextureRegion}s. You can add new regions at any time + * either programmatically or by reading them in from a file. * * @author mzechner - * + * */ -public class TextureAtlas -{ - private final Map regions = new HashMap( ); +public class TextureAtlas { + private final Map regions = new HashMap(); private final Texture texture; - + /** - * Constructs a new texture atlas with the given texture. - * Use {@link #addRegion()} or one of the {@link #load()} methods - * to add {@link TextureRegions} + * Constructs a new texture atlas with the given texture. Use {@link #addRegion()} or one of the {@link #load()} methods to add + * {@link TextureRegions} * * @param texture the texture */ - public TextureAtlas( Texture texture ) - { + public TextureAtlas (Texture texture) { this.texture = texture; } - + /** - * Returns the {@link TextureRegion} with name regionName or null - * in case the region is undefined. + * Returns the {@link TextureRegion} with name regionName or null in case the region is undefined. * * @param regionName the region name * @return the region or null. */ - public TextureRegion getRegion( String regionName ) - { + public TextureRegion getRegion (String regionName) { return regions.get(regionName); } - + /** - * Adds the {@link TextureRegion} with name regionName - * to this atlas. If a region with the given name was - * present already it will be overwritten. + * Adds the {@link TextureRegion} with name regionName to this atlas. If a region with the given name was present already it + * will be overwritten. * * @param regionName the region name * @param region the region */ - public void addRegion( String regionName, TextureRegion region ) - { - regions.put( regionName, region ); + public void addRegion (String regionName, TextureRegion region) { + regions.put(regionName, region); } - + /** - * Adds a new {@link TextureRegion} with name regionName to this - * atlas. If a region with the given name was already present it + * Adds a new {@link TextureRegion} with name regionName to this atlas. If a region with the given name was already present it * is overwritten. * * @param regionName the region name - * @param x the x coordinate of the region in pixels + * @param x the x coordinate of the region in pixels * @param y the y coordinate of the region in pixels * @param width the width of the region in pixels * @param height the height of the region in pixels */ - public void addRegion( String regionName, int x, int y, int width, int height ) - { - regions.put( regionName, new TextureRegion( texture, x, y, width, height ) ); + public void addRegion (String regionName, int x, int y, int width, int height) { + regions.put(regionName, new TextureRegion(texture, x, y, width, height)); } - + /** * @return the {@link Texture} of this atlas */ - public Texture getTexture( ) - { + public Texture getTexture () { return texture; } } diff --git a/gdx/src/com/badlogic/gdx/graphics/TextureRegion.java b/gdx/src/com/badlogic/gdx/graphics/TextureRegion.java index bd074348f..d90f71961 100644 --- a/gdx/src/com/badlogic/gdx/graphics/TextureRegion.java +++ b/gdx/src/com/badlogic/gdx/graphics/TextureRegion.java @@ -1,25 +1,22 @@ + package com.badlogic.gdx.graphics; /** - * A TextureRegion defines a rectangular area in a texture - * given in pixels. + * A TextureRegion defines a rectangular area in a texture given in pixels. * * @author mzechner - * + * */ -public class TextureRegion -{ +public class TextureRegion { public int x, y; public int width, height; public Texture texture; - - public TextureRegion( Texture texture, int x, int y, int width, int height ) - { - set( texture, x, y, width, height ); + + public TextureRegion (Texture texture, int x, int y, int width, int height) { + set(texture, x, y, width, height); } - public void set(Texture texture, int x, int y, int width, int height) - { + public void set (Texture texture, int x, int y, int width, int height) { this.texture = texture; this.x = x; this.y = y; diff --git a/gdx/src/com/badlogic/gdx/graphics/VertexAttribute.java b/gdx/src/com/badlogic/gdx/graphics/VertexAttribute.java index 680844349..06ae709b3 100644 --- a/gdx/src/com/badlogic/gdx/graphics/VertexAttribute.java +++ b/gdx/src/com/badlogic/gdx/graphics/VertexAttribute.java @@ -1,36 +1,30 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics; import com.badlogic.gdx.graphics.VertexAttributes.Usage; /** - * A single vertex attribute defined by its {@link Usage}, its number of components - * and its shader alias. The Usage is needed for the fixed function pipeline of - * OpenGL ES 1.x. Generic attributes are not supported in the fixed function pipeline. - * The number of components defines how many components the attribute has. The alias - * defines to which shader attribute this attribute should bind. The alias is used - * by a {@link Mesh} when drawing with a {@link ShaderProgram}. The alias can be - * changed at any time. + * A single vertex attribute defined by its {@link Usage}, its number of components and its shader alias. The Usage is needed for + * the fixed function pipeline of OpenGL ES 1.x. Generic attributes are not supported in the fixed function pipeline. The number + * of components defines how many components the attribute has. The alias defines to which shader attribute this attribute should + * bind. The alias is used by a {@link Mesh} when drawing with a {@link ShaderProgram}. The alias can be changed at any time. * * @author mzechner - * + * */ -public final class VertexAttribute -{ +public final class VertexAttribute { /** the attribute {@link Usage} **/ public final int usage; /** the number of components this attribute has **/ @@ -41,14 +35,14 @@ public final class VertexAttribute public String alias; /** - * Constructs a new VertexAttribute. + * Constructs a new VertexAttribute. * - * @param usage the usage, used for the fixed function pipeline. Generic attributes are not supported in the fixed function pipeline. + * @param usage the usage, used for the fixed function pipeline. Generic attributes are not supported in the fixed function + * pipeline. * @param numComponents the number of components of this attribute, must be between 1 and 4. * @param alias the alias used in a shader for this attribute. Can be changed after construction. */ - public VertexAttribute( int usage, int numComponents, String alias ) - { + public VertexAttribute (int usage, int numComponents, String alias) { this.usage = usage; this.numComponents = numComponents; this.alias = alias; diff --git a/gdx/src/com/badlogic/gdx/graphics/VertexAttributes.java b/gdx/src/com/badlogic/gdx/graphics/VertexAttributes.java index 9347f1f59..9c10ccda5 100644 --- a/gdx/src/com/badlogic/gdx/graphics/VertexAttributes.java +++ b/gdx/src/com/badlogic/gdx/graphics/VertexAttributes.java @@ -1,40 +1,33 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ -package com.badlogic.gdx.graphics; +package com.badlogic.gdx.graphics; /** - * Instances of this class specify the vertex attributes of a mesh. - * VertexAttributes are used by {@link Mesh} instances to define its vertex structure. Vertex - * attributes have an order. The order is specified by the order - * they are added to this class. + * Instances of this class specify the vertex attributes of a mesh. VertexAttributes are used by {@link Mesh} instances to define + * its vertex structure. Vertex attributes have an order. The order is specified by the order they are added to this class. * * @author mzechner - * + * */ -public final class VertexAttributes -{ +public final class VertexAttributes { /** * The usage of a vertex attribute. * * @author mzechner - * + * */ - public final class Usage - { + public final class Usage { public static final int Position = 0; public static final int Color = 1; public static final int ColorPacked = 5; @@ -42,98 +35,82 @@ public final class VertexAttributes public static final int TextureCoordinates = 3; public static final int Generic = 4; } - + /** the attributes in the order they were specified **/ private final VertexAttribute[] attributes; - + /** the size of a single vertex in bytes **/ public final int vertexSize; - + /** - * Constructor, sets the vertex attributes in a specific order + * Constructor, sets the vertex attributes in a specific order */ - public VertexAttributes( VertexAttribute ... attributes ) - { - if( attributes.length == 0 ) - throw new IllegalArgumentException( "attributes must be >= 1" ); - + public VertexAttributes (VertexAttribute... attributes) { + if (attributes.length == 0) throw new IllegalArgumentException("attributes must be >= 1"); + VertexAttribute[] list = new VertexAttribute[attributes.length]; - for( int i = 0; i < attributes.length; i++ ) + for (int i = 0; i < attributes.length; i++) list[i] = attributes[i]; - + this.attributes = list; - - checkValidity( ); - vertexSize = calculateOffsets( ); + + checkValidity(); + vertexSize = calculateOffsets(); } - - private int calculateOffsets( ) - { + + private int calculateOffsets () { int count = 0; - for( int i = 0; i < attributes.length; i++ ) - { + for (int i = 0; i < attributes.length; i++) { VertexAttribute attribute = attributes[i]; attribute.offset = count; - if( attribute.usage == VertexAttributes.Usage.ColorPacked ) + if (attribute.usage == VertexAttributes.Usage.ColorPacked) count += 4; else count += 4 * attribute.numComponents; } - + return count; } - - private void checkValidity( ) - { + + private void checkValidity () { boolean pos = false; boolean cols = false; boolean nors = false; - - for( int i = 0; i < attributes.length; i++ ) - { + + for (int i = 0; i < attributes.length; i++) { VertexAttribute attribute = attributes[i]; - if( attribute.usage == Usage.Position ) - { - if( pos ) - throw new IllegalArgumentException( "two position attributes were specified" ); + if (attribute.usage == Usage.Position) { + if (pos) throw new IllegalArgumentException("two position attributes were specified"); pos = true; } - - if( attribute.usage == Usage.Normal ) - { - if( nors ) - throw new IllegalArgumentException( "two normal attributes were specified" ); + + if (attribute.usage == Usage.Normal) { + if (nors) throw new IllegalArgumentException("two normal attributes were specified"); } - - if( attribute.usage == Usage.Color || attribute.usage == Usage.ColorPacked ) - { - if( attribute.numComponents != 4 ) - throw new IllegalArgumentException( "color attribute must have 4 components" ); - - if( cols ) - throw new IllegalArgumentException( "two color attributes were specified" ); + + if (attribute.usage == Usage.Color || attribute.usage == Usage.ColorPacked) { + if (attribute.numComponents != 4) throw new IllegalArgumentException("color attribute must have 4 components"); + + if (cols) throw new IllegalArgumentException("two color attributes were specified"); cols = true; } } - - if( pos == false ) - throw new IllegalArgumentException( "no position attribute was specified" ); + + if (pos == false) throw new IllegalArgumentException("no position attribute was specified"); } - + /** * @return the number of attributes */ - public int size() - { + public int size () { return attributes.length; } - + /** * @param index the index * @return the VertexAttribute at the given index */ - public VertexAttribute get( int index ) - { + public VertexAttribute get (int index) { return attributes[index]; } } diff --git a/gdx/src/com/badlogic/gdx/graphics/loaders/ObjLoader.java b/gdx/src/com/badlogic/gdx/graphics/loaders/ObjLoader.java index 72f13df30..353a12f74 100644 --- a/gdx/src/com/badlogic/gdx/graphics/loaders/ObjLoader.java +++ b/gdx/src/com/badlogic/gdx/graphics/loaders/ObjLoader.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.loaders; import java.io.BufferedReader; @@ -27,43 +25,37 @@ import com.badlogic.gdx.graphics.VertexAttributes.Usage; /** * Loads Wavefront OBJ files, ignores material files. * @author mzechner - * + * */ -public class ObjLoader -{ +public class ObjLoader { /** * Loads a Wavefront OBJ file from the given input stream. * * @param in the InputStream * @param useFloats whether to return a FloatMesh or a FixedPointMesh - * + * */ - public static Mesh loadObj( InputStream in, boolean useFloats ) - { + public static Mesh loadObj (InputStream in, boolean useFloats) { String line = ""; - - try - { - BufferedReader reader = new BufferedReader( new InputStreamReader( in ) ); + + try { + BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuffer b = new StringBuffer(); String l = reader.readLine(); - while( l != null ) - { - b.append( l ); - b.append( "\n" ); + while (l != null) { + b.append(l); + b.append("\n"); l = reader.readLine(); } - + line = b.toString(); reader.close(); - } - catch( Exception ex ) - { + } catch (Exception ex) { return null; } - return loadObjFromString( line, useFloats ); + return loadObjFromString(line, useFloats); } - + /** * Loads a mesh from the given string in Wavefront OBJ format * @@ -71,149 +63,129 @@ public class ObjLoader * @param useFloats whether to return a FloatMesh or a FixedPointMesh * @return The Mesh */ - public static Mesh loadObjFromString( String obj, boolean useFloats ) - { - String[] lines = obj.split( "\n" ); + public static Mesh loadObjFromString (String obj, boolean useFloats) { + String[] lines = obj.split("\n"); float[] vertices = new float[lines.length * 3]; float[] normals = new float[lines.length * 3]; float[] uv = new float[lines.length * 3]; - + int numVertices = 0; int numNormals = 0; int numUV = 0; int numFaces = 0; - + int[] facesVerts = new int[lines.length * 3]; int[] facesNormals = new int[lines.length * 3]; int[] facesUV = new int[lines.length * 3]; int vertexIndex = 0; int normalIndex = 0; int uvIndex = 0; - int faceIndex = 0; - - for( int i = 0; i < lines.length; i++ ) - { - String line = lines[i]; - if( line.startsWith( "v " ) ) - { - String[] tokens = line.split( "[ ]+" ); + int faceIndex = 0; + + for (int i = 0; i < lines.length; i++) { + String line = lines[i]; + if (line.startsWith("v ")) { + String[] tokens = line.split("[ ]+"); vertices[vertexIndex] = Float.parseFloat(tokens[1]); - vertices[vertexIndex+1] = Float.parseFloat(tokens[2]); - vertices[vertexIndex+2] = Float.parseFloat(tokens[3]); + vertices[vertexIndex + 1] = Float.parseFloat(tokens[2]); + vertices[vertexIndex + 2] = Float.parseFloat(tokens[3]); vertexIndex += 3; numVertices++; continue; } - - if( line.startsWith( "vn " ) ) - { - String[] tokens = line.split( "[ ]+" ); + + if (line.startsWith("vn ")) { + String[] tokens = line.split("[ ]+"); normals[normalIndex] = Float.parseFloat(tokens[1]); - normals[normalIndex+1] = Float.parseFloat(tokens[2]); - normals[normalIndex+2] = Float.parseFloat(tokens[3]); + normals[normalIndex + 1] = Float.parseFloat(tokens[2]); + normals[normalIndex + 2] = Float.parseFloat(tokens[3]); normalIndex += 3; numNormals++; continue; } - - if( line.startsWith( "vt" ) ) - { - String[] tokens = line.split( "[ ]+" ); + + if (line.startsWith("vt")) { + String[] tokens = line.split("[ ]+"); uv[uvIndex] = Float.parseFloat(tokens[1]); - uv[uvIndex+1] = Float.parseFloat(tokens[2]); + uv[uvIndex + 1] = Float.parseFloat(tokens[2]); uvIndex += 2; numUV++; continue; } - - if( line.startsWith( "f " ) ) - { - String[] tokens = line.split( "[ ]+" ); - + + if (line.startsWith("f ")) { + String[] tokens = line.split("[ ]+"); + String[] parts = tokens[1].split("/"); facesVerts[faceIndex] = getIndex(parts[0], numVertices); - if( parts.length > 2 ) - facesNormals[faceIndex] = getIndex(parts[2], numNormals); - if( parts.length > 1 ) - facesUV[faceIndex] = getIndex(parts[1], numUV); + if (parts.length > 2) facesNormals[faceIndex] = getIndex(parts[2], numNormals); + if (parts.length > 1) facesUV[faceIndex] = getIndex(parts[1], numUV); faceIndex++; - + parts = tokens[2].split("/"); facesVerts[faceIndex] = getIndex(parts[0], numVertices); - if( parts.length > 2 ) - facesNormals[faceIndex] = getIndex(parts[2], numNormals); - if( parts.length > 1 ) - facesUV[faceIndex] = getIndex(parts[1], numUV); + if (parts.length > 2) facesNormals[faceIndex] = getIndex(parts[2], numNormals); + if (parts.length > 1) facesUV[faceIndex] = getIndex(parts[1], numUV); faceIndex++; - + parts = tokens[3].split("/"); facesVerts[faceIndex] = getIndex(parts[0], numVertices); - if( parts.length > 2 ) - facesNormals[faceIndex] = getIndex(parts[2], numNormals); - if( parts.length > 1 ) - facesUV[faceIndex] = getIndex(parts[1], numUV); - faceIndex++; + if (parts.length > 2) facesNormals[faceIndex] = getIndex(parts[2], numNormals); + if (parts.length > 1) facesUV[faceIndex] = getIndex(parts[1], numUV); + faceIndex++; numFaces++; continue; } } - - - float[] verts = new float[ (numFaces * 3) * ( 3 + (numNormals>0?3:0) + (numUV > 0?2:0 ) )]; - - for( int i = 0, vi=0; i < numFaces*3; i++ ) - { - int vertexIdx = facesVerts[i] *3; + + float[] verts = new float[(numFaces * 3) * (3 + (numNormals > 0 ? 3 : 0) + (numUV > 0 ? 2 : 0))]; + + for (int i = 0, vi = 0; i < numFaces * 3; i++) { + int vertexIdx = facesVerts[i] * 3; verts[vi++] = vertices[vertexIdx]; - verts[vi++] = vertices[vertexIdx+1]; - verts[vi++] = vertices[vertexIdx+2]; - - if( numNormals > 0 ) - { + verts[vi++] = vertices[vertexIdx + 1]; + verts[vi++] = vertices[vertexIdx + 2]; + + if (numNormals > 0) { int normalIdx = facesNormals[i] * 3; verts[vi++] = normals[normalIdx]; - verts[vi++] = normals[normalIdx+1]; - verts[vi++] = normals[normalIdx+2]; + verts[vi++] = normals[normalIdx + 1]; + verts[vi++] = normals[normalIdx + 2]; } - if( numUV > 0 ) - { + if (numUV > 0) { int uvIdx = facesUV[i] * 2; verts[vi++] = uv[uvIdx]; - verts[vi++] = uv[uvIdx+1]; - } + verts[vi++] = uv[uvIdx + 1]; + } } - + Mesh mesh = null; - - ArrayList attributes = new ArrayList( ); - attributes.add( new VertexAttribute( Usage.Position, 3, "a_Position" ) ); - if( numNormals > 0 ) - attributes.add( new VertexAttribute( Usage.Normal, 3, "a_Normal" ) ); - if( numUV > 0 ) - attributes.add( new VertexAttribute( Usage.TextureCoordinates, 2, "a_TexCoord" ) ); - - mesh = new Mesh( true, !useFloats, numFaces * 3, 0, attributes.toArray( new VertexAttribute[attributes.size()] ) ); - if( useFloats ) - mesh.setVertices( verts ); + + ArrayList attributes = new ArrayList(); + attributes.add(new VertexAttribute(Usage.Position, 3, "a_Position")); + if (numNormals > 0) attributes.add(new VertexAttribute(Usage.Normal, 3, "a_Normal")); + if (numUV > 0) attributes.add(new VertexAttribute(Usage.TextureCoordinates, 2, "a_TexCoord")); + + mesh = new Mesh(true, !useFloats, numFaces * 3, 0, attributes.toArray(new VertexAttribute[attributes.size()])); + if (useFloats) + mesh.setVertices(verts); else - mesh.setVertices( convertToFixedPoint( verts ) ); + mesh.setVertices(convertToFixedPoint(verts)); return mesh; - } - - private static int[] convertToFixedPoint( float[] fverts ) - { + } + + private static int[] convertToFixedPoint (float[] fverts) { int[] fpverts = new int[fverts.length]; - for( int i = 0; i < fverts.length; i++ ) - fpverts[i] = (int)(fverts[i] * 65536);; + for (int i = 0; i < fverts.length; i++) + fpverts[i] = (int)(fverts[i] * 65536); + ; return fpverts; } - - private static int getIndex( String index, int size ) - { - if( index == null || index.length() == 0 ) - return 0; - int idx = Integer.parseInt( index ); - if( idx < 0 ) + + private static int getIndex (String index, int size) { + if (index == null || index.length() == 0) return 0; + int idx = Integer.parseInt(index); + if (idx < 0) return size + idx; else return idx - 1; diff --git a/gdx/src/com/badlogic/gdx/graphics/loaders/OctLoader.java b/gdx/src/com/badlogic/gdx/graphics/loaders/OctLoader.java index 56e69840a..2b95fe59f 100644 --- a/gdx/src/com/badlogic/gdx/graphics/loaders/OctLoader.java +++ b/gdx/src/com/badlogic/gdx/graphics/loaders/OctLoader.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.loaders; import java.io.BufferedInputStream; @@ -25,128 +23,132 @@ import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.LittleEndianInputStream; /** - * Loads an OCT file as found in many of Paul Nettle's demos. - * See the source at http://www.paulnettle.com/pub/FluidStudios/CollisionDetection/Fluid_Studios_Collision_Detection_Demo_and_Source.zip - * for more information + * Loads an OCT file as found in many of Paul Nettle's demos. See the source at + * http://www.paulnettle.com/pub/FluidStudios/CollisionDetection/Fluid_Studios_Collision_Detection_Demo_and_Source.zip for more + * information * * @author mzechner - * + * */ -public class OctLoader -{ - private static class OctVert - { +public class OctLoader { + private static class OctVert { public float tu, tv; - @SuppressWarnings("unused") - public float lu, lv; + @SuppressWarnings("unused") public float lu, lv; public float x, y, z; } - - private static class OctFace - { + + private static class OctFace { public int start; public int num; - @SuppressWarnings("unused") - public int id; - @SuppressWarnings("unused") - public int lid; - @SuppressWarnings("unused") - public float nx, ny, nz, d; + @SuppressWarnings("unused") public int id; + @SuppressWarnings("unused") public int lid; + @SuppressWarnings("unused") public float nx, ny, nz, d; } - - public static Mesh loadOct(InputStream inputStream, boolean useFloats, Vector3 start ) - { - LittleEndianInputStream in = new LittleEndianInputStream( new BufferedInputStream(inputStream) ); - - try - { + + public static Mesh loadOct (InputStream inputStream, boolean useFloats, Vector3 start) { + LittleEndianInputStream in = new LittleEndianInputStream(new BufferedInputStream(inputStream)); + + try { int numVertices = in.readInt(); int numFaces = in.readInt(); int numTextures = in.readInt(); int numLightmaps = in.readInt(); - + OctVert[] verts = new OctVert[numVertices]; OctFace[] faces = new OctFace[numFaces]; - - for( int i = 0; i < numVertices; i++ ) - { - OctVert v = new OctVert( ); - v.tu = in.readFloat(); v.tv = in.readFloat(); - v.lu = in.readFloat(); v.lv = in.readFloat(); - v.x = in.readFloat(); v.y = in.readFloat(); v.z = in.readFloat(); + + for (int i = 0; i < numVertices; i++) { + OctVert v = new OctVert(); + v.tu = in.readFloat(); + v.tv = in.readFloat(); + v.lu = in.readFloat(); + v.lv = in.readFloat(); + v.x = in.readFloat(); + v.y = in.readFloat(); + v.z = in.readFloat(); verts[i] = v; } - + int numTriangles = 0; - for( int i = 0; i < numFaces; i++ ) - { - OctFace f = new OctFace( ); + for (int i = 0; i < numFaces; i++) { + OctFace f = new OctFace(); f.start = in.readInt(); f.num = in.readInt(); f.id = in.readInt(); f.lid = in.readInt(); - f.nx = in.readFloat(); f.ny = in.readFloat(); f.nz = in.readFloat(); f.d = in.readFloat(); + f.nx = in.readFloat(); + f.ny = in.readFloat(); + f.nz = in.readFloat(); + f.d = in.readFloat(); faces[i] = f; numTriangles += f.num - 2; } - - for( int i = 0; i < numTextures * (64 + 4); i++ ) + + for (int i = 0; i < numTextures * (64 + 4); i++) in.read(); - - for( int i = 0; i < numLightmaps * (49152 + 4); i++ ) + + for (int i = 0; i < numLightmaps * (49152 + 4); i++) in.read(); - start.set( in.readFloat(), in.readFloat(), in.readFloat() ); - + start.set(in.readFloat(), in.readFloat(), in.readFloat()); + float[] triangles = new float[numTriangles * 3 * (3 + 3 + 2)]; - + int idx = 0; - for( int i = 0; i < numFaces; i++ ) - { - OctFace f = faces[i]; + for (int i = 0; i < numFaces; i++) { + OctFace f = faces[i]; OctVert v1 = verts[f.start]; - - for( int j = 0; j < f.num - 2; j++ ) - { + + for (int j = 0; j < f.num - 2; j++) { OctVert v2 = verts[f.start + j + 1]; OctVert v3 = verts[f.start + j + 2]; - - triangles[idx++] = v1.x; triangles[idx++] = v1.y; triangles[idx++] = v1.z; - triangles[idx++] = f.nx; triangles[idx++] = f.ny; triangles[idx++] = f.nz; - triangles[idx++] = v1.tu; triangles[idx++] = v1.tv; - triangles[idx++] = v2.x; triangles[idx++] = v2.y; triangles[idx++] = v2.z; - triangles[idx++] = f.nx; triangles[idx++] = f.ny; triangles[idx++] = f.nz; - triangles[idx++] = v2.tu; triangles[idx++] = v2.tv; - triangles[idx++] = v3.x; triangles[idx++] = v3.y; triangles[idx++] = v3.z; - triangles[idx++] = f.nx; triangles[idx++] = f.ny; triangles[idx++] = f.nz; - triangles[idx++] = v3.tu; triangles[idx++] = v3.tv; + + triangles[idx++] = v1.x; + triangles[idx++] = v1.y; + triangles[idx++] = v1.z; + triangles[idx++] = f.nx; + triangles[idx++] = f.ny; + triangles[idx++] = f.nz; + triangles[idx++] = v1.tu; + triangles[idx++] = v1.tv; + triangles[idx++] = v2.x; + triangles[idx++] = v2.y; + triangles[idx++] = v2.z; + triangles[idx++] = f.nx; + triangles[idx++] = f.ny; + triangles[idx++] = f.nz; + triangles[idx++] = v2.tu; + triangles[idx++] = v2.tv; + triangles[idx++] = v3.x; + triangles[idx++] = v3.y; + triangles[idx++] = v3.z; + triangles[idx++] = f.nx; + triangles[idx++] = f.ny; + triangles[idx++] = f.nz; + triangles[idx++] = v3.tu; + triangles[idx++] = v3.tv; } } - - Mesh m = new Mesh( true, !useFloats, numTriangles * 3, 0, - new VertexAttribute( Usage.Position, 3, "a_position"), - new VertexAttribute( Usage.Normal, 3, "a_position"), - new VertexAttribute( Usage.TextureCoordinates, 2, "a_texCoords") - ); - if( useFloats ) - m.setVertices( triangles ); + + Mesh m = new Mesh(true, !useFloats, numTriangles * 3, 0, new VertexAttribute(Usage.Position, 3, "a_position"), + new VertexAttribute(Usage.Normal, 3, "a_position"), new VertexAttribute(Usage.TextureCoordinates, 2, "a_texCoords")); + if (useFloats) + m.setVertices(triangles); else - m.setVertices( convertToFixedPoint( triangles ) ); - + m.setVertices(convertToFixedPoint(triangles)); + return m; - } - catch( Exception ex ) - { + } catch (Exception ex) { ex.printStackTrace(); return null; - } + } } - - private static int[] convertToFixedPoint( float[] fverts ) - { + + private static int[] convertToFixedPoint (float[] fverts) { int[] fpverts = new int[fverts.length]; - for( int i = 0; i < fverts.length; i++ ) - fpverts[i] = (int)(fverts[i] * 65536);; + for (int i = 0; i < fverts.length; i++) + fpverts[i] = (int)(fverts[i] * 65536); + ; return fpverts; - } + } } diff --git a/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Animation.java b/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Animation.java index 331e45729..53182cc8f 100644 --- a/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Animation.java +++ b/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Animation.java @@ -1,52 +1,50 @@ + package com.badlogic.gdx.graphics.loaders.md5; import com.badlogic.gdx.math.collision.BoundingBox; -public class MD5Animation -{ +public class MD5Animation { public int frameRate; public float secondsPerFrame; - + public MD5Joints[] frames; public BoundingBox[] bounds; - - static MD5Quaternion jointAOrient = new MD5Quaternion( ); - static MD5Quaternion jointBOrient = new MD5Quaternion( ); - - public static void interpolate( MD5Joints skeletonA, MD5Joints skeletonB, MD5Joints skeletonOut, float t ) - { - for( int i = 0, idx = 0; i < skeletonA.numJoints; i++, idx+=8 ) - { - float jointAPosX = skeletonA.joints[idx+1]; - float jointAPosY = skeletonA.joints[idx+2]; - float jointAPosZ = skeletonA.joints[idx+3]; - - jointAOrient.x = skeletonA.joints[idx+4]; - jointAOrient.y = skeletonA.joints[idx+5]; - jointAOrient.z = skeletonA.joints[idx+6]; - jointAOrient.w = skeletonA.joints[idx+7]; - - float jointBPosX = skeletonB.joints[idx+1]; - float jointBPosY = skeletonB.joints[idx+2]; - float jointBPosZ = skeletonB.joints[idx+3]; - - jointBOrient.x = skeletonB.joints[idx+4]; - jointBOrient.y = skeletonB.joints[idx+5]; - jointBOrient.z = skeletonB.joints[idx+6]; - jointBOrient.w = skeletonB.joints[idx+7]; - + + static MD5Quaternion jointAOrient = new MD5Quaternion(); + static MD5Quaternion jointBOrient = new MD5Quaternion(); + + public static void interpolate (MD5Joints skeletonA, MD5Joints skeletonB, MD5Joints skeletonOut, float t) { + for (int i = 0, idx = 0; i < skeletonA.numJoints; i++, idx += 8) { + float jointAPosX = skeletonA.joints[idx + 1]; + float jointAPosY = skeletonA.joints[idx + 2]; + float jointAPosZ = skeletonA.joints[idx + 3]; + + jointAOrient.x = skeletonA.joints[idx + 4]; + jointAOrient.y = skeletonA.joints[idx + 5]; + jointAOrient.z = skeletonA.joints[idx + 6]; + jointAOrient.w = skeletonA.joints[idx + 7]; + + float jointBPosX = skeletonB.joints[idx + 1]; + float jointBPosY = skeletonB.joints[idx + 2]; + float jointBPosZ = skeletonB.joints[idx + 3]; + + jointBOrient.x = skeletonB.joints[idx + 4]; + jointBOrient.y = skeletonB.joints[idx + 5]; + jointBOrient.z = skeletonB.joints[idx + 6]; + jointBOrient.w = skeletonB.joints[idx + 7]; + skeletonOut.joints[idx] = skeletonA.joints[idx]; - - skeletonOut.joints[idx+1] = jointAPosX + t * (jointBPosX - jointAPosX); - skeletonOut.joints[idx+2] = jointAPosY + t * (jointBPosY - jointAPosY); - skeletonOut.joints[idx+3] = jointAPosZ + t * (jointBPosZ - jointAPosZ); - - jointAOrient.slerp( jointBOrient, t ); - - skeletonOut.joints[idx+4] = jointAOrient.x; - skeletonOut.joints[idx+5] = jointAOrient.y; - skeletonOut.joints[idx+6] = jointAOrient.z; - skeletonOut.joints[idx+7] = jointAOrient.w; + + skeletonOut.joints[idx + 1] = jointAPosX + t * (jointBPosX - jointAPosX); + skeletonOut.joints[idx + 2] = jointAPosY + t * (jointBPosY - jointAPosY); + skeletonOut.joints[idx + 3] = jointAPosZ + t * (jointBPosZ - jointAPosZ); + + jointAOrient.slerp(jointBOrient, t); + + skeletonOut.joints[idx + 4] = jointAOrient.x; + skeletonOut.joints[idx + 5] = jointAOrient.y; + skeletonOut.joints[idx + 6] = jointAOrient.z; + skeletonOut.joints[idx + 7] = jointAOrient.w; } } } diff --git a/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5AnimationInfo.java b/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5AnimationInfo.java index 17ebe4a7a..cba175ecc 100644 --- a/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5AnimationInfo.java +++ b/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5AnimationInfo.java @@ -1,63 +1,53 @@ + package com.badlogic.gdx.graphics.loaders.md5; -public class MD5AnimationInfo -{ +public class MD5AnimationInfo { int currFrame = 0; int nextFrame = 1; int maxFrame; - + float lastTime; - float maxTime; - - public MD5AnimationInfo( int maxFrame, float maxTime ) - { + float maxTime; + + public MD5AnimationInfo (int maxFrame, float maxTime) { this.maxFrame = maxFrame; - this.maxTime = maxTime; + this.maxTime = maxTime; } - - public void reset( ) - { - reset( maxFrame, maxTime ); + + public void reset () { + reset(maxFrame, maxTime); } - - public void reset( int maxFrame, float maxTime ) - { + + public void reset (int maxFrame, float maxTime) { this.maxFrame = maxFrame; this.maxTime = maxTime; this.currFrame = 0; this.nextFrame = 1; this.lastTime = 0; } - - public void update( float delta ) - { + + public void update (float delta) { lastTime += delta; - - if( lastTime >= maxTime ) - { + + if (lastTime >= maxTime) { currFrame++; nextFrame++; lastTime = 0; - - if( currFrame >= maxFrame ) - currFrame = 0; - if( nextFrame >= maxFrame ) - nextFrame = 0; + + if (currFrame >= maxFrame) currFrame = 0; + if (nextFrame >= maxFrame) nextFrame = 0; } } - - public int getCurrentFrame( ) - { + + public int getCurrentFrame () { return currFrame; } - - public int getNextFrame( ) - { + + public int getNextFrame () { return nextFrame; } - - public float getInterpolation( ) - { + + public float getInterpolation () { return lastTime / maxTime; } } diff --git a/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Jni.java b/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Jni.java index 2c451f5c6..ea303fe4c 100644 --- a/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Jni.java +++ b/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Jni.java @@ -1,7 +1,7 @@ -package com.badlogic.gdx.graphics.loaders.md5; +package com.badlogic.gdx.graphics.loaders.md5; -public class MD5Jni -{ - public static native void calculateVertices( float[] skeleton, float[] weights, float[] verticesIn, float[] verticesOut, int numVertices ); +public class MD5Jni { + public static native void calculateVertices (float[] skeleton, float[] weights, float[] verticesIn, float[] verticesOut, + int numVertices); } diff --git a/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Joints.java b/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Joints.java index 0a3b90cbd..9868d313c 100644 --- a/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Joints.java +++ b/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Joints.java @@ -1,9 +1,9 @@ + package com.badlogic.gdx.graphics.loaders.md5; -public class MD5Joints -{ +public class MD5Joints { public String[] names; public int numJoints; /** (0) parent, (1) pos.x, (2) pos.y, (3) pos.z, (4) orient.x, (5) orient.y, (6) orient.z, (7) orient.w **/ - public float[] joints; + public float[] joints; } diff --git a/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Loader.java b/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Loader.java index b62eb660c..3fa463420 100644 --- a/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Loader.java +++ b/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Loader.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.loaders.md5; import java.io.BufferedReader; @@ -10,516 +11,449 @@ import java.util.StringTokenizer; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.collision.BoundingBox; -public class MD5Loader -{ - - public static MD5Model loadModel( InputStream in ) - { - BufferedReader reader = new BufferedReader( new InputStreamReader( in ), 1024 ); - MD5Model model = new MD5Model( ); - Listtokens = new ArrayList( 10 ); - MD5Quaternion quat = new MD5Quaternion( ); - - try - { +public class MD5Loader { + + public static MD5Model loadModel (InputStream in) { + BufferedReader reader = new BufferedReader(new InputStreamReader(in), 1024); + MD5Model model = new MD5Model(); + List tokens = new ArrayList(10); + MD5Quaternion quat = new MD5Quaternion(); + + try { String line; int currMesh = 0; - - while( (line = reader.readLine() ) != null ) - { - tokenize( line, tokens ); - if( tokens.size() == 0 ) - continue; - + + while ((line = reader.readLine()) != null) { + tokenize(line, tokens); + if (tokens.size() == 0) continue; + // // check version string // - if( tokens.get(0).equals( "MD5Version" ) ) - { + if (tokens.get(0).equals("MD5Version")) { int version = parseInt(tokens.get(1)); - if( version != 10 ) - throw new IllegalArgumentException( "Not a valid MD5 file, go version " + version + ", need 10" ); - } - + if (version != 10) + throw new IllegalArgumentException("Not a valid MD5 file, go version " + version + ", need 10"); + } + // // read number of joints // - if( tokens.get(0).equals( "numJoints" ) ) - { - int numJoints = parseInt( tokens.get(1) ); + if (tokens.get(0).equals("numJoints")) { + int numJoints = parseInt(tokens.get(1)); model.baseSkeleton = new MD5Joints(); model.baseSkeleton.names = new String[numJoints]; model.baseSkeleton.numJoints = numJoints; - model.baseSkeleton.joints = new float[numJoints*8]; + model.baseSkeleton.joints = new float[numJoints * 8]; } - + // // read number of meshes // - if( tokens.get(0).equals( "numMeshes" ) ) - { - int numMeshes = parseInt( tokens.get(1) ); + if (tokens.get(0).equals("numMeshes")) { + int numMeshes = parseInt(tokens.get(1)); model.meshes = new MD5Mesh[numMeshes]; } - + // // read joints // - if( tokens.get(0).equals( "joints") ) - { - for( int i = 0; i < model.baseSkeleton.numJoints; i++ ) - { + if (tokens.get(0).equals("joints")) { + for (int i = 0; i < model.baseSkeleton.numJoints; i++) { line = reader.readLine(); - tokenize( line, tokens ); - if( tokens.size() == 0 ) - { + tokenize(line, tokens); + if (tokens.size() == 0) { i--; continue; - } - + } + int jointIdx = i << 3; - model.baseSkeleton.names[i] = tokens.get(0);; - model.baseSkeleton.joints[jointIdx] = parseInt( tokens.get(1) );; - model.baseSkeleton.joints[jointIdx+1] = parseFloat( tokens.get(3) ); - model.baseSkeleton.joints[jointIdx+2] = parseFloat( tokens.get(4) ); - model.baseSkeleton.joints[jointIdx+3] = parseFloat( tokens.get(5) ); - - quat.x = parseFloat( tokens.get(8) ); - quat.y = parseFloat( tokens.get(9) ); - quat.z = parseFloat( tokens.get(10) ); - quat.computeW(); - - model.baseSkeleton.joints[jointIdx+4] = quat.x; - model.baseSkeleton.joints[jointIdx+5] = quat.y; - model.baseSkeleton.joints[jointIdx+6] = quat.z; - model.baseSkeleton.joints[jointIdx+7] = quat.w; + model.baseSkeleton.names[i] = tokens.get(0); + ; + model.baseSkeleton.joints[jointIdx] = parseInt(tokens.get(1)); + ; + model.baseSkeleton.joints[jointIdx + 1] = parseFloat(tokens.get(3)); + model.baseSkeleton.joints[jointIdx + 2] = parseFloat(tokens.get(4)); + model.baseSkeleton.joints[jointIdx + 3] = parseFloat(tokens.get(5)); + + quat.x = parseFloat(tokens.get(8)); + quat.y = parseFloat(tokens.get(9)); + quat.z = parseFloat(tokens.get(10)); + quat.computeW(); + + model.baseSkeleton.joints[jointIdx + 4] = quat.x; + model.baseSkeleton.joints[jointIdx + 5] = quat.y; + model.baseSkeleton.joints[jointIdx + 6] = quat.z; + model.baseSkeleton.joints[jointIdx + 7] = quat.w; } } - + // // read meshes // - if( tokens.get(0).equals( "mesh" ) && tokens.get(1).equals( "{") ) - { - MD5Mesh mesh = new MD5Mesh( ); + if (tokens.get(0).equals("mesh") && tokens.get(1).equals("{")) { + MD5Mesh mesh = new MD5Mesh(); model.meshes[currMesh++] = mesh; - + int vertIndex = 0; int triIndex = 0; int weightIndex = 0; - - - while( !line.contains( "}" ) ) - { - line = reader.readLine( ); - tokenize( line, tokens ); - if( tokens.size() == 0 ) - continue; - - if( tokens.get(0).equals( "shader" ) ) - { + + while (!line.contains("}")) { + line = reader.readLine(); + tokenize(line, tokens); + if (tokens.size() == 0) continue; + + if (tokens.get(0).equals("shader")) { mesh.shader = tokens.get(1); } - if( tokens.get(0).equals( "numverts" ) ) - { - mesh.vertices = new float[parseInt( tokens.get(1) )*4]; + if (tokens.get(0).equals("numverts")) { + mesh.vertices = new float[parseInt(tokens.get(1)) * 4]; mesh.numVertices = mesh.vertices.length / 4; } - if( tokens.get(0).equals( "numtris" ) ) - { - mesh.indices = new short[parseInt( tokens.get(1) )*3]; + if (tokens.get(0).equals("numtris")) { + mesh.indices = new short[parseInt(tokens.get(1)) * 3]; mesh.numTriangles = mesh.indices.length / 3; } - if( tokens.get(0).equals( "numweights" ) ) - { - mesh.weights = new float[parseInt( tokens.get(1) )*5]; + if (tokens.get(0).equals("numweights")) { + mesh.weights = new float[parseInt(tokens.get(1)) * 5]; mesh.numWeights = mesh.weights.length / 5; } - if( tokens.get(0).equals( "vert" ) ) - { - vertIndex = parseInt( tokens.get(1) ); - - int idx = vertIndex*4; - mesh.vertices[idx++] = parseFloat( tokens.get(3) ); // s - mesh.vertices[idx++] = parseFloat( tokens.get(4) ); // t - mesh.vertices[idx++] = parseFloat( tokens.get(6) ); // start - mesh.vertices[idx++] = parseFloat( tokens.get(7) ); // count + if (tokens.get(0).equals("vert")) { + vertIndex = parseInt(tokens.get(1)); + + int idx = vertIndex * 4; + mesh.vertices[idx++] = parseFloat(tokens.get(3)); // s + mesh.vertices[idx++] = parseFloat(tokens.get(4)); // t + mesh.vertices[idx++] = parseFloat(tokens.get(6)); // start + mesh.vertices[idx++] = parseFloat(tokens.get(7)); // count } - if( tokens.get(0).equals( "tri" ) ) - { - triIndex = parseInt( tokens.get(1) ); - - int idx = triIndex*3; - mesh.indices[idx++] = Short.parseShort( tokens.get(2) ); // idx 1 - mesh.indices[idx++] = Short.parseShort( tokens.get(3) ); // idx 2 - mesh.indices[idx++] = Short.parseShort( tokens.get(4) ); // idx 3 + if (tokens.get(0).equals("tri")) { + triIndex = parseInt(tokens.get(1)); + + int idx = triIndex * 3; + mesh.indices[idx++] = Short.parseShort(tokens.get(2)); // idx 1 + mesh.indices[idx++] = Short.parseShort(tokens.get(3)); // idx 2 + mesh.indices[idx++] = Short.parseShort(tokens.get(4)); // idx 3 } - - if( tokens.get(0).equals( "weight" ) ) - { - weightIndex = parseInt( tokens.get(1) ); - - int idx = weightIndex*5; - mesh.weights[idx++] = parseInt( tokens.get(2) ); // joint - mesh.weights[idx++] = parseFloat( tokens.get(3) ); // bias - mesh.weights[idx++] = parseFloat( tokens.get(5) ); // pos.x - mesh.weights[idx++] = parseFloat( tokens.get(6) ); // pos.y - mesh.weights[idx++] = parseFloat( tokens.get(7) ); // pos.z + + if (tokens.get(0).equals("weight")) { + weightIndex = parseInt(tokens.get(1)); + + int idx = weightIndex * 5; + mesh.weights[idx++] = parseInt(tokens.get(2)); // joint + mesh.weights[idx++] = parseFloat(tokens.get(3)); // bias + mesh.weights[idx++] = parseFloat(tokens.get(5)); // pos.x + mesh.weights[idx++] = parseFloat(tokens.get(6)); // pos.y + mesh.weights[idx++] = parseFloat(tokens.get(7)); // pos.z } } } } - + return model; - } - catch( Exception ex ) - { - ex.printStackTrace( ); + } catch (Exception ex) { + ex.printStackTrace(); return null; - } + } } - - public static MD5Animation loadAnimation( InputStream in ) - { - BufferedReader reader = new BufferedReader( new InputStreamReader( in ) ); - List tokens = new ArrayList( ); - MD5Animation animation = new MD5Animation( ); - - try - { + + public static MD5Animation loadAnimation (InputStream in) { + BufferedReader reader = new BufferedReader(new InputStreamReader(in)); + List tokens = new ArrayList(); + MD5Animation animation = new MD5Animation(); + + try { String line; JointInfo[] jointInfos = null; BaseFrameJoint[] baseFrame = null; float[] animFrameData = null; - - while( (line = reader.readLine() ) != null ) - { - tokenize( line, tokens ); - if( tokens.size() == 0 ) - continue; - - if( tokens.get(0).equals( "MD5Version" ) ) - { - if( !tokens.get(1).equals( "10" ) ) - throw new IllegalArgumentException( "Not a valid MD5 animation file, version is " + tokens.get(1) + ", expected 10" ); + + while ((line = reader.readLine()) != null) { + tokenize(line, tokens); + if (tokens.size() == 0) continue; + + if (tokens.get(0).equals("MD5Version")) { + if (!tokens.get(1).equals("10")) + throw new IllegalArgumentException("Not a valid MD5 animation file, version is " + tokens.get(1) + + ", expected 10"); } - - if( tokens.get(0).equals( "numFrames" ) ) - { + + if (tokens.get(0).equals("numFrames")) { int numFrames = parseInt(tokens.get(1)); animation.frames = new MD5Joints[numFrames]; animation.bounds = new BoundingBox[numFrames]; } - - if( tokens.get(0).equals( "numJoints" ) ) - { - int numJoints = parseInt( tokens.get(1) ); - for( int i = 0; i < animation.frames.length; i++ ) - { + + if (tokens.get(0).equals("numJoints")) { + int numJoints = parseInt(tokens.get(1)); + for (int i = 0; i < animation.frames.length; i++) { animation.frames[i] = new MD5Joints(); animation.frames[i].numJoints = numJoints; animation.frames[i].names = new String[numJoints]; - animation.frames[i].joints = new float[numJoints * 8]; + animation.frames[i].joints = new float[numJoints * 8]; } - + jointInfos = new JointInfo[numJoints]; baseFrame = new BaseFrameJoint[numJoints]; } - - if( tokens.get(0).equals( "frameRate" ) ) - { - int frameRate = parseInt( tokens.get(1) ); + + if (tokens.get(0).equals("frameRate")) { + int frameRate = parseInt(tokens.get(1)); animation.frameRate = frameRate; animation.secondsPerFrame = 1.0f / frameRate; } - - if( tokens.get(0).equals( "numAnimatedComponents" ) ) - { - int numAnimatedComponents = parseInt( tokens.get(1) ); + + if (tokens.get(0).equals("numAnimatedComponents")) { + int numAnimatedComponents = parseInt(tokens.get(1)); animFrameData = new float[numAnimatedComponents]; } - - if( tokens.get(0).equals( "hierarchy" ) ) - { - for( int i = 0; i < jointInfos.length; i++ ) - { + + if (tokens.get(0).equals("hierarchy")) { + for (int i = 0; i < jointInfos.length; i++) { line = reader.readLine(); - tokenize( line, tokens ); - if( tokens.size() == 0 || tokens.get(0).equals( "//" )) - { + tokenize(line, tokens); + if (tokens.size() == 0 || tokens.get(0).equals("//")) { i--; continue; } - + JointInfo jointInfo = new JointInfo(); jointInfo.name = tokens.get(0); - jointInfo.parent = parseInt( tokens.get(1) ); - jointInfo.flags = parseInt( tokens.get(2) ); - jointInfo.startIndex = parseInt( tokens.get(3) ); - + jointInfo.parent = parseInt(tokens.get(1)); + jointInfo.flags = parseInt(tokens.get(2)); + jointInfo.startIndex = parseInt(tokens.get(3)); + jointInfos[i] = jointInfo; } } - - if( tokens.get(0).equals( "bounds" ) ) - { - for( int i = 0; i < animation.bounds.length; i++ ) - { + + if (tokens.get(0).equals("bounds")) { + for (int i = 0; i < animation.bounds.length; i++) { line = reader.readLine(); - tokenize( line, tokens ); - if( tokens.size() == 0 ) - { + tokenize(line, tokens); + if (tokens.size() == 0) { i--; continue; } - - BoundingBox bounds = new BoundingBox( ); - bounds.min.x = parseFloat( tokens.get( 1 ) ); - bounds.min.y = parseFloat( tokens.get( 2 ) ); - bounds.min.z = parseFloat( tokens.get( 3 ) ); - - bounds.max.x = parseFloat( tokens.get( 6 ) ); - bounds.max.y = parseFloat( tokens.get( 7 ) ); - bounds.max.z = parseFloat( tokens.get( 8 ) ); - + + BoundingBox bounds = new BoundingBox(); + bounds.min.x = parseFloat(tokens.get(1)); + bounds.min.y = parseFloat(tokens.get(2)); + bounds.min.z = parseFloat(tokens.get(3)); + + bounds.max.x = parseFloat(tokens.get(6)); + bounds.max.y = parseFloat(tokens.get(7)); + bounds.max.z = parseFloat(tokens.get(8)); + animation.bounds[i] = bounds; } } - - if( tokens.get(0).equals( "baseframe" ) ) - { - for( int i = 0; i < baseFrame.length; i++ ) - { + + if (tokens.get(0).equals("baseframe")) { + for (int i = 0; i < baseFrame.length; i++) { line = reader.readLine(); - tokenize( line, tokens ); - if( tokens.size() == 0 ) - { + tokenize(line, tokens); + if (tokens.size() == 0) { i--; continue; } - - BaseFrameJoint joint = new BaseFrameJoint( ); - joint.pos.x = parseFloat( tokens.get(1) ); - joint.pos.y = parseFloat( tokens.get(2) ); - joint.pos.z = parseFloat( tokens.get(3) ); - - joint.orient.x = parseFloat( tokens.get(6) ); - joint.orient.y = parseFloat( tokens.get(7) ); - joint.orient.z = parseFloat( tokens.get(8) ); + + BaseFrameJoint joint = new BaseFrameJoint(); + joint.pos.x = parseFloat(tokens.get(1)); + joint.pos.y = parseFloat(tokens.get(2)); + joint.pos.z = parseFloat(tokens.get(3)); + + joint.orient.x = parseFloat(tokens.get(6)); + joint.orient.y = parseFloat(tokens.get(7)); + joint.orient.z = parseFloat(tokens.get(8)); joint.orient.computeW(); - + baseFrame[i] = joint; } } - - if( tokens.get(0).equals( "frame" ) ) - { - int frameIndex = parseInt( tokens.get(1) ); - + + if (tokens.get(0).equals("frame")) { + int frameIndex = parseInt(tokens.get(1)); + int i = 0; line = reader.readLine(); - tokenize( line, tokens ); - while( tokens.get(0).equals( "}" ) == false ) - { - for( int j = 0; j < tokens.size(); j++ ) - animFrameData[i++] = parseFloat(tokens.get(j) ); - + tokenize(line, tokens); + while (tokens.get(0).equals("}") == false) { + for (int j = 0; j < tokens.size(); j++) + animFrameData[i++] = parseFloat(tokens.get(j)); + line = reader.readLine(); - tokenize( line, tokens ); + tokenize(line, tokens); } - - buildFrameSkeleton( jointInfos, baseFrame, animFrameData, animation, frameIndex ); + + buildFrameSkeleton(jointInfos, baseFrame, animFrameData, animation, frameIndex); } } - + return animation; - } - catch( Exception ex ) - { - ex.printStackTrace( ); + } catch (Exception ex) { + ex.printStackTrace(); return null; } - } - - static MD5Quaternion thisOrient = new MD5Quaternion( ); - static MD5Quaternion parentOrient = new MD5Quaternion( ); - static Vector3 parentPos = new Vector3( ); - - private static float parseFloat( String value ) - { + } + + static MD5Quaternion thisOrient = new MD5Quaternion(); + static MD5Quaternion parentOrient = new MD5Quaternion(); + static Vector3 parentPos = new Vector3(); + + private static float parseFloat (String value) { float front = 0; float back = 0; float sign = 1; boolean isBack = false; int count = 1; int len = value.length(); - for( int i = 0; i < len; i++ ) - { + for (int i = 0; i < len; i++) { char c = value.charAt(i); - if( c == '-' ) - { + if (c == '-') { sign = -1; continue; } - if( c == '+' ) - continue; - if( c == '.' || c == ',' ) - { + if (c == '+') continue; + if (c == '.' || c == ',') { isBack = true; continue; } - + float val = c - '0'; - if( !isBack ) - front = front * 10 + val; - else - back = back + val * ( 1.0f / (float)Math.pow( 10, count++ )); + if (!isBack) + front = front * 10 + val; + else + back = back + val * (1.0f / (float)Math.pow(10, count++)); } - + return sign * (front + back); } - - private static int parseInt( String value ) - { - int front = 0; - int sign = 1; - + + private static int parseInt (String value) { + int front = 0; + int sign = 1; + int len = value.length(); - for( int i = 0; i < len; i++ ) - { + for (int i = 0; i < len; i++) { char c = value.charAt(i); - if( c == '-' ) - { + if (c == '-') { sign = -1; continue; } - if( c == '+' ) - continue; - if( c == '.' || c == ',' ) - { + if (c == '+') continue; + if (c == '.' || c == ',') { break; } - - int val = c - '0'; - front = front * 10 + val; + + int val = c - '0'; + front = front * 10 + val; } - + return sign * front; } - - private static void buildFrameSkeleton( JointInfo[] jointInfos, BaseFrameJoint[] baseFrame, float[] animFrameData, MD5Animation animation, int frameIndex ) - { + + private static void buildFrameSkeleton (JointInfo[] jointInfos, BaseFrameJoint[] baseFrame, float[] animFrameData, + MD5Animation animation, int frameIndex) { MD5Joints skelFrame = animation.frames[frameIndex]; - - for( int i = 0; i < jointInfos.length; i++ ) - { + + for (int i = 0; i < jointInfos.length; i++) { BaseFrameJoint baseJoint = baseFrame[i]; - Vector3 animatedPos = new Vector3( ); - MD5Quaternion animatedOrient = new MD5Quaternion( ); + Vector3 animatedPos = new Vector3(); + MD5Quaternion animatedOrient = new MD5Quaternion(); int j = 0; - - animatedPos.set( baseJoint.pos ); - animatedOrient.set( baseJoint.orient ); - - if( (jointInfos[i].flags & 1) != 0 ) - { + + animatedPos.set(baseJoint.pos); + animatedOrient.set(baseJoint.orient); + + if ((jointInfos[i].flags & 1) != 0) { animatedPos.x = animFrameData[jointInfos[i].startIndex + j]; j++; } - - if( (jointInfos[i].flags & 2 ) != 0 ) - { + + if ((jointInfos[i].flags & 2) != 0) { animatedPos.y = animFrameData[jointInfos[i].startIndex + j]; j++; } - - if( (jointInfos[i].flags & 4) != 0 ) - { + + if ((jointInfos[i].flags & 4) != 0) { animatedPos.z = animFrameData[jointInfos[i].startIndex + j]; j++; } - - if( (jointInfos[i].flags & 8) != 0 ) - { + + if ((jointInfos[i].flags & 8) != 0) { animatedOrient.x = animFrameData[jointInfos[i].startIndex + j]; j++; } - - if( (jointInfos[i].flags & 16) != 0 ) - { + + if ((jointInfos[i].flags & 16) != 0) { animatedOrient.y = animFrameData[jointInfos[i].startIndex + j]; j++; } - - if( (jointInfos[i].flags & 32) != 0 ) - { + + if ((jointInfos[i].flags & 32) != 0) { animatedOrient.z = animFrameData[jointInfos[i].startIndex + j]; j++; } - + animatedOrient.computeW(); - + int thisJointIdx = i << 3; skelFrame.names[i] = jointInfos[i].name; - skelFrame.joints[thisJointIdx] = jointInfos[i].parent; - - if( jointInfos[i].parent < 0 ) - { - skelFrame.joints[thisJointIdx+1] = animatedPos.x; - skelFrame.joints[thisJointIdx+2] = animatedPos.y; - skelFrame.joints[thisJointIdx+3] = animatedPos.z; - - skelFrame.joints[thisJointIdx+4] = animatedOrient.x; - skelFrame.joints[thisJointIdx+5] = animatedOrient.y; - skelFrame.joints[thisJointIdx+6] = animatedOrient.z; - skelFrame.joints[thisJointIdx+7] = animatedOrient.w; - } - else - { + skelFrame.joints[thisJointIdx] = jointInfos[i].parent; + + if (jointInfos[i].parent < 0) { + skelFrame.joints[thisJointIdx + 1] = animatedPos.x; + skelFrame.joints[thisJointIdx + 2] = animatedPos.y; + skelFrame.joints[thisJointIdx + 3] = animatedPos.z; + + skelFrame.joints[thisJointIdx + 4] = animatedOrient.x; + skelFrame.joints[thisJointIdx + 5] = animatedOrient.y; + skelFrame.joints[thisJointIdx + 6] = animatedOrient.z; + skelFrame.joints[thisJointIdx + 7] = animatedOrient.w; + } else { int parentJointIdx = jointInfos[i].parent << 3; parentPos.x = skelFrame.joints[parentJointIdx + 1]; parentPos.y = skelFrame.joints[parentJointIdx + 2]; parentPos.z = skelFrame.joints[parentJointIdx + 3]; - + parentOrient.x = skelFrame.joints[parentJointIdx + 4]; parentOrient.y = skelFrame.joints[parentJointIdx + 5]; parentOrient.z = skelFrame.joints[parentJointIdx + 6]; parentOrient.w = skelFrame.joints[parentJointIdx + 7]; - - parentOrient.rotate( animatedPos ); - skelFrame.joints[thisJointIdx+1] = animatedPos.x + parentPos.x; - skelFrame.joints[thisJointIdx+2] = animatedPos.y + parentPos.y; - skelFrame.joints[thisJointIdx+3] = animatedPos.z + parentPos.z; - - parentOrient.multiply( animatedOrient ); + + parentOrient.rotate(animatedPos); + skelFrame.joints[thisJointIdx + 1] = animatedPos.x + parentPos.x; + skelFrame.joints[thisJointIdx + 2] = animatedPos.y + parentPos.y; + skelFrame.joints[thisJointIdx + 3] = animatedPos.z + parentPos.z; + + parentOrient.multiply(animatedOrient); parentOrient.normalize(); - skelFrame.joints[thisJointIdx+4] = parentOrient.x; - skelFrame.joints[thisJointIdx+5] = parentOrient.y; - skelFrame.joints[thisJointIdx+6] = parentOrient.z; - skelFrame.joints[thisJointIdx+7] = parentOrient.w; + skelFrame.joints[thisJointIdx + 4] = parentOrient.x; + skelFrame.joints[thisJointIdx + 5] = parentOrient.y; + skelFrame.joints[thisJointIdx + 6] = parentOrient.z; + skelFrame.joints[thisJointIdx + 7] = parentOrient.w; } } } - - private static void tokenize( String line, List tokens ) - { + + private static void tokenize (String line, List tokens) { tokens.clear(); - StringTokenizer tokenizer = new StringTokenizer( line ); - while( tokenizer.hasMoreTokens() ) - tokens.add( tokenizer.nextToken() ); + StringTokenizer tokenizer = new StringTokenizer(line); + while (tokenizer.hasMoreTokens()) + tokens.add(tokenizer.nextToken()); } - - static class JointInfo - { + + static class JointInfo { public String name; public int parent; public int flags; public int startIndex; } - - static class BaseFrameJoint - { - public final Vector3 pos = new Vector3( ); - public final MD5Quaternion orient = new MD5Quaternion( ); + + static class BaseFrameJoint { + public final Vector3 pos = new Vector3(); + public final MD5Quaternion orient = new MD5Quaternion(); } } diff --git a/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Mesh.java b/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Mesh.java index 35e23c9a3..c4988293e 100644 --- a/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Mesh.java +++ b/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Mesh.java @@ -1,93 +1,84 @@ -package com.badlogic.gdx.graphics.loaders.md5; +package com.badlogic.gdx.graphics.loaders.md5; -public class MD5Mesh -{ +public class MD5Mesh { public String shader; - + public int numVertices; public int numWeights; public int numTriangles; - /** s, t, start, count **/ + /** s, t, start, count **/ public float[] vertices; /** joint, bias, pos.x, pos.y, pos.z **/ public float[] weights; /** idx 1, idx 2, idx 3 **/ - public short[] indices; - - public float[] createVertexArray( ) - { + public short[] indices; + + public float[] createVertexArray () { float[] verts = new float[numVertices * 5]; - for( int i = 0, j = 3; i < vertices.length; i+=4 ) - { + for (int i = 0, j = 3; i < vertices.length; i += 4) { verts[j++] = vertices[i]; - verts[j++] = vertices[i+1]; - j+=3; + verts[j++] = vertices[i + 1]; + j += 3; } - + return verts; } - - public short[] getIndices( ) - { + + public short[] getIndices () { return indices; } - - public void calculateVertices( MD5Joints skeleton, float[] verts ) - { - calculateVertices( skeleton, weights, vertices, verts ); + + public void calculateVertices (MD5Joints skeleton, float[] verts) { + calculateVertices(skeleton, weights, vertices, verts); } - - public static void calculateVertices( MD5Joints skeleton, float[] weights, float vertices[], float[] verts ) - { - for( int vertexOffset = 2, k = 0; vertexOffset < vertices.length; vertexOffset += 4 ) - { + + public static void calculateVertices (MD5Joints skeleton, float[] weights, float vertices[], float[] verts) { + for (int vertexOffset = 2, k = 0; vertexOffset < vertices.length; vertexOffset += 4) { float finalX = 0; float finalY = 0; float finalZ = 0; - + int weightOffset = (int)vertices[vertexOffset]; - int weightCount = (int)vertices[vertexOffset+1]; + int weightCount = (int)vertices[vertexOffset + 1]; weightOffset = (weightOffset << 2) + weightOffset; - - for( int j = 0; j < weightCount; j++ ) - { - int jointOffset = (int)weights[weightOffset++] << 3; - float bias = weights[weightOffset++]; + + for (int j = 0; j < weightCount; j++) { + int jointOffset = (int)weights[weightOffset++] << 3; + float bias = weights[weightOffset++]; float vx = weights[weightOffset++]; float vy = weights[weightOffset++]; float vz = weights[weightOffset++]; - - float qx = skeleton.joints[jointOffset+4]; - float qy = skeleton.joints[jointOffset+5]; - float qz = skeleton.joints[jointOffset+6]; - float qw = skeleton.joints[jointOffset+7]; - - float ix = -qx, iy = -qy, iz = -qz, iw = qw; - + + float qx = skeleton.joints[jointOffset + 4]; + float qy = skeleton.joints[jointOffset + 5]; + float qz = skeleton.joints[jointOffset + 6]; + float qw = skeleton.joints[jointOffset + 7]; + + float ix = -qx, iy = -qy, iz = -qz, iw = qw; + float tw = -qx * vx - qy * vy - qz * vz; - float tx = qw * vx + qy * vz - qz * vy; - float ty = qw * vy + qz * vx - qx * vz; - float tz = qw * vz + qx * vy - qy * vx; - + float tx = qw * vx + qy * vz - qz * vy; + float ty = qw * vy + qz * vx - qx * vz; + float tz = qw * vz + qx * vy - qy * vx; + vx = tx * iw + tw * ix + ty * iz - tz * iy; vy = ty * iw + tw * iy + tz * ix - tx * iz; - vz = tz * iw + tw * iz + tx * iy - ty * ix; - - finalX += (skeleton.joints[jointOffset+1] + vx) * bias; - finalY += (skeleton.joints[jointOffset+2] + vy) * bias; - finalZ += (skeleton.joints[jointOffset+3] + vz) * bias; + vz = tz * iw + tw * iz + tx * iy - ty * ix; + + finalX += (skeleton.joints[jointOffset + 1] + vx) * bias; + finalY += (skeleton.joints[jointOffset + 2] + vy) * bias; + finalZ += (skeleton.joints[jointOffset + 3] + vz) * bias; } - + verts[k++] = finalX; verts[k++] = finalY; verts[k++] = finalZ; - k+=2; + k += 2; } - } - - public void calculateVerticesJni( MD5Joints skeleton, float[] verts ) - { - MD5Jni.calculateVertices( skeleton.joints, weights, vertices, verts, numVertices ); + } + + public void calculateVerticesJni (MD5Joints skeleton, float[] verts) { + MD5Jni.calculateVertices(skeleton.joints, weights, vertices, verts, numVertices); } } diff --git a/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Model.java b/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Model.java index 9c630299b..fe4a20a6e 100644 --- a/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Model.java +++ b/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Model.java @@ -1,28 +1,26 @@ + package com.badlogic.gdx.graphics.loaders.md5; -public class MD5Model -{ +public class MD5Model { public int numJoints; public MD5Joints baseSkeleton; public MD5Mesh[] meshes; - - public int getNumVertices( ) - { + + public int getNumVertices () { int numVertices = 0; - - for( int i = 0; i < meshes.length; i++ ) + + for (int i = 0; i < meshes.length; i++) numVertices += meshes[i].numVertices; - + return numVertices; } - - public int getNumTriangles( ) - { + + public int getNumTriangles () { int numTriangles = 0; - - for( int i = 0; i < meshes.length; i++ ) + + for (int i = 0; i < meshes.length; i++) numTriangles += meshes[i].numTriangles; - + return numTriangles; } } diff --git a/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Quaternion.java b/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Quaternion.java index 4e154dabd..99c9bfeb6 100644 --- a/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Quaternion.java +++ b/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Quaternion.java @@ -1,165 +1,151 @@ + package com.badlogic.gdx.graphics.loaders.md5; import com.badlogic.gdx.math.Vector3; -public class MD5Quaternion -{ +public class MD5Quaternion { public float x, y, z, w; - - public MD5Quaternion( ) - { - + + public MD5Quaternion () { + } - - public MD5Quaternion( float x, float y, float z ) - { + + public MD5Quaternion (float x, float y, float z) { this.x = x; this.y = y; this.z = z; - computeW( ); + computeW(); } - - public MD5Quaternion( float x, float y, float z, float w ) - { + + public MD5Quaternion (float x, float y, float z, float w) { this.x = x; this.y = y; this.z = z; this.w = w; } - - public void set( MD5Quaternion q ) - { + + public void set (MD5Quaternion q) { this.w = q.w; this.x = q.x; this.y = q.y; this.z = q.z; } - - public void computeW( ) - { + + public void computeW () { float t = 1.0f - x * x - y * y - z * z; - - if( t < 0.0f ) + + if (t < 0.0f) w = 0; else - w = -(float)Math.sqrt( t ); + w = -(float)Math.sqrt(t); } - - public void normalize( ) - { - float mag = (float)Math.sqrt( x * x + y * y + z * z + w * w ); - - if( mag > 0 ) - { + + public void normalize () { + float mag = (float)Math.sqrt(x * x + y * y + z * z + w * w); + + if (mag > 0) { float inv = 1.0f / mag; - + x *= inv; y *= inv; z *= inv; w *= inv; } } - - public void multiply( MD5Quaternion q ) - { + + public void multiply (MD5Quaternion q) { float tw = w * q.w - x * q.x - y * q.y - z * q.z; float tx = x * q.w + w * q.x + y * q.z - z * q.y; float ty = y * q.w + w * q.y + z * q.x - x * q.z; float tz = z * q.w + w * q.z + x * q.y - y * q.x; - + w = tw; x = tx; y = ty; - z = tz; + z = tz; } - - public void multiply( Vector3 v ) - { + + public void multiply (Vector3 v) { float tw = -x * v.x - y * v.y - z * v.z; - float tx = w * v.x + y * v.z - z * v.y; - float ty = w * v.y + z * v.x - x * v.z; - float tz = w * v.z + x * v.y - y * v.x; - + float tx = w * v.x + y * v.z - z * v.y; + float ty = w * v.y + z * v.x - x * v.z; + float tz = w * v.z + x * v.y - y * v.x; + w = tw; x = tx; y = ty; z = tz; } - - private static final MD5Quaternion tmp = new MD5Quaternion( ); - private static final MD5Quaternion inv = new MD5Quaternion( ); - public void rotate( Vector3 vec ) - { - inv.x = -x; inv.y = -y; inv.z = -z; inv.w = w; - -// inv.normalize(); - tmp.set( this ); - tmp.multiply( vec ); - tmp.multiply( inv ); - + + private static final MD5Quaternion tmp = new MD5Quaternion(); + private static final MD5Quaternion inv = new MD5Quaternion(); + + public void rotate (Vector3 vec) { + inv.x = -x; + inv.y = -y; + inv.z = -z; + inv.w = w; + +// inv.normalize(); + tmp.set(this); + tmp.multiply(vec); + tmp.multiply(inv); + vec.x = tmp.x; vec.y = tmp.y; - vec.z = tmp.z; + vec.z = tmp.z; } - - public float dot( MD5Quaternion q ) - { + + public float dot (MD5Quaternion q) { return x * q.x + y * q.y + z * q.z + w * q.w; } - - public void slerp( MD5Quaternion q, float t ) - { - if( t <= 0 ) - return; - - if( t >= 1 ) - { - set( q ); + + public void slerp (MD5Quaternion q, float t) { + if (t <= 0) return; + + if (t >= 1) { + set(q); return; } - - float cosOmega = dot( q ); - + + float cosOmega = dot(q); + float q1w = q.w; float q1x = q.x; float q1y = q.y; float q1z = q.z; - - if( cosOmega < 0 ) - { + + if (cosOmega < 0) { q1w = -q1w; q1x = -q1x; q1y = -q1y; - q1z = -q1z; + q1z = -q1z; cosOmega = -cosOmega; } - + assert cosOmega < 1.1f; - + float k0, k1; - - if( cosOmega > 0.9999f ) - { + + if (cosOmega > 0.9999f) { k0 = 1.0f - t; k1 = t; - } - else - { - float sinOmega = (float)Math.sqrt( 1.0f - (cosOmega * cosOmega ) ); - float omega = (float)Math.atan2( sinOmega, cosOmega ); + } else { + float sinOmega = (float)Math.sqrt(1.0f - (cosOmega * cosOmega)); + float omega = (float)Math.atan2(sinOmega, cosOmega); float oneOverSinOmega = 1.0f / sinOmega; - k0 = (float)Math.sin( (1.0f - t) * omega ) * oneOverSinOmega; - k1 = (float)Math.sin( t * omega ) * oneOverSinOmega; + k0 = (float)Math.sin((1.0f - t) * omega) * oneOverSinOmega; + k1 = (float)Math.sin(t * omega) * oneOverSinOmega; } - + w = k0 * w + k1 * q1w; x = k0 * x + k1 * q1x; y = k0 * y + k1 * q1y; z = k0 * z + k1 * q1z; } - - public String toString( ) - { - return String.format( "%.4f", x ) + ", " + String.format( "%.4f", y ) + ", " + String.format( "%.4f", z ) + ", " + String.format( "%.4f", w ); + + public String toString () { + return String.format("%.4f", x) + ", " + String.format("%.4f", y) + ", " + String.format("%.4f", z) + ", " + + String.format("%.4f", w); } } diff --git a/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Renderer.java b/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Renderer.java index e748a2527..cfbe3c302 100644 --- a/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Renderer.java +++ b/gdx/src/com/badlogic/gdx/graphics/loaders/md5/MD5Renderer.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.loaders.md5; import com.badlogic.gdx.graphics.GL10; @@ -5,74 +6,61 @@ import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.VertexAttributes; -public class MD5Renderer -{ +public class MD5Renderer { private final MD5Model model; private final Mesh mesh; private final short[][] indices; - private final float[][] vertices; + private final float[][] vertices; private boolean useJni; - - public MD5Renderer( MD5Model model, boolean useJni ) - { + + public MD5Renderer (MD5Model model, boolean useJni) { int maxVertices = 0; int maxIndices = 0; - + this.model = model; this.useJni = useJni; this.indices = new short[model.meshes.length][]; this.vertices = new float[model.meshes.length][]; - - for( int i = 0; i < model.meshes.length; i++ ) - { - if( maxVertices < model.meshes[i].numVertices ) - maxVertices = model.meshes[i].numVertices; - if( maxIndices < model.meshes[i].numTriangles * 3 ) - maxIndices = model.meshes[i].numTriangles * 3; - + + for (int i = 0; i < model.meshes.length; i++) { + if (maxVertices < model.meshes[i].numVertices) maxVertices = model.meshes[i].numVertices; + if (maxIndices < model.meshes[i].numTriangles * 3) maxIndices = model.meshes[i].numTriangles * 3; + this.indices[i] = model.meshes[i].getIndices(); this.vertices[i] = model.meshes[i].createVertexArray(); } - - this.mesh = new Mesh( false, false, maxVertices, maxIndices, - new VertexAttribute( VertexAttributes.Usage.Position, 3, "a_position" ), - new VertexAttribute( VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoords" ) ); + + this.mesh = new Mesh(false, false, maxVertices, maxIndices, new VertexAttribute(VertexAttributes.Usage.Position, 3, + "a_position"), new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoords")); } - - public void setSkeleton( MD5Joints skeleton ) - { - for( int i = 0; i < model.meshes.length; i++ ) - { + + public void setSkeleton (MD5Joints skeleton) { + for (int i = 0; i < model.meshes.length; i++) { MD5Mesh mesh = model.meshes[i]; - if( useJni ) - mesh.calculateVerticesJni( skeleton, vertices[i] ); + if (useJni) + mesh.calculateVerticesJni(skeleton, vertices[i]); else - mesh.calculateVertices( skeleton, vertices[i] ); + mesh.calculateVertices(skeleton, vertices[i]); } } - - public void setUseJni( boolean useJni ) - { + + public void setUseJni (boolean useJni) { this.useJni = useJni; } - - public void render( ) - { - for( int i = 0; i < model.meshes.length; i++ ) - { - this.mesh.setIndices( indices[i] ); - this.mesh.setVertices( vertices[i] ); - this.mesh.render( GL10.GL_TRIANGLES, 0, indices[i].length ); + + public void render () { + for (int i = 0; i < model.meshes.length; i++) { + this.mesh.setIndices(indices[i]); + this.mesh.setVertices(vertices[i]); + this.mesh.render(GL10.GL_TRIANGLES, 0, indices[i].length); } } - - public void dispose( ) - { - mesh.dispose( ); + + public void dispose () { + mesh.dispose(); } - public boolean isJniUsed() - { + public boolean isJniUsed () { return useJni; } } diff --git a/gdx/src/com/badlogic/gdx/math/CatmullRomSpline.java b/gdx/src/com/badlogic/gdx/math/CatmullRomSpline.java index ad99d0073..4b76f9c07 100644 --- a/gdx/src/com/badlogic/gdx/math/CatmullRomSpline.java +++ b/gdx/src/com/badlogic/gdx/math/CatmullRomSpline.java @@ -1,238 +1,212 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math; import java.util.ArrayList; import java.util.List; /** - * Encapsulates a catmull rom spline with n control points, n >= 4. For more information on this - * type of spline see http://www.mvps.org/directx/articles/catmull/. + * Encapsulates a catmull rom spline with n control points, n >= 4. For more information on this type of spline see + * http://www.mvps.org/directx/articles/catmull/. * * @author badlogicgames@gmail.com - * + * */ -public final class CatmullRomSpline -{ +public final class CatmullRomSpline { /** * */ private static final long serialVersionUID = -3290464799289771451L; - private List controlPoints = new ArrayList( ); - + private List controlPoints = new ArrayList(); + /** - * Adds a new control point + * Adds a new control point * @param point the point */ - public void add( Vector3 point ) - { - controlPoints.add( point ); + public void add (Vector3 point) { + controlPoints.add(point); } - + /** * @return all control points */ - public List getControlPoints( ) - { + public List getControlPoints () { return controlPoints; } - + /** - * Returns a path, between every two control - * points numPoints are generated and the control - * points themselves are added too. The first - * and the last controlpoint are omitted. if - * there's less than 4 controlpoints an empty - * path is returned. + * Returns a path, between every two control points numPoints are generated and the control points themselves are added too. + * The first and the last controlpoint are omitted. if there's less than 4 controlpoints an empty path is returned. * - * @param numPoints number of points returned for a segment + * @param numPoints number of points returned for a segment * @return the path */ - public List getPath( int numPoints ) - { - ArrayList points = new ArrayList( ); - - if( controlPoints.size() < 4 ) - return points; - - Vector3 T1 = new Vector3( ); - Vector3 T2 = new Vector3( ); - - for( int i = 1; i <= controlPoints.size() - 3; i++ ) - { + public List getPath (int numPoints) { + ArrayList points = new ArrayList(); + + if (controlPoints.size() < 4) return points; + + Vector3 T1 = new Vector3(); + Vector3 T2 = new Vector3(); + + for (int i = 1; i <= controlPoints.size() - 3; i++) { points.add(controlPoints.get(i)); float increment = 1.0f / (numPoints + 1); float t = increment; - - T1.set(controlPoints.get(i+1)).sub(controlPoints.get(i-1)).mul(0.5f); - T2.set(controlPoints.get(i+2)).sub(controlPoints.get(i)).mul(0.5f); - - for( int j = 0; j < numPoints; j++ ) - { - float h1 = 2*t*t*t - 3*t*t + 1; // calculate basis function 1 - float h2 = -2*t*t*t + 3*t*t; // calculate basis function 2 - float h3 = t*t*t - 2*t*t + t; // calculate basis function 3 - float h4 = t*t*t - t*t; // calculate basis function 4 - - Vector3 point = new Vector3( controlPoints.get(i) ).mul( h1 ); - point.add( controlPoints.get(i+1).tmp().mul(h2) ); - point.add( T1.tmp().mul(h3) ); - point.add( T2.tmp().mul(h4) ); - points.add( point ); + + T1.set(controlPoints.get(i + 1)).sub(controlPoints.get(i - 1)).mul(0.5f); + T2.set(controlPoints.get(i + 2)).sub(controlPoints.get(i)).mul(0.5f); + + for (int j = 0; j < numPoints; j++) { + float h1 = 2 * t * t * t - 3 * t * t + 1; // calculate basis function 1 + float h2 = -2 * t * t * t + 3 * t * t; // calculate basis function 2 + float h3 = t * t * t - 2 * t * t + t; // calculate basis function 3 + float h4 = t * t * t - t * t; // calculate basis function 4 + + Vector3 point = new Vector3(controlPoints.get(i)).mul(h1); + point.add(controlPoints.get(i + 1).tmp().mul(h2)); + point.add(T1.tmp().mul(h3)); + point.add(T2.tmp().mul(h4)); + points.add(point); t += increment; } - } - - if( controlPoints.size() >= 4 ) - points.add( controlPoints.get(controlPoints.size()-2) ); - + } + + if (controlPoints.size() >= 4) points.add(controlPoints.get(controlPoints.size() - 2)); + return points; } - + /** - * Returns all tangents for the points in a path. - * Same semantics as getPath. + * Returns all tangents for the points in a path. Same semantics as getPath. * - * @param numPoints number of points returned for a segment + * @param numPoints number of points returned for a segment * @return the tangents of the points in the path */ - public List getTangents( int numPoints ) - { - ArrayList tangents = new ArrayList( ); - - if( controlPoints.size() < 4 ) - return tangents; - - Vector3 T1 = new Vector3( ); - Vector3 T2 = new Vector3( ); - - for( int i = 1; i <= controlPoints.size() - 3; i++ ) - { + public List getTangents (int numPoints) { + ArrayList tangents = new ArrayList(); + + if (controlPoints.size() < 4) return tangents; + + Vector3 T1 = new Vector3(); + Vector3 T2 = new Vector3(); + + for (int i = 1; i <= controlPoints.size() - 3; i++) { float increment = 1.0f / (numPoints + 1); float t = increment; - - T1.set(controlPoints.get(i+1)).sub(controlPoints.get(i-1)).mul(0.5f); - T2.set(controlPoints.get(i+2)).sub(controlPoints.get(i)).mul(0.5f); - - tangents.add(new Vector3( T1 ).nor() ); - - for( int j = 0; j < numPoints; j++ ) - { - float h1 = 6*t*t - 6*t; // calculate basis function 1 - float h2 = -6*t*t + 6*t; // calculate basis function 2 - float h3 = 3*t*t - 4*t + 1; // calculate basis function 3 - float h4 = 3*t*t - 2*t; // calculate basis function 4 - - Vector3 point = new Vector3( controlPoints.get(i) ).mul( h1 ); - point.add( controlPoints.get(i+1).tmp().mul(h2) ); - point.add( T1.tmp().mul(h3) ); - point.add( T2.tmp().mul(h4) ); - tangents.add( point.nor() ); + + T1.set(controlPoints.get(i + 1)).sub(controlPoints.get(i - 1)).mul(0.5f); + T2.set(controlPoints.get(i + 2)).sub(controlPoints.get(i)).mul(0.5f); + + tangents.add(new Vector3(T1).nor()); + + for (int j = 0; j < numPoints; j++) { + float h1 = 6 * t * t - 6 * t; // calculate basis function 1 + float h2 = -6 * t * t + 6 * t; // calculate basis function 2 + float h3 = 3 * t * t - 4 * t + 1; // calculate basis function 3 + float h4 = 3 * t * t - 2 * t; // calculate basis function 4 + + Vector3 point = new Vector3(controlPoints.get(i)).mul(h1); + point.add(controlPoints.get(i + 1).tmp().mul(h2)); + point.add(T1.tmp().mul(h3)); + point.add(T2.tmp().mul(h4)); + tangents.add(point.nor()); t += increment; } - } - - if( controlPoints.size() >= 4 ) - tangents.add( T1.set(controlPoints.get(controlPoints.size()-1)).sub(controlPoints.get(controlPoints.size()-3)).mul(0.5f).cpy().nor() ); - - return tangents; + } + + if (controlPoints.size() >= 4) + tangents.add(T1.set(controlPoints.get(controlPoints.size() - 1)).sub(controlPoints.get(controlPoints.size() - 3)) + .mul(0.5f).cpy().nor()); + + return tangents; } - + /** - * Returns all tangent's normals in 2D space for the points in a path. - * The controlpoints have to lie in the x/y plane for this to work. - * Same semantics as getPath. + * Returns all tangent's normals in 2D space for the points in a path. The controlpoints have to lie in the x/y plane for this + * to work. Same semantics as getPath. * - * @param numPoints number of points returned for a segment + * @param numPoints number of points returned for a segment * @return the tangents of the points in the path */ - public List getTangentNormals2D( int numPoints ) - { - ArrayList tangents = new ArrayList( ); - - if( controlPoints.size() < 4 ) - return tangents; - - Vector3 T1 = new Vector3( ); - Vector3 T2 = new Vector3( ); - - for( int i = 1; i <= controlPoints.size() - 3; i++ ) - { + public List getTangentNormals2D (int numPoints) { + ArrayList tangents = new ArrayList(); + + if (controlPoints.size() < 4) return tangents; + + Vector3 T1 = new Vector3(); + Vector3 T2 = new Vector3(); + + for (int i = 1; i <= controlPoints.size() - 3; i++) { float increment = 1.0f / (numPoints + 1); float t = increment; - - T1.set(controlPoints.get(i+1)).sub(controlPoints.get(i-1)).mul(0.5f); - T2.set(controlPoints.get(i+2)).sub(controlPoints.get(i)).mul(0.5f); - - Vector3 normal = new Vector3( T1 ).nor(); + + T1.set(controlPoints.get(i + 1)).sub(controlPoints.get(i - 1)).mul(0.5f); + T2.set(controlPoints.get(i + 2)).sub(controlPoints.get(i)).mul(0.5f); + + Vector3 normal = new Vector3(T1).nor(); float x = normal.x; normal.x = normal.y; normal.y = -x; - tangents.add( normal ); - - for( int j = 0; j < numPoints; j++ ) - { - float h1 = 6*t*t - 6*t; // calculate basis function 1 - float h2 = -6*t*t + 6*t; // calculate basis function 2 - float h3 = 3*t*t - 4*t + 1; // calculate basis function 3 - float h4 = 3*t*t - 2*t; // calculate basis function 4 - - Vector3 point = new Vector3( controlPoints.get(i) ).mul( h1 ); - point.add( controlPoints.get(i+1).tmp().mul(h2) ); - point.add( T1.tmp().mul(h3) ); - point.add( T2.tmp().mul(h4) ); + tangents.add(normal); + + for (int j = 0; j < numPoints; j++) { + float h1 = 6 * t * t - 6 * t; // calculate basis function 1 + float h2 = -6 * t * t + 6 * t; // calculate basis function 2 + float h3 = 3 * t * t - 4 * t + 1; // calculate basis function 3 + float h4 = 3 * t * t - 2 * t; // calculate basis function 4 + + Vector3 point = new Vector3(controlPoints.get(i)).mul(h1); + point.add(controlPoints.get(i + 1).tmp().mul(h2)); + point.add(T1.tmp().mul(h3)); + point.add(T2.tmp().mul(h4)); point.nor(); x = point.x; point.x = point.y; point.y = -x; - tangents.add( point ); + tangents.add(point); t += increment; } - } - - return tangents; + } + + return tangents; } - + /** - * Returns the tangent's normals using the tangent and provided - * up vector doing a cross product. + * Returns the tangent's normals using the tangent and provided up vector doing a cross product. * @param numPoints number of points per segment - * @param up up vector - * @return + * @param up up vector + * @return */ - public List getTangentNormals( int numPoints, Vector3 up ) - { - List tangents = getTangents( numPoints ); + public List getTangentNormals (int numPoints, Vector3 up) { + List tangents = getTangents(numPoints); ArrayList normals = new ArrayList(); - - for( Vector3 tangent: tangents ) - normals.add( new Vector3( tangent ).crs( up ).nor() ); - - return normals; + + for (Vector3 tangent : tangents) + normals.add(new Vector3(tangent).crs(up).nor()); + + return normals; } - - public List getTangentNormals( int numPoints, List up ) - { - List tangents = getTangents( numPoints ); + + public List getTangentNormals (int numPoints, List up) { + List tangents = getTangents(numPoints); ArrayList normals = new ArrayList(); - + int i = 0; - for( Vector3 tangent: tangents ) - normals.add( new Vector3( tangent ).crs( up.get(i++) ).nor() ); - - return normals; + for (Vector3 tangent : tangents) + normals.add(new Vector3(tangent).crs(up.get(i++)).nor()); + + return normals; } } diff --git a/gdx/src/com/badlogic/gdx/math/EarCutTriangulator.java b/gdx/src/com/badlogic/gdx/math/EarCutTriangulator.java index b65cd17a0..13938bf89 100644 --- a/gdx/src/com/badlogic/gdx/math/EarCutTriangulator.java +++ b/gdx/src/com/badlogic/gdx/math/EarCutTriangulator.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math; import java.util.ArrayList; @@ -20,327 +18,280 @@ import java.util.Collections; import java.util.List; /** - * A simple implementation of the ear cutting algorithm to triangulate - * simple polygons without holes. For more information see http://cgm.cs.mcgill.ca/~godfried/teaching/cg-projects/97/Ian/algorithm2.html + * A simple implementation of the ear cutting algorithm to triangulate simple polygons without holes. For more information see + * http://cgm.cs.mcgill.ca/~godfried/teaching/cg-projects/97/Ian/algorithm2.html * @author badlogicgames@gmail.com - * + * */ -public final class EarCutTriangulator -{ +public final class EarCutTriangulator { /** - * Triangulates the list of points and returns an array - * of {@link Vector3} triples that each form a single triangle. + * Triangulates the list of points and returns an array of {@link Vector3} triples that each form a single triangle. * * @param polygon The polygon to triangulate * @return The list of triangle vertices. */ - public List triangulate( List polygon ) - { - List triangles = new ArrayList( ); - List tmp = new ArrayList( polygon.size() ); - tmp.addAll( polygon ); + public List triangulate (List polygon) { + List triangles = new ArrayList(); + List tmp = new ArrayList(polygon.size()); + tmp.addAll(polygon); polygon = tmp; - - if( polygon.size() == 3 ) - { + + if (polygon.size() == 3) { triangles.addAll(polygon); return triangles; } - - while( polygon.size() >= 3 ) - { - int ptType[] = classifyPoints( polygon ); - - for( int i = 0; i < polygon.size(); i++ ) - { - float x1 = polygon.get(i==0?polygon.size()-1:i-1).x; - float y1 = polygon.get(i==0?polygon.size()-1:i-1).y; + while (polygon.size() >= 3) { + int ptType[] = classifyPoints(polygon); + + for (int i = 0; i < polygon.size(); i++) { + float x1 = polygon.get(i == 0 ? polygon.size() - 1 : i - 1).x; + float y1 = polygon.get(i == 0 ? polygon.size() - 1 : i - 1).y; float x2 = polygon.get(i).x; float y2 = polygon.get(i).y; - float x3 = polygon.get(i==polygon.size()-1?0:i+1).x; - float y3 = polygon.get(i==polygon.size()-1?0:i+1).y; - - if( ear( polygon, ptType, x1, y1, x2, y2, x3, y3 ) ) - { + float x3 = polygon.get(i == polygon.size() - 1 ? 0 : i + 1).x; + float y3 = polygon.get(i == polygon.size() - 1 ? 0 : i + 1).y; + + if (ear(polygon, ptType, x1, y1, x2, y2, x3, y3)) { cutEar(polygon, triangles, i); - updatePolygon( polygon, i); + updatePolygon(polygon, i); break; } } } - -// if( polygon.size() == 3 ) -// { -// triangles.add( polygon.get(0) ); -// triangles.add( polygon.get(1) ); -// triangles.add( polygon.get(2) ); -// } - + +// if( polygon.size() == 3 ) +// { +// triangles.add( polygon.get(0) ); +// triangles.add( polygon.get(1) ); +// triangles.add( polygon.get(2) ); +// } + return triangles; } - /* polygonClockwise: Returns true if user inputted polygon in - * clockwise order, false if counterclockwise. - * The Law of Cosines is used to determine the - * angle. + /* + * polygonClockwise: Returns true if user inputted polygon in clockwise order, false if counterclockwise. The Law of Cosines is + * used to determine the angle. */ - public boolean polygonClockwise(List polygon) - { + public boolean polygonClockwise (List polygon) { float area = 0; - for( int i = 0; i < polygon.size();i++ ) - { + for (int i = 0; i < polygon.size(); i++) { Vector2 p1 = polygon.get(i); - Vector2 p2 = polygon.get(i==polygon.size()-1?0:i+1); + Vector2 p2 = polygon.get(i == polygon.size() - 1 ? 0 : i + 1); area += p1.x * p2.y - p2.x * p1.y; } - - if( area < 0 ) + + if (area < 0) return true; else return false; - -// float aa, bb, cc, b, c, theta; -// float convex_turn; -// float convex_sum = 0; + +// float aa, bb, cc, b, c, theta; +// float convex_turn; +// float convex_sum = 0; // -// for (int i = 0; i < polygon.size() - 2; i++) { -// aa = ((polygon.get(i+2).getX() - polygon.get(i).getX()) * (polygon.get(i+2).getX() - polygon.get(i).getX())) + -// ((-polygon.get(i+2).getY() + polygon.get(i).getY()) * (-polygon.get(i+2).getY() + polygon.get(i).getY())); +// for (int i = 0; i < polygon.size() - 2; i++) { +// aa = ((polygon.get(i+2).getX() - polygon.get(i).getX()) * (polygon.get(i+2).getX() - polygon.get(i).getX())) + +// ((-polygon.get(i+2).getY() + polygon.get(i).getY()) * (-polygon.get(i+2).getY() + polygon.get(i).getY())); // -// bb = ((polygon.get(i+1).getX() - polygon.get(i).getX()) * (polygon.get(i+1).getX() - polygon.get(i).getX()) + -// ((-polygon.get(i+1).getY() + polygon.get(i).getY()) * (-polygon.get(i+1).getY() + polygon.get(i).getY()))); +// bb = ((polygon.get(i+1).getX() - polygon.get(i).getX()) * (polygon.get(i+1).getX() - polygon.get(i).getX()) + +// ((-polygon.get(i+1).getY() + polygon.get(i).getY()) * (-polygon.get(i+1).getY() + polygon.get(i).getY()))); // -// cc = ((polygon.get(i+2).getX() - polygon.get(i+1).getX()) * -// (polygon.get(i+2).getX() - polygon.get(i+1).getX())) + -// ((-polygon.get(i+2).getY() + polygon.get(i+1).getY()) * -// (-polygon.get(i+2).getY() + polygon.get(i+1).getY())); +// cc = ((polygon.get(i+2).getX() - polygon.get(i+1).getX()) * +// (polygon.get(i+2).getX() - polygon.get(i+1).getX())) + +// ((-polygon.get(i+2).getY() + polygon.get(i+1).getY()) * +// (-polygon.get(i+2).getY() + polygon.get(i+1).getY())); // -// b = (float)Math.sqrt(bb); -// c = (float)Math.sqrt(cc); -// theta = (float)Math.acos((bb + cc - aa) / (2 * b * c)); +// b = (float)Math.sqrt(bb); +// c = (float)Math.sqrt(cc); +// theta = (float)Math.acos((bb + cc - aa) / (2 * b * c)); // -// if (convex(polygon.get(i).getX(), polygon.get(i).getY(), -// polygon.get(i+1).getX(), polygon.get(i+1).getY(), -// polygon.get(i+2).getX(), polygon.get(i+2).getY())) { -// convex_turn = (float)Math.PI - theta; -// convex_sum += convex_turn; -// } -// else { -// convex_sum -= Math.PI - theta; -// } -// } -// aa = ((polygon.get(1).getX() - polygon.get(polygon.size()-1).getX()) * -// (polygon.get(1).getX() - polygon.get(polygon.size()-1).getX())) + -// ((-polygon.get(1).getY() + polygon.get(polygon.size()-1).getY()) * -// (-polygon.get(1).getY() + polygon.get(polygon.size()-1).getY())); +// if (convex(polygon.get(i).getX(), polygon.get(i).getY(), +// polygon.get(i+1).getX(), polygon.get(i+1).getY(), +// polygon.get(i+2).getX(), polygon.get(i+2).getY())) { +// convex_turn = (float)Math.PI - theta; +// convex_sum += convex_turn; +// } +// else { +// convex_sum -= Math.PI - theta; +// } +// } +// aa = ((polygon.get(1).getX() - polygon.get(polygon.size()-1).getX()) * +// (polygon.get(1).getX() - polygon.get(polygon.size()-1).getX())) + +// ((-polygon.get(1).getY() + polygon.get(polygon.size()-1).getY()) * +// (-polygon.get(1).getY() + polygon.get(polygon.size()-1).getY())); // -// bb = ((polygon.get(0).getX() - polygon.get(polygon.size()-1).getX()) * -// (polygon.get(0).getX() - polygon.get(polygon.size()-1).getX())) + -// ((-polygon.get(0).getY() + polygon.get(polygon.size()-1).getY()) * -// (-polygon.get(0).getY() + polygon.get(polygon.size()-1).getY())); +// bb = ((polygon.get(0).getX() - polygon.get(polygon.size()-1).getX()) * +// (polygon.get(0).getX() - polygon.get(polygon.size()-1).getX())) + +// ((-polygon.get(0).getY() + polygon.get(polygon.size()-1).getY()) * +// (-polygon.get(0).getY() + polygon.get(polygon.size()-1).getY())); // -// cc = ((polygon.get(1).getX() - polygon.get(0).getX()) * -// (polygon.get(1).getX() - polygon.get(0).getX())) + -// ((-polygon.get(1).getY() + polygon.get(0).getY()) * -// (-polygon.get(1).getY() + polygon.get(0).getY())); +// cc = ((polygon.get(1).getX() - polygon.get(0).getX()) * +// (polygon.get(1).getX() - polygon.get(0).getX())) + +// ((-polygon.get(1).getY() + polygon.get(0).getY()) * +// (-polygon.get(1).getY() + polygon.get(0).getY())); // -// b = (float)Math.sqrt(bb); -// c = (float)Math.sqrt(cc); -// theta = (float)Math.acos((bb + cc - aa) / (2 * b * c)); +// b = (float)Math.sqrt(bb); +// c = (float)Math.sqrt(cc); +// theta = (float)Math.acos((bb + cc - aa) / (2 * b * c)); // -// if (convex(polygon.get(polygon.size()-1).getX(), polygon.get(polygon.size()-1).getY(), -// polygon.get(0).getX(), polygon.get(0).getY(), -// polygon.get(1).getX(), polygon.get(1).getY())) { -// convex_turn = (float)Math.PI - theta; -// convex_sum += convex_turn; -// } -// else { -// convex_sum -= Math.PI - theta; -// } +// if (convex(polygon.get(polygon.size()-1).getX(), polygon.get(polygon.size()-1).getY(), +// polygon.get(0).getX(), polygon.get(0).getY(), +// polygon.get(1).getX(), polygon.get(1).getY())) { +// convex_turn = (float)Math.PI - theta; +// convex_sum += convex_turn; +// } +// else { +// convex_sum -= Math.PI - theta; +// } // -// if (convex_sum >= (2 * 3.14159)) -// return true; -// else -// return false; +// if (convex_sum >= (2 * 3.14159)) +// return true; +// else +// return false; } - - /* classifyPoints: Classifies points as "convex" or "concave". - * Convex points are represented as a "1" in the - * ptType array; concave points are represented as a - * "-1" in the array. + /* + * classifyPoints: Classifies points as "convex" or "concave". Convex points are represented as a "1" in the ptType array; + * concave points are represented as a "-1" in the array. */ int concaveCount = 0; - - int[] classifyPoints(List polygon) - { - int[] ptType = new int[polygon.size()]; - concaveCount = 0; + int[] classifyPoints (List polygon) { + int[] ptType = new int[polygon.size()]; + concaveCount = 0; - /* Before cutting any ears, we must determine if the polygon was - * inputted in clockwise order or not, since the algorithm for - * cutting ears assumes that the polygon's points are in clockwise - * order. If the points are in counterclockwise order, they are - * simply reversed in the array. - */ + /* + * Before cutting any ears, we must determine if the polygon was inputted in clockwise order or not, since the algorithm for + * cutting ears assumes that the polygon's points are in clockwise order. If the points are in counterclockwise order, they + * are simply reversed in the array. + */ if (!polygonClockwise(polygon)) { Collections.reverse(polygon); - } + } for (int i = 0; i < polygon.size(); i++) { if (i == 0) { - if (convex(polygon.get(polygon.size()-1).x, polygon.get(polygon.size()-1).y, - polygon.get(i).x, polygon.get(i).y, - polygon.get(i+1).x, polygon.get(i+1).y)) { - ptType[i] = 1; /* point is convex */ - } - else { - ptType[i] = -1; /* point is concave */ + if (convex(polygon.get(polygon.size() - 1).x, polygon.get(polygon.size() - 1).y, polygon.get(i).x, polygon.get(i).y, + polygon.get(i + 1).x, polygon.get(i + 1).y)) { + ptType[i] = 1; /* point is convex */ + } else { + ptType[i] = -1; /* point is concave */ concaveCount++; } - } - else - if( i == polygon.size()-1) - { - if (convex(polygon.get(i-1).x, polygon.get(i-1).y, - polygon.get(i).x, polygon.get(i).y, - polygon.get(0).x, polygon.get(0).y)) { - ptType[i] = 1; /* point is convex */ - } - else { - ptType[i] = -1; /* point is concave */ + } else if (i == polygon.size() - 1) { + if (convex(polygon.get(i - 1).x, polygon.get(i - 1).y, polygon.get(i).x, polygon.get(i).y, polygon.get(0).x, + polygon.get(0).y)) { + ptType[i] = 1; /* point is convex */ + } else { + ptType[i] = -1; /* point is concave */ concaveCount++; } - } - else - { /* i > 0 */ - if (convex(polygon.get(i-1).x, polygon.get(i-1).y, - polygon.get(i).x, polygon.get(i).y, - polygon.get(i+1).x, polygon.get(i+1).y)) { - ptType[i] = 1; /* point is convex */ - } - else { - ptType[i] = -1; /* point is concave */ + } else { /* i > 0 */ + if (convex(polygon.get(i - 1).x, polygon.get(i - 1).y, polygon.get(i).x, polygon.get(i).y, polygon.get(i + 1).x, + polygon.get(i + 1).y)) { + ptType[i] = 1; /* point is convex */ + } else { + ptType[i] = -1; /* point is concave */ concaveCount++; } } } - + return ptType; } - - /* convex: returns true if point (x2, y2) is convex + /* + * convex: returns true if point (x2, y2) is convex */ - boolean convex(float x1, float y1, float x2, float y2, - float x3, float y3) - { + boolean convex (float x1, float y1, float x2, float y2, float x3, float y3) { if (area(x1, y1, x2, y2, x3, y3) < 0) return false; else return true; } - - /* area: determines area of triangle formed by three points + /* + * area: determines area of triangle formed by three points */ - float area(float x1, float y1, float x2, float y2, - float x3, float y3) - { + float area (float x1, float y1, float x2, float y2, float x3, float y3) { float areaSum = 0; areaSum += x1 * (y3 - y2); areaSum += x2 * (y1 - y3); areaSum += x3 * (y2 - y1); - /* for actual area, we need to multiple areaSum * 0.5, but we are - * only interested in the sign of the area (+/-) + /* + * for actual area, we need to multiple areaSum * 0.5, but we are only interested in the sign of the area (+/-) */ return areaSum; } - - /* triangleContainsPoints: returns true if the triangle formed by - * three points contains another point + /* + * triangleContainsPoints: returns true if the triangle formed by three points contains another point */ - boolean triangleContainsPoint(List polygon, int[] ptType, float x1, float y1, float x2, - float y2, float x3, float y3) - { + boolean triangleContainsPoint (List polygon, int[] ptType, float x1, float y1, float x2, float y2, float x3, float y3) { int i = 0; float area1, area2, area3; boolean noPointInTriangle = true; while ((i < polygon.size() - 1) && (noPointInTriangle)) { - if ((ptType[i] == -1) /* point is concave */ && - (((polygon.get(i).x != x1) && (polygon.get(i).y != y1)) || - ((polygon.get(i).x != x2) && (polygon.get(i).y != y2)) || - ((polygon.get(i).x != x3) && (polygon.get(i).y != y3)))) { + if ((ptType[i] == -1) /* point is concave */ + && (((polygon.get(i).x != x1) && (polygon.get(i).y != y1)) || ((polygon.get(i).x != x2) && (polygon.get(i).y != y2)) || ((polygon + .get(i).x != x3) && (polygon.get(i).y != y3)))) { area1 = area(x1, y1, x2, y2, polygon.get(i).x, polygon.get(i).y); area2 = area(x2, y2, x3, y3, polygon.get(i).x, polygon.get(i).y); area3 = area(x3, y3, x1, y1, polygon.get(i).x, polygon.get(i).y); - if (area1 > 0) - if ((area2 > 0) && (area3 > 0)) - noPointInTriangle = false; - if (area1 <= 0) - if ((area2 <= 0) && (area3 <= 0)) - noPointInTriangle = false; + if (area1 > 0) if ((area2 > 0) && (area3 > 0)) noPointInTriangle = false; + if (area1 <= 0) if ((area2 <= 0) && (area3 <= 0)) noPointInTriangle = false; } i++; } return !noPointInTriangle; } - - /* ear: returns true if the point (x2, y2) is an ear, false - * otherwise + /* + * ear: returns true if the point (x2, y2) is an ear, false otherwise */ - boolean ear(List polygon, int[] ptType, float x1, float y1, float x2, float y2, - float x3, float y3) - { + boolean ear (List polygon, int[] ptType, float x1, float y1, float x2, float y2, float x3, float y3) { if (concaveCount != 0) if (triangleContainsPoint(polygon, ptType, x1, y1, x2, y2, x3, y3)) return false; - else + else return true; else return true; } - - /* cutEar: creates triangle that represents ear for graphics purposes + /* + * cutEar: creates triangle that represents ear for graphics purposes */ - void cutEar(List polygon, List triangles, int index) - { + void cutEar (List polygon, List triangles, int index) { if (index == 0) { - triangles.add( new Vector2( polygon.get(polygon.size()-1) )); - triangles.add( new Vector2( polygon.get(index) ) ); - triangles.add( new Vector2( polygon.get(index+1) ) ); - } - else if ((index > 0) && (index < polygon.size()-1)) { - triangles.add( new Vector2( polygon.get(index-1) )); - triangles.add( new Vector2( polygon.get(index) ) ); - triangles.add( new Vector2( polygon.get(index+1) ) ); + triangles.add(new Vector2(polygon.get(polygon.size() - 1))); + triangles.add(new Vector2(polygon.get(index))); + triangles.add(new Vector2(polygon.get(index + 1))); + } else if ((index > 0) && (index < polygon.size() - 1)) { + triangles.add(new Vector2(polygon.get(index - 1))); + triangles.add(new Vector2(polygon.get(index))); + triangles.add(new Vector2(polygon.get(index + 1))); + } else if (index == polygon.size() - 1) { + triangles.add(new Vector2(polygon.get(index - 1))); + triangles.add(new Vector2(polygon.get(index))); + triangles.add(new Vector2(polygon.get(0))); } - else if (index == polygon.size()-1) { - triangles.add( new Vector2( polygon.get(index-1) )); - triangles.add( new Vector2( polygon.get(index) ) ); - triangles.add( new Vector2( polygon.get(0) ) ); - } } - - /* updatePolygon: creates new polygon without the ear that was - * cut + /* + * updatePolygon: creates new polygon without the ear that was cut */ - void updatePolygon(List polygon, int index) - { - polygon.remove(index); + void updatePolygon (List polygon, int index) { + polygon.remove(index); } } diff --git a/gdx/src/com/badlogic/gdx/math/Frustum.java b/gdx/src/com/badlogic/gdx/math/Frustum.java index d7e707574..10962d618 100644 --- a/gdx/src/com/badlogic/gdx/math/Frustum.java +++ b/gdx/src/com/badlogic/gdx/math/Frustum.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math; import java.util.ArrayList; @@ -23,35 +21,31 @@ import com.badlogic.gdx.math.collision.BoundingBox; import com.badlogic.gdx.math.collision.Ray; /** - * Encapsulates a view frustum based on clipping planes. Offers - * methods to perform culling of simple geometric objects like points, - * spheres and {@link BoundingBox}es. + * Encapsulates a view frustum based on clipping planes. Offers methods to perform culling of simple geometric objects like + * points, spheres and {@link BoundingBox}es. * @author badlogicgames@gmail.com - * + * */ -public final class Frustum -{ +public final class Frustum { private static final long serialVersionUID = -7082961504074610513L; protected List planes = new ArrayList(6); - protected float near, far, fov, aspect, near_width, near_height, far_width, far_height, tang; - + protected float near, far, fov, aspect, near_width, near_height, far_width, far_height, tang; + /** * @return The list of {@link Plane}s that make up this frustum. */ - public List getPlanes( ) - { + public List getPlanes () { return planes; } - + /** * Adds a new {@link Plane} to the frustum * @param plane The plane to add */ - public void addPlane( Plane plane ) - { - planes.add( plane ); + public void addPlane (Plane plane) { + planes.add(plane); } - + /** * Sets the camera parameters. * @@ -60,126 +54,114 @@ public final class Frustum * @param near The near plane * @param far The far plane */ - public void setCameraParameters( float fov, float aspect, float near, float far ) - { + public void setCameraParameters (float fov, float aspect, float near, float far) { this.near = near; this.far = far; this.aspect = aspect; this.fov = fov; - - tang = (float)Math.tan( Math.toRadians( fov * 0.5 ) ); - this.near_height = near * tang; + + tang = (float)Math.tan(Math.toRadians(fov * 0.5)); + this.near_height = near * tang; this.near_width = this.near_height * aspect; this.far_height = far * tang; - this.far_width = this.far_height * aspect; + this.far_width = this.far_height * aspect; } - + Vector3 tmp = new Vector3(); Vector3 tmp2 = new Vector3(); - + static Vector3 X = new Vector3(); static Vector3 Y = new Vector3(); static Vector3 Z = new Vector3(); - + static Vector3 near_tl = new Vector3(); static Vector3 near_tr = new Vector3(); static Vector3 near_bl = new Vector3(); static Vector3 near_br = new Vector3(); - + static Vector3 far_tl = new Vector3(); static Vector3 far_tr = new Vector3(); static Vector3 far_bl = new Vector3(); static Vector3 far_br = new Vector3(); - - static Vector3 near_center = new Vector3( ); - static Vector3 far_center = new Vector3( ); - + + static Vector3 near_center = new Vector3(); + static Vector3 far_center = new Vector3(); + /** - * Sets the camera orientation. This will add 6 planes - * for near, far, left, right, top and bottom of the - * frustum. Call {@link Frustum.setCameraParameters} before - * calling this function. + * Sets the camera orientation. This will add 6 planes for near, far, left, right, top and bottom of the frustum. Call + * {@link Frustum.setCameraParameters} before calling this function. * * @param pos The camera position * @param dir The camera direction with unit length * @param up The camera up vector with unit length */ - public void setCameraOrientation( Vector3 pos, Vector3 dir, Vector3 up ) - { - X.set(0,0,0); - Y.set(0,0,0); - Z.set(0,0,0); - - Z.set( dir.tmp().mul(-1) ).nor(); - X.set( up.tmp().crs( Z ) ).nor(); - Y.set( Z.tmp().crs(X) ).nor(); - near_center.set( pos.tmp().sub( tmp.set(Z).mul( near ) ) ); - far_center.set( pos.tmp().sub( tmp.set(Z).mul( far ) ) ); - - near_tl.set( near_center.tmp().add( tmp.set(Y).mul( near_height) ).sub( tmp2.set(X).mul( near_width ) ) ); - near_tr.set( near_center.tmp().add( tmp.set(Y).mul( near_height) ).add( tmp2.set(X).mul( near_width ) ) ); - near_bl.set( near_center.tmp().sub( tmp.set(Y).mul( near_height) ).sub( tmp2.set(X).mul( near_width ) ) ); - near_br.set( near_center.tmp().sub( tmp.set(Y).mul( near_height) ).add( tmp2.set(X).mul( near_width ) ) ); - - far_tl.set( far_center.tmp().add( tmp.set(Y).mul( far_height) ).sub( tmp2.set(X).mul( far_width ) ) ); - far_tr.set( far_center.tmp().add( tmp.set(Y).mul( far_height) ).add( tmp2.set(X).mul( far_width ) ) ); - far_bl.set( far_center.tmp().sub( tmp.set(Y).mul( far_height) ).sub( tmp2.set(X).mul( far_width ) ) ); - far_br.set( far_center.tmp().sub( tmp.set(Y).mul( far_height) ).add( tmp2.set(X).mul( far_width ) ) ); - - if( planes.size() != 6 ) - { + public void setCameraOrientation (Vector3 pos, Vector3 dir, Vector3 up) { + X.set(0, 0, 0); + Y.set(0, 0, 0); + Z.set(0, 0, 0); + + Z.set(dir.tmp().mul(-1)).nor(); + X.set(up.tmp().crs(Z)).nor(); + Y.set(Z.tmp().crs(X)).nor(); + near_center.set(pos.tmp().sub(tmp.set(Z).mul(near))); + far_center.set(pos.tmp().sub(tmp.set(Z).mul(far))); + + near_tl.set(near_center.tmp().add(tmp.set(Y).mul(near_height)).sub(tmp2.set(X).mul(near_width))); + near_tr.set(near_center.tmp().add(tmp.set(Y).mul(near_height)).add(tmp2.set(X).mul(near_width))); + near_bl.set(near_center.tmp().sub(tmp.set(Y).mul(near_height)).sub(tmp2.set(X).mul(near_width))); + near_br.set(near_center.tmp().sub(tmp.set(Y).mul(near_height)).add(tmp2.set(X).mul(near_width))); + + far_tl.set(far_center.tmp().add(tmp.set(Y).mul(far_height)).sub(tmp2.set(X).mul(far_width))); + far_tr.set(far_center.tmp().add(tmp.set(Y).mul(far_height)).add(tmp2.set(X).mul(far_width))); + far_bl.set(far_center.tmp().sub(tmp.set(Y).mul(far_height)).sub(tmp2.set(X).mul(far_width))); + far_br.set(far_center.tmp().sub(tmp.set(Y).mul(far_height)).add(tmp2.set(X).mul(far_width))); + + if (planes.size() != 6) { planes.clear(); - planes.add( new Plane( near_tr, near_tl, far_tl ) ); - planes.add( new Plane( near_bl, near_br, far_br ) ); - planes.add( new Plane( near_tl, near_bl, far_bl ) ); - planes.add( new Plane( near_br, near_tr, far_br ) ); - planes.add( new Plane( near_tl, near_tr, near_br ) ); - planes.add( new Plane( far_tr, far_tl, far_bl ) ); - } - else - { + planes.add(new Plane(near_tr, near_tl, far_tl)); + planes.add(new Plane(near_bl, near_br, far_br)); + planes.add(new Plane(near_tl, near_bl, far_bl)); + planes.add(new Plane(near_br, near_tr, far_br)); + planes.add(new Plane(near_tl, near_tr, near_br)); + planes.add(new Plane(far_tr, far_tl, far_bl)); + } else { planes.get(0).set(near_tr, near_tl, far_tl); planes.get(1).set(near_bl, near_br, far_br); planes.get(2).set(near_tl, near_bl, far_bl); planes.get(3).set(near_br, near_tr, far_br); planes.get(4).set(near_tl, near_tr, near_br); planes.get(5).set(far_tr, far_tl, far_bl); - + } } - - public String toString( ) - { - StringBuilder builder = new StringBuilder( ); - - for( Plane plane: planes ) - { - builder.append( plane.normal ); - builder.append( plane.d ); - builder.append( "\n" ); + + public String toString () { + StringBuilder builder = new StringBuilder(); + + for (Plane plane : planes) { + builder.append(plane.normal); + builder.append(plane.d); + builder.append("\n"); } - + return builder.toString(); } - + /** * Returns wheter the point is in the frustum. * * @param point The point * @return Wheter the point is in the frustum. */ - public boolean pointInFrustum( Vector3 point ) - { - for( int i = 0; i < planes.size(); i++ ) - { - PlaneSide result = planes.get(i).testPoint( point ); - if( result == PlaneSide.Back ) - return false; + public boolean pointInFrustum (Vector3 point) { + for (int i = 0; i < planes.size(); i++) { + PlaneSide result = planes.get(i).testPoint(point); + if (result == PlaneSide.Back) return false; } - + return true; } - + /** * Returns wheter the given sphere is in the frustum. * @@ -187,63 +169,52 @@ public final class Frustum * @param radius The radius of the sphere * @return Wheter the sphere is in the frustum */ - public boolean sphereInFrustum( Vector3 center, float radius ) - { - for( int i = 0; i < planes.size(); i++ ) - if( planes.get(i).distance( center ) < -radius ) - return false; - + public boolean sphereInFrustum (Vector3 center, float radius) { + for (int i = 0; i < planes.size(); i++) + if (planes.get(i).distance(center) < -radius) return false; + return true; } - + /** - * Returns wheter the given sphere is in the frustum not checking - * wheter it is behind the near and far clipping plane. + * Returns wheter the given sphere is in the frustum not checking wheter it is behind the near and far clipping plane. * * @param center The center of the sphere * @param radius The radius of the sphere * @return Wheter the sphere is in the frustum */ - public boolean sphereInFrustumWithoutNearFar( Vector3 center, float radius ) - { - for( int i = 0; i < planes.size(); i++ ) - if( planes.get(i).distance( center ) < -radius ) - return false; - + public boolean sphereInFrustumWithoutNearFar (Vector3 center, float radius) { + for (int i = 0; i < planes.size(); i++) + if (planes.get(i).distance(center) < -radius) return false; + return true; } - + /** * Returns wheter the given {@link BoundingBox} is in the frustum. * * @param bounds The bounding box * @return Wheter the bounding box is in the frustum */ - public boolean boundsInFrustum( BoundingBox bounds ) - { + public boolean boundsInFrustum (BoundingBox bounds) { Vector3[] corners = bounds.getCorners(); int len = corners.length; - - for( int i = 0, len2 = planes.size(); i < len2; i++ ) - { + + for (int i = 0, len2 = planes.size(); i < len2; i++) { int out = 0; - - for( int j = 0; j < len; j++ ) - if( planes.get(i).testPoint(corners[j]) == PlaneSide.Back ) - out++; - - if( out == 8 ) - return false; + + for (int j = 0; j < len; j++) + if (planes.get(i).testPoint(corners[j]) == PlaneSide.Back) out++; + + if (out == 8) return false; } - + return true; } - + /** - * Calculates the pick ray for the given window coordinates. Assumes - * the window coordinate system has it's y downwards. The returned - * Ray is a member of this instance so don't reuse it outside this - * class. + * Calculates the pick ray for the given window coordinates. Assumes the window coordinate system has it's y downwards. The + * returned Ray is a member of this instance so don't reuse it outside this class. * * @param screen_width The window width in pixels * @param screen_height The window height in pixels @@ -253,23 +224,23 @@ public final class Frustum * @param direction The camera direction, having unit length * @param up The camera up vector, having unit length * @return the picking ray. - */ - Ray ray = new Ray( new Vector3(), new Vector3() ); - public Ray calculatePickRay( float screen_width, float screen_height, float mouse_x, float mouse_y, - Vector3 pos, Vector3 dir, Vector3 up ) - { + */ + Ray ray = new Ray(new Vector3(), new Vector3()); + + public Ray calculatePickRay (float screen_width, float screen_height, float mouse_x, float mouse_y, Vector3 pos, Vector3 dir, + Vector3 up) { float n_x = mouse_x - screen_width / 2.0f; float n_y = mouse_y - screen_height / 2.0f; n_x /= screen_width / 2.0f; - n_y /= screen_height / 2.0f; - - Z.set( dir.tmp().mul(-1) ).nor(); - X.set( up.tmp().crs( Z ) ).nor(); - Y.set( Z.tmp().crs(X) ).nor(); - near_center.set( pos.tmp3().sub( Z.tmp2().mul( near ) ) ); - Vector3 near_point = X.tmp3().mul( near_width ).mul( n_x ).add( Y.tmp2().mul( near_height).mul(n_y ) ); - near_point.add( near_center ); - - return ray.set( near_point.tmp(), near_point.sub( pos ).nor() ); + n_y /= screen_height / 2.0f; + + Z.set(dir.tmp().mul(-1)).nor(); + X.set(up.tmp().crs(Z)).nor(); + Y.set(Z.tmp().crs(X)).nor(); + near_center.set(pos.tmp3().sub(Z.tmp2().mul(near))); + Vector3 near_point = X.tmp3().mul(near_width).mul(n_x).add(Y.tmp2().mul(near_height).mul(n_y)); + near_point.add(near_center); + + return ray.set(near_point.tmp(), near_point.sub(pos).nor()); } } diff --git a/gdx/src/com/badlogic/gdx/math/Intersector.java b/gdx/src/com/badlogic/gdx/math/Intersector.java index 68de29c29..c4006ac04 100644 --- a/gdx/src/com/badlogic/gdx/math/Intersector.java +++ b/gdx/src/com/badlogic/gdx/math/Intersector.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math; import java.util.List; @@ -21,54 +19,45 @@ import com.badlogic.gdx.math.collision.BoundingBox; import com.badlogic.gdx.math.collision.Ray; /** - * Class offering various static methods for intersection testing between - * different geometric objects. + * Class offering various static methods for intersection testing between different geometric objects. * @author badlogicgames@gmail.com - * + * */ -public final class Intersector -{ +public final class Intersector { /** - * Returns the lowest positive root of the quadric equation given - * by a* x * x + b * x + c = 0. If no solution is given Float.Nan - * is returned. + * Returns the lowest positive root of the quadric equation given by a* x * x + b * x + c = 0. If no solution is given + * Float.Nan is returned. * * @param a the first coefficient of the quadric equation * @param b the second coefficient of the quadric equation * @param c the third coefficient of the quadric equation * @return the lowest positive root or Float.Nan */ - public static float getLowestPositiveRoot( float a, float b, float c ) - { + public static float getLowestPositiveRoot (float a, float b, float c) { float det = b * b - 4 * a * c; - if( det < 0 ) - return Float.NaN; - - float sqrtD = (float)Math.sqrt( det ); + if (det < 0) return Float.NaN; + + float sqrtD = (float)Math.sqrt(det); float invA = 1 / (2 * a); float r1 = (-b - sqrtD) * invA; float r2 = (-b + sqrtD) * invA; - - if( r1 > r2 ) - { + + if (r1 > r2) { float tmp = r2; r2 = r1; r1 = tmp; } - - if( r1 > 0 ) - return r1; - - if( r2 > 0 ) - return r2; - + + if (r1 > 0) return r1; + + if (r2 > 0) return r2; + return Float.NaN; } - + /** - * Returns whether the given point is inside the triangle. This assumes - * that the point is on the plane of the triangle. No check is performed - * that this is the case. + * Returns whether the given point is inside the triangle. This assumes that the point is on the plane of the triangle. No + * check is performed that this is the case. * * @param point the point * @param t1 the first vertex of the triangle @@ -76,69 +65,62 @@ public final class Intersector * @param t3 the third vertex of the triangle * @return whether the point is in the triangle */ - private final static Vector3 v0 = new Vector3( ); - private final static Vector3 v1 = new Vector3( ); - private final static Vector3 v2 = new Vector3( ); - - public static boolean isPointInTriangle( Vector3 point, Vector3 t1, Vector3 t2, Vector3 t3 ) - { + private final static Vector3 v0 = new Vector3(); + private final static Vector3 v1 = new Vector3(); + private final static Vector3 v2 = new Vector3(); + + public static boolean isPointInTriangle (Vector3 point, Vector3 t1, Vector3 t2, Vector3 t3) { v0.set(t1).sub(point); v1.set(t2).sub(point); v2.set(t3).sub(point); - + float ab = v0.dot(v1); float ac = v0.dot(v2); float bc = v1.dot(v2); float cc = v2.dot(v2); - - if( bc * ac - cc * ab < 0 ) return false; + + if (bc * ac - cc * ab < 0) return false; float bb = v1.dot(v1); - if( ab * bc - ac * bb < 0 ) return false; + if (ab * bc - ac * bb < 0) return false; return true; } - - public static boolean intersectSegmentPlane( Vector3 start, Vector3 end, Plane plane, Vector3 intersection ) - { + + public static boolean intersectSegmentPlane (Vector3 start, Vector3 end, Plane plane, Vector3 intersection) { Vector3 dir = end.tmp().sub(start); - float denom = dir.dot( plane.getNormal() ); - float t = -( start.dot(plane.getNormal()) + plane.getD() ) / denom; - if( t < 0 || t > 1 ) - return false; + float denom = dir.dot(plane.getNormal()); + float t = -(start.dot(plane.getNormal()) + plane.getD()) / denom; + if (t < 0 || t > 1) return false; - intersection.set( start ).add( dir.mul(t) ); - return true; + intersection.set(start).add(dir.mul(t)); + return true; } - + /** - * Checks wheter the given point is in the polygon. Only the - * x and y coordinates of the provided {@link Vector3}s are used. + * Checks wheter the given point is in the polygon. Only the x and y coordinates of the provided {@link Vector3}s are used. * * @param polygon The polygon vertices * @param x The x-coordinate * @param y The y-coordinate * @return Wheter the point is in the polygon */ - public static boolean isPointInPolygon( List polygon, Vector2 point ) - { - + public static boolean isPointInPolygon (List polygon, Vector2 point) { + int j = polygon.size() - 1; boolean oddNodes = false; - for( int i = 0; i < polygon.size(); i++ ) - { - if( (polygon.get(i).y < point.y && polygon.get(j).y >= point.y ) || - (polygon.get(j).y < point.y && polygon.get(i).y >= point.y ) ) - { - if( polygon.get(i).x + (point.y - polygon.get(i).y)/(polygon.get(j).y - polygon.get(i).y)*(polygon.get(j).x-polygon.get(i).x)= point.y) + || (polygon.get(j).y < point.y && polygon.get(i).y >= point.y)) { + if (polygon.get(i).x + (point.y - polygon.get(i).y) / (polygon.get(j).y - polygon.get(i).y) + * (polygon.get(j).x - polygon.get(i).x) < point.x) { + oddNodes = !oddNodes; } + } j = i; } - + return oddNodes; } - + /** * Returns the distance between the given line segment and point. * @param start The line start point @@ -146,18 +128,16 @@ public final class Intersector * @param point The point * * @return The distance between the line segment and the point. - */ - public static float distanceLinePoint( Vector2 start, Vector2 end, Vector2 point ) - { - tmp.set( end.x, end.y, 0 ).sub(start.x, start.y, 0); + */ + public static float distanceLinePoint (Vector2 start, Vector2 end, Vector2 point) { + tmp.set(end.x, end.y, 0).sub(start.x, start.y, 0); float l = tmp.len(); tmp2.set(start.x, start.y, 0).sub(point.x, point.y, 0); return tmp.crs(tmp2).len() / l; } - + /** - * Returns wheter the given line segment intersects the given - * circle. + * Returns wheter the given line segment intersects the given circle. * * @param start The start point of the line segment * @param end The end point of the line segment @@ -165,85 +145,72 @@ public final class Intersector * @param squareRadius The squared radius of the circle * @return Wheter the line segment and the circle intersect */ - public static boolean intersectSegmentCircle( Vector2 start, Vector2 end, Vector2 center, float squareRadius ) - { - float u = (center.x - start.x) * ( end.x - start.x ) + ( center.y - start.y ) * ( end.y - start.y ); - float d = start.dst( end ); - u /= ( d * d ); - if( u < 0 || u > 1 ) - return false; - tmp.set( end.x, end.y, 0 ).sub(start.x, start.y, 0); - tmp2.set(start.x, start.y, 0).add( tmp.mul(u) ); - if( tmp2.dst2( center.x, center.y, 0 ) < squareRadius ) + public static boolean intersectSegmentCircle (Vector2 start, Vector2 end, Vector2 center, float squareRadius) { + float u = (center.x - start.x) * (end.x - start.x) + (center.y - start.y) * (end.y - start.y); + float d = start.dst(end); + u /= (d * d); + if (u < 0 || u > 1) return false; + tmp.set(end.x, end.y, 0).sub(start.x, start.y, 0); + tmp2.set(start.x, start.y, 0).add(tmp.mul(u)); + if (tmp2.dst2(center.x, center.y, 0) < squareRadius) return true; else return false; } - + /** - * Checks wheter the line segment and the circle intersect and returns by - * how much and in what direction the line has to move away from the circle to not intersect. + * Checks wheter the line segment and the circle intersect and returns by how much and in what direction the line has to move + * away from the circle to not intersect. * * @param start The line segment starting point * @param end The line segment end point * @param point The center of the circle * @param radius The radius of the circle * @param displacement The displacement vector set by the method having unit length - * @return The displacement or Float.POSITIVE_INFINITY if no intersection is present + * @return The displacement or Float.POSITIVE_INFINITY if no intersection is present */ - public static float intersectSegmentCircleDisplace( Vector2 start, Vector2 end, Vector2 point, float radius, Vector2 displacement ) - { - float u = (point.x - start.x) * ( end.x - start.x ) + ( point.y - start.y ) * ( end.y - start.y ); - float d = start.dst( end ); - u /= ( d * d ); - if( u < 0 || u > 1 ) - return Float.POSITIVE_INFINITY; - tmp.set( end.x, end.y, 0 ).sub(start.x, start.y, 0); - tmp2.set(start.x, start.y, 0).add( tmp.mul(u) ); - d = tmp2.dst(point.x, point.y, 0 ); - if( d < radius ) - { + public static float intersectSegmentCircleDisplace (Vector2 start, Vector2 end, Vector2 point, float radius, + Vector2 displacement) { + float u = (point.x - start.x) * (end.x - start.x) + (point.y - start.y) * (end.y - start.y); + float d = start.dst(end); + u /= (d * d); + if (u < 0 || u > 1) return Float.POSITIVE_INFINITY; + tmp.set(end.x, end.y, 0).sub(start.x, start.y, 0); + tmp2.set(start.x, start.y, 0).add(tmp.mul(u)); + d = tmp2.dst(point.x, point.y, 0); + if (d < radius) { displacement.set(point).sub(tmp2.x, tmp2.y).nor(); return d; - } - else + } else return Float.POSITIVE_INFINITY; } - + /** - * Intersects a {@link Ray} and a {@link Plane}. The intersection point - * is stored in intersection in case an intersection is present. + * Intersects a {@link Ray} and a {@link Plane}. The intersection point is stored in intersection in case an intersection is + * present. * * @param ray The ray * @param plane The plane * @param intersection The vector the intersection point is written to * @return Wheter an intersection is present. */ - public static boolean intersectRayPlane( Ray ray, Plane plane, Vector3 intersection ) - { - float denom = ray.direction.dot( plane.getNormal() ); - if( denom != 0 ) - { - float t = -( ray.origin.dot(plane.getNormal()) + plane.getD() ) / denom; - if( t < 0 ) - return false; - - intersection.set( ray.origin ).add( ray.direction.tmp().mul(t) ); + public static boolean intersectRayPlane (Ray ray, Plane plane, Vector3 intersection) { + float denom = ray.direction.dot(plane.getNormal()); + if (denom != 0) { + float t = -(ray.origin.dot(plane.getNormal()) + plane.getD()) / denom; + if (t < 0) return false; + + intersection.set(ray.origin).add(ray.direction.tmp().mul(t)); return true; - } - else - if( plane.testPoint( ray.origin ) == Plane.PlaneSide.OnPlane ) - { - intersection.set( ray.origin ); - return true; - } - else - return false; + } else if (plane.testPoint(ray.origin) == Plane.PlaneSide.OnPlane) { + intersection.set(ray.origin); + return true; + } else + return false; } /** - * Intersect a {@link Ray} and a triangle, returning the intersection point - * in intersection. + * Intersect a {@link Ray} and a triangle, returning the intersection point in intersection. * * @param ray The ray * @param t1 The first vertex of the triangle @@ -252,46 +219,40 @@ public final class Intersector * @param intersection The intersection point * @return True in case an intersection is present. */ - private static final Plane p = new Plane( new Vector3(), 0 ); - private static final Vector3 i = new Vector3( ); - public static boolean intersectRayTriangle( Ray ray, Vector3 t1, Vector3 t2, Vector3 t3, Vector3 intersection ) - { - p.set( t1, t2, t3 ); - if( !intersectRayPlane( ray, p, i ) ) - return false; + private static final Plane p = new Plane(new Vector3(), 0); + private static final Vector3 i = new Vector3(); - v0.set( t3 ).sub( t1 ); - v1.set( t2 ).sub( t1 ); - v2.set( i ).sub( t1 ); + public static boolean intersectRayTriangle (Ray ray, Vector3 t1, Vector3 t2, Vector3 t3, Vector3 intersection) { + p.set(t1, t2, t3); + if (!intersectRayPlane(ray, p, i)) return false; - float dot00 = v0.dot( v0 ); - float dot01 = v0.dot( v1 ); - float dot02 = v0.dot( v2 ); - float dot11 = v1.dot( v1 ); - float dot12 = v1.dot( v2 ); + v0.set(t3).sub(t1); + v1.set(t2).sub(t1); + v2.set(i).sub(t1); + + float dot00 = v0.dot(v0); + float dot01 = v0.dot(v1); + float dot02 = v0.dot(v2); + float dot11 = v1.dot(v1); + float dot12 = v1.dot(v2); float denom = dot00 * dot11 - dot01 * dot01; - if( denom == 0 ) - return false; + if (denom == 0) return false; float u = (dot11 * dot02 - dot01 * dot12) / denom; float v = (dot00 * dot12 - dot01 * dot02) / denom; - if( u >= 0 && v >= 0 && u + v <= 1 ) - { - intersection.set( i ); + if (u >= 0 && v >= 0 && u + v <= 1) { + intersection.set(i); return true; - } - else - { + } else { return false; } } /** - * Intersects a {@link Ray} and a sphere, returning the intersection - * point in intersection. + * Intersects a {@link Ray} and a sphere, returning the intersection point in intersection. * * @param ray The ray * @param center The center of the sphere @@ -301,31 +262,29 @@ public final class Intersector */ private static final Vector3 dir = new Vector3(); private static final Vector3 start = new Vector3(); - public static boolean intersectRaySphere( Ray ray, Vector3 center, float radius, Vector3 intersection ) - { - dir.set( ray.direction ).nor(); + + public static boolean intersectRaySphere (Ray ray, Vector3 center, float radius, Vector3 intersection) { + dir.set(ray.direction).nor(); start.set(ray.origin); - float b = 2 * ( dir.dot( start.tmp().sub( center ) ) ); - float c = start.dist2( center ) - radius * radius; + float b = 2 * (dir.dot(start.tmp().sub(center))); + float c = start.dist2(center) - radius * radius; float disc = b * b - 4 * c; - if( disc < 0 ) - return false; + if (disc < 0) return false; // compute q as described above float distSqrt = (float)Math.sqrt(disc); float q; if (b < 0) - q = (-b - distSqrt)/2.0f; + q = (-b - distSqrt) / 2.0f; else - q = (-b + distSqrt)/2.0f; + q = (-b + distSqrt) / 2.0f; // compute t0 and t1 float t0 = q / 1; float t1 = c / q; // make sure t0 is smaller than t1 - if (t0 > t1) - { + if (t0 > t1) { // if t0 is bigger than t1 swap them around float temp = t0; t0 = t1; @@ -334,35 +293,28 @@ public final class Intersector // if t1 is less than zero, the object is in the ray's negative direction // and consequently the ray misses the sphere - if (t1 < 0) - return false; + if (t1 < 0) return false; // if t0 is less than zero, the intersection point is at t1 - if (t0 < 0) - { - if( intersection != null ) - intersection.set( start ).add( dir.tmp().mul( t1 ) ); + if (t0 < 0) { + if (intersection != null) intersection.set(start).add(dir.tmp().mul(t1)); return true; } // else the intersection point is at t0 - else - { - if( intersection != null ) - intersection.set( start ).add( dir.tmp().mul( t0 ) ); + else { + if (intersection != null) intersection.set(start).add(dir.tmp().mul(t0)); return true; } } /** - * Quick check wheter the given {@link Ray} and {@link BoundingBox} - * intersect. + * Quick check wheter the given {@link Ray} and {@link BoundingBox} intersect. * * @param ray The ray * @param bounds The bounding box * @return Wheter the ray and the bounding box intersect. */ - public static boolean intersectRayBoundsFast( Ray ray, BoundingBox bounds ) - { + public static boolean intersectRayBoundsFast (Ray ray, BoundingBox bounds) { float t_x_min, t_x_max; float t_y_min, t_y_max; float t_z_min, t_z_max; @@ -372,53 +324,38 @@ public final class Intersector div_y = 1 / ray.direction.y; div_z = 1 / ray.direction.z; - if (div_x >= 0) - { + if (div_x >= 0) { t_x_min = (bounds.min.x - ray.origin.x) * div_x; t_x_max = (bounds.max.x - ray.origin.x) * div_x; - } - else - { + } else { t_x_min = (bounds.max.x - ray.origin.x) * div_x; t_x_max = (bounds.min.x - ray.origin.x) * div_x; } - if (div_y >= 0) - { + if (div_y >= 0) { t_y_min = (bounds.min.y - ray.origin.y) * div_y; t_y_max = (bounds.max.y - ray.origin.y) * div_y; - } - else - { + } else { t_y_min = (bounds.max.y - ray.origin.y) * div_y; t_y_max = (bounds.min.y - ray.origin.y) * div_y; } - if (t_x_min > t_y_max || (t_y_min > t_x_max)) - return false; + if (t_x_min > t_y_max || (t_y_min > t_x_max)) return false; - if (t_y_min > t_x_min) - t_x_min = t_y_min; - if (t_y_max < t_x_max) - t_x_max = t_y_max; + if (t_y_min > t_x_min) t_x_min = t_y_min; + if (t_y_max < t_x_max) t_x_max = t_y_max; - if (div_z >= 0) - { + if (div_z >= 0) { t_z_min = (bounds.min.z - ray.origin.z) * div_z; t_z_max = (bounds.max.z - ray.origin.z) * div_z; - } - else - { + } else { t_z_min = (bounds.max.z - ray.origin.z) * div_z; t_z_max = (bounds.min.z - ray.origin.z) * div_z; } - if ((t_x_min > t_z_max) || (t_z_min > t_x_max)) - return false; - if (t_z_min > t_x_min) - t_x_min = t_z_min; - if (t_z_max < t_x_max) - t_x_max = t_z_max; + if ((t_x_min > t_z_max) || (t_z_min > t_x_max)) return false; + if (t_z_min > t_x_min) t_x_min = t_z_min; + if (t_z_max < t_x_max) t_x_max = t_z_max; return ((t_x_min < 1) && (t_x_max > 0)); } @@ -430,56 +367,45 @@ public final class Intersector static Vector3 tmp3 = new Vector3(); /** - * Intersects the given ray with list of triangles. Returns the nearest - * intersection point in intersection - * + * Intersects the given ray with list of triangles. Returns the nearest intersection point in intersection + * * @param ray The ray * @param triangles The triangles, each succesive 3 elements from a vertex * @param intersection The nearest intersection point * @return Wheter the ray and the triangles intersect. */ - public static boolean intersectRayTriangles( Ray ray, float[] triangles, Vector3 intersection ) - { + public static boolean intersectRayTriangles (Ray ray, float[] triangles, Vector3 intersection) { float min_dist = Float.MAX_VALUE; boolean hit = false; - if( ( triangles.length / 3 ) % 3 != 0 ) - throw new RuntimeException( "triangle list size is not a multiple of 3" ); - - for( int i = 0; i < triangles.length - 6; i+=9 ) - { - boolean result = intersectRayTriangle( ray, - tmp1.set( triangles[i], triangles[i+1], triangles[i+2] ), - tmp2.set( triangles[i+3], triangles[i+4], triangles[i+5] ), - tmp3.set( triangles[i+6], triangles[i+7], triangles[i+8] ), - tmp); - - if( result == true ) - { - float dist = ray.origin.tmp().sub( tmp ).len(); - if( dist < min_dist ) - { - min_dist = dist; - best.set( tmp ); + if ((triangles.length / 3) % 3 != 0) throw new RuntimeException("triangle list size is not a multiple of 3"); + + for (int i = 0; i < triangles.length - 6; i += 9) { + boolean result = intersectRayTriangle(ray, tmp1.set(triangles[i], triangles[i + 1], triangles[i + 2]), + tmp2.set(triangles[i + 3], triangles[i + 4], triangles[i + 5]), + tmp3.set(triangles[i + 6], triangles[i + 7], triangles[i + 8]), tmp); + + if (result == true) { + float dist = ray.origin.tmp().sub(tmp).len(); + if (dist < min_dist) { + min_dist = dist; + best.set(tmp); hit = true; } } } - if( hit == false ) + if (hit == false) return false; - else - { - if( intersection != null ) - intersection.set( best ); + else { + if (intersection != null) intersection.set(best); return true; } } - + /** - * Intersects the given ray with list of triangles. Returns the nearest - * intersection point in intersection - * + * Intersects the given ray with list of triangles. Returns the nearest intersection point in intersection + * * @param ray The ray * @param vertices the vertices * @param indices the indices, each successive 3 shorts index the 3 vertices of a triangle @@ -487,90 +413,68 @@ public final class Intersector * @param intersection The nearest intersection point * @return Wheter the ray and the triangles intersect. */ - public static boolean intersectRayTriangles( Ray ray, float[] vertices, short[] indices, int vertexSize, Vector3 intersection ) - { + public static boolean intersectRayTriangles (Ray ray, float[] vertices, short[] indices, int vertexSize, Vector3 intersection) { float min_dist = Float.MAX_VALUE; boolean hit = false; - if( ( indices.length % 3) != 0 ) - throw new RuntimeException( "triangle list size is not a multiple of 3" ); + if ((indices.length % 3) != 0) throw new RuntimeException("triangle list size is not a multiple of 3"); - for( int i = 0; i < indices.length; i+=3 ) - { + for (int i = 0; i < indices.length; i += 3) { int i1 = indices[i] * vertexSize; - int i2 = indices[i+1] * vertexSize; - int i3 = indices[i+2] * vertexSize; - - boolean result = intersectRayTriangle( ray, - tmp1.set( vertices[i1], vertices[i1+1], vertices[i1+2] ), - tmp2.set( vertices[i2], vertices[i2+1], vertices[i2+2] ), - tmp3.set( vertices[i3], vertices[i3+1], vertices[i3+2] ), - tmp); - - if( result == true ) - { - float dist = ray.origin.tmp().sub( tmp ).len(); - if( dist < min_dist ) - { - min_dist = dist; - best.set( tmp ); + int i2 = indices[i + 1] * vertexSize; + int i3 = indices[i + 2] * vertexSize; + + boolean result = intersectRayTriangle(ray, tmp1.set(vertices[i1], vertices[i1 + 1], vertices[i1 + 2]), + tmp2.set(vertices[i2], vertices[i2 + 1], vertices[i2 + 2]), + tmp3.set(vertices[i3], vertices[i3 + 1], vertices[i3 + 2]), tmp); + + if (result == true) { + float dist = ray.origin.tmp().sub(tmp).len(); + if (dist < min_dist) { + min_dist = dist; + best.set(tmp); hit = true; } } } - if( hit == false ) + if (hit == false) return false; - else - { - if( intersection != null ) - intersection.set( best ); + else { + if (intersection != null) intersection.set(best); return true; } } - /** - * Intersects the given ray with list of triangles. Returns the nearest - * intersection point in intersection - * + * Intersects the given ray with list of triangles. Returns the nearest intersection point in intersection + * * @param ray The ray * @param triangles The triangles * @param intersection The nearest intersection point * @return Wheter the ray and the triangles intersect. */ - public static boolean intersectRayTriangles( Ray ray, List triangles, Vector3 intersection ) - { + public static boolean intersectRayTriangles (Ray ray, List triangles, Vector3 intersection) { float min_dist = Float.MAX_VALUE; - if( triangles.size() % 3 != 0 ) - throw new RuntimeException( "triangle list size is not a multiple of 3" ); - - for( int i = 0; i < triangles.size() - 2; i+=3 ) - { - boolean result = intersectRayTriangle( ray, - triangles.get(i), - triangles.get(i+1), - triangles.get(i+2), - tmp); - - if( result == true ) - { - float dist = ray.origin.tmp().sub( tmp ).len(); - if( dist < min_dist ) - { + if (triangles.size() % 3 != 0) throw new RuntimeException("triangle list size is not a multiple of 3"); + + for (int i = 0; i < triangles.size() - 2; i += 3) { + boolean result = intersectRayTriangle(ray, triangles.get(i), triangles.get(i + 1), triangles.get(i + 2), tmp); + + if (result == true) { + float dist = ray.origin.tmp().sub(tmp).len(); + if (dist < min_dist) { min_dist = dist; - best.set( tmp ); + best.set(tmp); } } } - if( best == null ) + if (best == null) return false; - else - { - if( intersection != null ) - intersection.set( best ); + else { + if (intersection != null) intersection.set(best); return true; } } @@ -581,15 +485,13 @@ public final class Intersector * @param b The second rectangle * @return Wheter the two rectangles intersect */ - public static boolean intersectRectangles(Rectangle a, Rectangle b) - { - return !(a.getX() > b.getX() + b.getWidth() || a.getX() + a.getWidth() < b.getX() || - a.getY() > b.getY() + b.getHeight() || a.getY() + a.getHeight() < b.getY()); - } + public static boolean intersectRectangles (Rectangle a, Rectangle b) { + return !(a.getX() > b.getX() + b.getWidth() || a.getX() + a.getWidth() < b.getX() || a.getY() > b.getY() + b.getHeight() || a + .getY() + a.getHeight() < b.getY()); + } /** - * Intersects the two lines and returns the intersection point - * in intersection. + * Intersects the two lines and returns the intersection point in intersection. * * @param p1 The first point of the first line * @param p2 The second point of the first line @@ -598,72 +500,53 @@ public final class Intersector * @param intersection The intersection point * @return Wheter the two lines intersect */ - public static boolean intersectLines( Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, Vector2 intersection ) - { - float x1 = p1.x, y1 = p1.y, - x2 = p2.x, y2 = p2.y, - x3 = p3.x, y3 = p3.y, - x4 = p4.x, y4 = p4.y; - - float det1 = det(x1, y1, x2, y2); - float det2 = det(x3, y3, x4, y4); - float det3 = det(x1 - x2, y1 - y2, x3 - x4, y3 - y4); - - float x = det(det1, x1 - x2, - det2, x3 - x4)/ - det3; - float y = det(det1, y1 - y2, - det2, y3 - y4)/ - det3; - + public static boolean intersectLines (Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, Vector2 intersection) { + float x1 = p1.x, y1 = p1.y, x2 = p2.x, y2 = p2.y, x3 = p3.x, y3 = p3.y, x4 = p4.x, y4 = p4.y; + + float det1 = det(x1, y1, x2, y2); + float det2 = det(x3, y3, x4, y4); + float det3 = det(x1 - x2, y1 - y2, x3 - x4, y3 - y4); + + float x = det(det1, x1 - x2, det2, x3 - x4) / det3; + float y = det(det1, y1 - y2, det2, y3 - y4) / det3; + intersection.x = x; intersection.y = y; - + return true; } - /** - * Intersects the two line segments and returns the intersection point - * in intersection. + * Intersects the two line segments and returns the intersection point in intersection. * * @param p1 The first point of the first line segment * @param p2 The second point of the first line segment * @param p3 The first point of the second line segment - * @param p4 The second point of the second line segment + * @param p4 The second point of the second line segment * @param intersection The intersection point * @return Wheter the two line segments intersect */ - public static boolean intersectSegments( Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, Vector2 intersection ) - { - float x1 = p1.x, y1 = p1.y, - x2 = p2.x, y2 = p2.y, - x3 = p3.x, y3 = p3.y, - x4 = p4.x, y4 = p4.y; - - float d = (y4-y3)*(x2-x1) - (x4-x3)*(y2-y1); - if( d == 0 ) - return false; - - float ua = ((x4-x3)*(y1-y3) - (y4-y3)*(x1-x3)) / d; - float ub = ((x2-x1)*(y1-y3) - (y2-y1)*(x1-x3)) / d; - - if( ua < 0 || ua > 1 ) - return false; - if( ub < 0 || ub > 1 ) - return false; - - intersection.set( x1 + (x2-x1)*ua, y1 + (y2-y1)*ua ); + public static boolean intersectSegments (Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, Vector2 intersection) { + float x1 = p1.x, y1 = p1.y, x2 = p2.x, y2 = p2.y, x3 = p3.x, y3 = p3.y, x4 = p4.x, y4 = p4.y; + + float d = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); + if (d == 0) return false; + + float ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / d; + float ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / d; + + if (ua < 0 || ua > 1) return false; + if (ub < 0 || ub > 1) return false; + + intersection.set(x1 + (x2 - x1) * ua, y1 + (y2 - y1) * ua); return true; } - - static float det(float a, float b, float c, float d) - { + + static float det (float a, float b, float c, float d) { return a * d - b * c; } - - static double detd(double a, double b, double c, double d) - { + + static double detd (double a, double b, double c, double d) { return a * d - b * c; } } diff --git a/gdx/src/com/badlogic/gdx/math/Matrix3.java b/gdx/src/com/badlogic/gdx/math/Matrix3.java index ac14ac0a8..31479976e 100644 --- a/gdx/src/com/badlogic/gdx/math/Matrix3.java +++ b/gdx/src/com/badlogic/gdx/math/Matrix3.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.math; import com.badlogic.gdx.GdxRuntimeException; @@ -6,58 +7,53 @@ import com.badlogic.gdx.GdxRuntimeException; * A 3x3 column major matrix for 2D transforms. * * @author mzechner - * + * */ -public class Matrix3 -{ +public class Matrix3 { private final static float DEGREE_TO_RAD = (float)Math.PI / 180; float[] vals = new float[9]; - - public Matrix3( ) - { + + public Matrix3 () { idt(); } - + /** * Sets this matrix to the identity matrix * @return this matrix */ - public Matrix3 idt( ) - { + public Matrix3 idt () { this.vals[0] = 1; this.vals[1] = 0; this.vals[2] = 0; - + this.vals[3] = 0; this.vals[4] = 1; this.vals[5] = 0; - + this.vals[6] = 0; this.vals[7] = 0; this.vals[8] = 1; - + return this; } - + /** - * Multiplies this matrix with the other matrix in the order - * this * m. + * Multiplies this matrix with the other matrix in the order this * m. * @return this matrix */ - public Matrix3 mul( Matrix3 m ) - { + public Matrix3 mul (Matrix3 m) { float v00 = vals[0] * m.vals[0] + vals[3] * m.vals[1] + vals[6] * m.vals[2]; float v01 = vals[0] * m.vals[3] + vals[3] * m.vals[4] + vals[6] * m.vals[5]; float v02 = vals[0] * m.vals[6] + vals[3] * m.vals[7] + vals[6] * m.vals[8]; - + float v10 = vals[1] * m.vals[0] + vals[4] * m.vals[1] + vals[7] * m.vals[2]; float v11 = vals[1] * m.vals[3] + vals[4] * m.vals[4] + vals[7] * m.vals[5]; float v12 = vals[1] * m.vals[6] + vals[4] * m.vals[7] + vals[7] * m.vals[8]; - + float v20 = vals[2] * m.vals[0] + vals[5] * m.vals[1] + vals[8] * m.vals[2]; float v21 = vals[2] * m.vals[3] + vals[5] * m.vals[4] + vals[8] * m.vals[5]; float v22 = vals[2] * m.vals[6] + vals[5] * m.vals[7] + vals[8] * m.vals[8]; - + vals[0] = v00; vals[1] = v10; vals[2] = v20; @@ -67,60 +63,57 @@ public class Matrix3 vals[6] = v02; vals[7] = v12; vals[8] = v22; - + return this; } - + /** - * Sets this matrix to a rotation matrix that will rotate - * any vector in counter clockwise order around the z-axis. + * Sets this matrix to a rotation matrix that will rotate any vector in counter clockwise order around the z-axis. * @param angle the angle in degrees. * @return this matrix */ - public Matrix3 setToRotation( float angle ) - { + public Matrix3 setToRotation (float angle) { angle = DEGREE_TO_RAD * angle; - float cos = (float)Math.cos( angle ); - float sin = (float)Math.sin( angle ); - + float cos = (float)Math.cos(angle); + float sin = (float)Math.sin(angle); + this.vals[0] = cos; this.vals[1] = sin; this.vals[2] = 0; - + this.vals[3] = -sin; this.vals[4] = cos; this.vals[5] = 0; - + this.vals[6] = 0; this.vals[7] = 0; this.vals[8] = 1; - + return this; } - + /** * Sets this matrix to a translation matrix. * @param x the translation in x * @param y the translation in y * @return this matrix */ - public Matrix3 setToTranslation( float x, float y ) - { + public Matrix3 setToTranslation (float x, float y) { this.vals[0] = 1; this.vals[1] = 0; this.vals[2] = 0; - + this.vals[3] = 0; this.vals[4] = 1; this.vals[5] = 0; - + this.vals[6] = x; this.vals[7] = y; this.vals[8] = 1; - - return this; + + return this; } - + /** * Sets this matrix to a scaling matrix * @@ -128,92 +121,79 @@ public class Matrix3 * @param sy the scale in y * @return this matrix */ - public Matrix3 setToScaling( float sx, float sy ) - { + public Matrix3 setToScaling (float sx, float sy) { this.vals[0] = sx; this.vals[1] = 0; this.vals[2] = 0; - + this.vals[3] = 0; this.vals[4] = sy; this.vals[5] = 0; - + this.vals[6] = 0; this.vals[7] = 0; this.vals[8] = 1; - + return this; } - - public String toString( ) - { - return - "["+vals[0]+"|"+vals[3]+"|"+vals[6]+"]\n"+ - "["+vals[1]+"|"+vals[4]+"|"+vals[7]+"]\n"+ - "["+vals[2]+"|"+vals[5]+"|"+vals[8]+"]"; + + public String toString () { + return "[" + vals[0] + "|" + vals[3] + "|" + vals[6] + "]\n" + "[" + vals[1] + "|" + vals[4] + "|" + vals[7] + "]\n" + "[" + + vals[2] + "|" + vals[5] + "|" + vals[8] + "]"; } - + /** * @return the determinant of this matrix */ - public float det( ) - { - return vals[0] * vals[4] * vals[8] + - vals[3] * vals[7] * vals[2] + - vals[6] * vals[1] * vals[5] - - vals[0] * vals[7] * vals[5] - - vals[3] * vals[1] * vals[8] - - vals[6] * vals[4] * vals[2]; + public float det () { + return vals[0] * vals[4] * vals[8] + vals[3] * vals[7] * vals[2] + vals[6] * vals[1] * vals[5] - vals[0] * vals[7] + * vals[5] - vals[3] * vals[1] * vals[8] - vals[6] * vals[4] * vals[2]; } - + /** * Inverts this matrix given that the determinant is != 0 * @return this matrix */ - public Matrix3 inv( ) - { - float det = det( ); - if( det == 0 ) - throw new GdxRuntimeException( "Can't invert a singular matrix" ); - + public Matrix3 inv () { + float det = det(); + if (det == 0) throw new GdxRuntimeException("Can't invert a singular matrix"); + // TODO insert code... http://stackoverflow.com/questions/983999/simple-3x3-matrix-inverse-code-c - throw new GdxRuntimeException( "Not implemented yet" ); + throw new GdxRuntimeException("Not implemented yet"); } - - public static void main( String[] argv ) - { + + public static void main (String[] argv) { float refX = 50, refY = -50; float scaleX = 2, scaleY = 1; float rotation = 45; float x = -232, y = 123; - - Matrix3 transform = new Matrix3( ); - Matrix3 tmp = new Matrix3( ); - - tmp.vals = new float[] { -2, -1, 2, 2, 1, 0, -3, 3, -1 }; - System.out.println( tmp.det() ); - + + Matrix3 transform = new Matrix3(); + Matrix3 tmp = new Matrix3(); + + tmp.vals = new float[] {-2, -1, 2, 2, 1, 0, -3, 3, -1}; + System.out.println(tmp.det()); + transform.idt(); - transform.setToTranslation( -refX, -refY ); - transform.mul( tmp.setToScaling( scaleX, scaleY ) ); - transform.mul( tmp.setToRotation( rotation ) ); - transform.mul( tmp.setToTranslation( refX, refY ) ); - transform.mul( tmp.setToTranslation( x, y ) ); - System.out.println( new Vector2( ).mul( transform ) ); - - Matrix4 transform4 = new Matrix4( ); - Matrix4 tmp4 = new Matrix4( ); + transform.setToTranslation(-refX, -refY); + transform.mul(tmp.setToScaling(scaleX, scaleY)); + transform.mul(tmp.setToRotation(rotation)); + transform.mul(tmp.setToTranslation(refX, refY)); + transform.mul(tmp.setToTranslation(x, y)); + System.out.println(new Vector2().mul(transform)); + + Matrix4 transform4 = new Matrix4(); + Matrix4 tmp4 = new Matrix4(); transform4.idt(); - transform4.setToTranslation( -refX, -refY, 0 ); - transform4.mul( tmp4.setToScaling( scaleX, scaleY, 1 ) ); - transform4.mul( tmp4.setToRotation( new Vector3( 0, 0, 1 ), rotation ) ); - transform4.mul( tmp4.setToTranslation( refX, refY, 0 ) ); - transform4.mul( tmp4.setToTranslation( x, y, 0 ) ); - System.out.println( new Vector3( ).mul( transform4 ) ); + transform4.setToTranslation(-refX, -refY, 0); + transform4.mul(tmp4.setToScaling(scaleX, scaleY, 1)); + transform4.mul(tmp4.setToRotation(new Vector3(0, 0, 1), rotation)); + transform4.mul(tmp4.setToTranslation(refX, refY, 0)); + transform4.mul(tmp4.setToTranslation(x, y, 0)); + System.out.println(new Vector3().mul(transform4)); } - public Matrix3 set(Matrix3 mat) - { + public Matrix3 set (Matrix3 mat) { vals[0] = mat.vals[0]; vals[1] = mat.vals[1]; vals[2] = mat.vals[2]; @@ -226,8 +206,7 @@ public class Matrix3 return this; } - public float[] getValues() - { + public float[] getValues () { return vals; } } diff --git a/gdx/src/com/badlogic/gdx/math/Matrix4.java b/gdx/src/com/badlogic/gdx/math/Matrix4.java index 5a997b7db..b77e0e11a 100644 --- a/gdx/src/com/badlogic/gdx/math/Matrix4.java +++ b/gdx/src/com/badlogic/gdx/math/Matrix4.java @@ -1,634 +1,686 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ -package com.badlogic.gdx.math; +package com.badlogic.gdx.math; /** - * Encapsulates a column major 4 by 4 matrix. You can access - * the linear array for use with OpenGL via the public {@link Matrix4.val} - * member. Like the {@link Vector3} class it allows to chain methods by - * returning a reference to itself. + * Encapsulates a column major 4 by 4 matrix. You can access the linear array for use with OpenGL via the public + * {@link Matrix4.val} member. Like the {@link Vector3} class it allows to chain methods by returning a reference to itself. * * @author badlogicgames@gmail.com - * + * */ -public final class Matrix4 -{ +public final class Matrix4 { private static final long serialVersionUID = -2717655254359579617L; - public static final int M00=0;//0; - public static final int M01=4;//1; - public static final int M02=8;//2; - public static final int M03=12;//3; - public static final int M10=1;//4; - public static final int M11=5;//5; - public static final int M12=9;//6; - public static final int M13=13;//7; - public static final int M20=2;//8; - public static final int M21=6;//9; - public static final int M22=10;//10; - public static final int M23=14;//11; - public static final int M30=3;//12; - public static final int M31=7;//13; - public static final int M32=11;//14; - public static final int M33=15;//15; - - public final float tmp[] = new float[16]; - public final float val[] = new float[16]; - - /** - * Constructs an identity matrix - */ - public Matrix4() - { - val[M00]=1f; val[M11]=1f; val[M22]=1f; val[M33]=1f; - } - - /** - * Constructs a matrix from the given matrix - * - * @param matrix The matrix - */ - public Matrix4(Matrix4 matrix) - { - this.set(matrix); - } - - /** - * Constructs a matrix from the given float array. The - * array must have at least 16 elements - * @param values The float array - */ - public Matrix4(float[] values) - { - this.set(values); - } - - /** - * Constructs a rotation matrix from the given {@link Quaternion} - * @param quaternion The quaternion - */ - public Matrix4(Quaternion quaternion) - { - this.set(quaternion); - } - - /** - * Sets the matrix to the given matrix. - * - * @param matrix The matrix - * @return This matrix for chaining - */ - public Matrix4 set(Matrix4 matrix) - { - return this.set(matrix.val); - } - - /** - * Sets the matrix to the given matrix as a float array. - * The float array must have at least 16 elements. - * - * @param values The matrix - * @return This matrix for chaining - */ - public Matrix4 set(float[] values) - { - val[M00]=values[M00]; val[M10]=values[M10]; val[M20]=values[M20]; val[M30]=values[M30]; - val[M01]=values[M01]; val[M11]=values[M11]; val[M21]=values[M21]; val[M31]=values[M31]; - val[M02]=values[M02]; val[M12]=values[M12]; val[M22]=values[M22]; val[M32]=values[M32]; - val[M03]=values[M03]; val[M13]=values[M13]; val[M23]=values[M23]; val[M33]=values[M33]; - return this; - } - - /** - * Sets the matrix to a rotation matrix representing the - * quaternion. - * - * @param quaternion The quaternion - * @return This matrix for chaining - */ - public Matrix4 set(Quaternion quaternion) - { - // Compute quaternion factors - float l_xx = quaternion.x*quaternion.x; - float l_xy = quaternion.x*quaternion.y; - float l_xz = quaternion.x*quaternion.z; - float l_xw = quaternion.x*quaternion.w; - float l_yy = quaternion.y*quaternion.y; - float l_yz = quaternion.y*quaternion.z; - float l_yw = quaternion.y*quaternion.w; - float l_zz = quaternion.z*quaternion.z; - float l_zw = quaternion.z*quaternion.w; - // Set matrix from quaternion - val[M00]=1-2*(l_yy +l_zz); - val[M01]=2*(l_xy -l_zw); - val[M02]=2*(l_xz +l_yw); - val[M10]=2*(l_xy +l_zw); - val[M11]=1-2*(l_xx +l_zz); - val[M12]=2*(l_yz -l_xw); - val[M20]=2*(l_xz -l_yw); - val[M21]=2*(l_yz +l_xw); - val[M22]=1-2*(l_xx +l_yy); - val[M33]=1; - return this; - } - - /** - * Sets the four columns of the matrix which correspond to the - * x-, y- and z-axis of the vector space this matrix creates as - * well as the 4th column representing the translation of any - * point that is multiplied by this matrix. - * - * @param xAxis The x-axis - * @param yAxis The y-axis - * @param zAxis The z-axis - * @param pos The translation vector - */ - public void set( Vector3 xAxis, Vector3 yAxis, Vector3 zAxis, Vector3 pos ) - { - val[M00] = xAxis.x; - val[M01] = xAxis.y; - val[M02] = xAxis.z; - val[M10] = yAxis.x; - val[M11] = yAxis.y; - val[M12] = yAxis.z; - val[M20] = -zAxis.x; - val[M21] = -zAxis.y; - val[M22] = -zAxis.z; - val[M03] = pos.x; - val[M13] = pos.y; - val[M23] = pos.z; - val[M30] = 0; - val[M31] = 0; - val[M32] = 0; - val[M33] = 1; - } - - /** - * @return a copy of this matrix - */ - public Matrix4 cpy() - { - return new Matrix4(this); - } - - /** - * @return the backing float array - */ - public float[] getValues() - { - return val; - } - - /** - * Multiplies this matrix with the given matrix, storing - * the result in this matrix. - * - * @param matrix The other matrix - * @return This matrix for chaining. - */ - public Matrix4 mul(Matrix4 matrix) - { - tmp[M00]=val[M00]*matrix.val[M00] + val[M01]*matrix.val[M10] + val[M02]*matrix.val[M20] + val[M03]*matrix.val[M30]; - tmp[M01]=val[M00]*matrix.val[M01] + val[M01]*matrix.val[M11] + val[M02]*matrix.val[M21] + val[M03]*matrix.val[M31]; - tmp[M02]=val[M00]*matrix.val[M02] + val[M01]*matrix.val[M12] + val[M02]*matrix.val[M22] + val[M03]*matrix.val[M32]; - tmp[M03]=val[M00]*matrix.val[M03] + val[M01]*matrix.val[M13] + val[M02]*matrix.val[M23] + val[M03]*matrix.val[M33]; - tmp[M10]=val[M10]*matrix.val[M00] + val[M11]*matrix.val[M10] + val[M12]*matrix.val[M20] + val[M13]*matrix.val[M30]; - tmp[M11]=val[M10]*matrix.val[M01] + val[M11]*matrix.val[M11] + val[M12]*matrix.val[M21] + val[M13]*matrix.val[M31]; - tmp[M12]=val[M10]*matrix.val[M02] + val[M11]*matrix.val[M12] + val[M12]*matrix.val[M22] + val[M13]*matrix.val[M32]; - tmp[M13]=val[M10]*matrix.val[M03] + val[M11]*matrix.val[M13] + val[M12]*matrix.val[M23] + val[M13]*matrix.val[M33]; - tmp[M20]=val[M20]*matrix.val[M00] + val[M21]*matrix.val[M10] + val[M22]*matrix.val[M20] + val[M23]*matrix.val[M30]; - tmp[M21]=val[M20]*matrix.val[M01] + val[M21]*matrix.val[M11] + val[M22]*matrix.val[M21] + val[M23]*matrix.val[M31]; - tmp[M22]=val[M20]*matrix.val[M02] + val[M21]*matrix.val[M12] + val[M22]*matrix.val[M22] + val[M23]*matrix.val[M32]; - tmp[M23]=val[M20]*matrix.val[M03] + val[M21]*matrix.val[M13] + val[M22]*matrix.val[M23] + val[M23]*matrix.val[M33]; - tmp[M30]=val[M30]*matrix.val[M00] + val[M31]*matrix.val[M10] + val[M32]*matrix.val[M20] + val[M33]*matrix.val[M30]; - tmp[M31]=val[M30]*matrix.val[M01] + val[M31]*matrix.val[M11] + val[M32]*matrix.val[M21] + val[M33]*matrix.val[M31]; - tmp[M32]=val[M30]*matrix.val[M02] + val[M31]*matrix.val[M12] + val[M32]*matrix.val[M22] + val[M33]*matrix.val[M32]; - tmp[M33]=val[M30]*matrix.val[M03] + val[M31]*matrix.val[M13] + val[M32]*matrix.val[M23] + val[M33]*matrix.val[M33]; - return this.set(tmp); - } - - /** - * Transposes the matrix - * - * @return This matrix for chaining - */ - public Matrix4 tra() - { - tmp[M00]=val[M00]; tmp[M01]=val[M10]; tmp[M02]=val[M20]; tmp[M03]=val[M30]; - tmp[M10]=val[M01]; tmp[M11]=val[M11]; tmp[M12]=val[M21]; tmp[M13]=val[M31]; - tmp[M20]=val[M02]; tmp[M21]=val[M12]; tmp[M22]=val[M22]; tmp[M23]=val[M32]; - tmp[M30]=val[M03]; tmp[M31]=val[M13]; tmp[M32]=val[M23]; tmp[M33]=val[M33]; - return this.set(tmp); - } - - /** - * Sets the matrix to an identity matrix - * - * @return This matrix for chaining - */ - public Matrix4 idt() - { - val[M00]=1; val[M01]=0; val[M02]=0; val[M03]=0; - val[M10]=0; val[M11]=1; val[M12]=0; val[M13]=0; - val[M20]=0; val[M21]=0; val[M22]=1; val[M23]=0; - val[M30]=0; val[M31]=0; val[M32]=0; val[M33]=1; - return this; - } - - /** - * Inverts the matrix. Throws a RuntimeException in case the - * matrix is not invertible. Stores the result in this matrix - * - * @return This matrix for chaining - */ - public Matrix4 inv() - { - float l_det=this.det(); - if(l_det==0f) throw new RuntimeException("non-invertible matrix"); - tmp[M00]=val[M12]*val[M23]*val[M31] - val[M13]*val[M22]*val[M31] + val[M13]*val[M21]*val[M32] - val[M11]*val[M23]*val[M32] - val[M12]*val[M21]*val[M33] + val[M11]*val[M22]*val[M33]; - tmp[M01]=val[M03]*val[M22]*val[M31] - val[M02]*val[M23]*val[M31] - val[M03]*val[M21]*val[M32] + val[M01]*val[M23]*val[M32] + val[M02]*val[M21]*val[M33] - val[M01]*val[M22]*val[M33]; - tmp[M02]=val[M02]*val[M13]*val[M31] - val[M03]*val[M12]*val[M31] + val[M03]*val[M11]*val[M32] - val[M01]*val[M13]*val[M32] - val[M02]*val[M11]*val[M33] + val[M01]*val[M12]*val[M33]; - tmp[M03]=val[M03]*val[M12]*val[M21] - val[M02]*val[M13]*val[M21] - val[M03]*val[M11]*val[M22] + val[M01]*val[M13]*val[M22] + val[M02]*val[M11]*val[M23] - val[M01]*val[M12]*val[M23]; - tmp[M10]=val[M13]*val[M22]*val[M30] - val[M12]*val[M23]*val[M30] - val[M13]*val[M20]*val[M32] + val[M10]*val[M23]*val[M32] + val[M12]*val[M20]*val[M33] - val[M10]*val[M22]*val[M33]; - tmp[M11]=val[M02]*val[M23]*val[M30] - val[M03]*val[M22]*val[M30] + val[M03]*val[M20]*val[M32] - val[M00]*val[M23]*val[M32] - val[M02]*val[M20]*val[M33] + val[M00]*val[M22]*val[M33]; - tmp[M12]=val[M03]*val[M12]*val[M30] - val[M02]*val[M13]*val[M30] - val[M03]*val[M10]*val[M32] + val[M00]*val[M13]*val[M32] + val[M02]*val[M10]*val[M33] - val[M00]*val[M12]*val[M33]; - tmp[M13]=val[M02]*val[M13]*val[M20] - val[M03]*val[M12]*val[M20] + val[M03]*val[M10]*val[M22] - val[M00]*val[M13]*val[M22] - val[M02]*val[M10]*val[M23] + val[M00]*val[M12]*val[M23]; - tmp[M20]=val[M11]*val[M23]*val[M30] - val[M13]*val[M21]*val[M30] + val[M13]*val[M20]*val[M31] - val[M10]*val[M23]*val[M31] - val[M11]*val[M20]*val[M33] + val[M10]*val[M21]*val[M33]; - tmp[M21]=val[M03]*val[M21]*val[M30] - val[M01]*val[M23]*val[M30] - val[M03]*val[M20]*val[M31] + val[M00]*val[M23]*val[M31] + val[M01]*val[M20]*val[M33] - val[M00]*val[M21]*val[M33]; - tmp[M22]=val[M01]*val[M13]*val[M30] - val[M03]*val[M11]*val[M30] + val[M03]*val[M10]*val[M31] - val[M00]*val[M13]*val[M31] - val[M01]*val[M10]*val[M33] + val[M00]*val[M11]*val[M33]; - tmp[M23]=val[M03]*val[M11]*val[M20] - val[M01]*val[M13]*val[M20] - val[M03]*val[M10]*val[M21] + val[M00]*val[M13]*val[M21] + val[M01]*val[M10]*val[M23] - val[M00]*val[M11]*val[M23]; - tmp[M30]=val[M12]*val[M21]*val[M30] - val[M11]*val[M22]*val[M30] - val[M12]*val[M20]*val[M31] + val[M10]*val[M22]*val[M31] + val[M11]*val[M20]*val[M32] - val[M10]*val[M21]*val[M32]; - tmp[M31]=val[M01]*val[M22]*val[M30] - val[M02]*val[M21]*val[M30] + val[M02]*val[M20]*val[M31] - val[M00]*val[M22]*val[M31] - val[M01]*val[M20]*val[M32] + val[M00]*val[M21]*val[M32]; - tmp[M32]=val[M02]*val[M11]*val[M30] - val[M01]*val[M12]*val[M30] - val[M02]*val[M10]*val[M31] + val[M00]*val[M12]*val[M31] + val[M01]*val[M10]*val[M32] - val[M00]*val[M11]*val[M32]; - tmp[M33]=val[M01]*val[M12]*val[M20] - val[M02]*val[M11]*val[M20] + val[M02]*val[M10]*val[M21] - val[M00]*val[M12]*val[M21] - val[M01]*val[M10]*val[M22] + val[M00]*val[M11]*val[M22]; - this.set(tmp); - val[M00]/=l_det; val[M01]/=l_det; val[M02]/=l_det; val[M03]/=l_det; - val[M10]/=l_det; val[M11]/=l_det; val[M12]/=l_det; val[M13]/=l_det; - val[M20]/=l_det; val[M21]/=l_det; val[M22]/=l_det; val[M23]/=l_det; - val[M30]/=l_det; val[M31]/=l_det; val[M32]/=l_det; val[M33]/=l_det; - return this; - } - - /** - * @return The determinant of this matrix - */ - public float det() - { - return - val[M30] * val[M21] * val[M12] * val[M03]-val[M20] * val[M31] * val[M12] * val[M03]-val[M30] * val[M11] * val[M22] * val[M03]+val[M10] * val[M31] * val[M22] * val[M03]+ - val[M20] * val[M11] * val[M32] * val[M03]-val[M10] * val[M21] * val[M32] * val[M03]-val[M30] * val[M21] * val[M02] * val[M13]+val[M20] * val[M31] * val[M02] * val[M13]+ - val[M30] * val[M01] * val[M22] * val[M13]-val[M00] * val[M31] * val[M22] * val[M13]-val[M20] * val[M01] * val[M32] * val[M13]+val[M00] * val[M21] * val[M32] * val[M13]+ - val[M30] * val[M11] * val[M02] * val[M23]-val[M10] * val[M31] * val[M02] * val[M23]-val[M30] * val[M01] * val[M12] * val[M23]+val[M00] * val[M31] * val[M12] * val[M23]+ - val[M10] * val[M01] * val[M32] * val[M23]-val[M00] * val[M11] * val[M32] * val[M23]-val[M20] * val[M11] * val[M02] * val[M33]+val[M10] * val[M21] * val[M02] * val[M33]+ - val[M20] * val[M01] * val[M12] * val[M33]-val[M00] * val[M21] * val[M12] * val[M33]-val[M10] * val[M01] * val[M22] * val[M33]+val[M00] * val[M11] * val[M22] * val[M33]; - } - - /** - * Sets the matrix to a projection matrix with a near- and - * far plane, a field of view in degrees and an aspect ratio. - * - * @param near The near plane - * @param far The far plane - * @param fov The field of view in degrees - * @param aspectRatio The aspect ratio - * @return This matrix for chaining - */ - public Matrix4 setToProjection(float near, float far, float fov, float aspectRatio) - { - this.idt(); - float l_fd=(float)(1.0/Math.tan((fov*(Math.PI/180))/2.0)); - float l_a1=-(far+near)/(far-near); - float l_a2=-(2*far*near)/(far-near); - val[M00]=l_fd/aspectRatio; val[M10]=0; val[M20]=0; val[M30]=0; - val[M01]=0; val[M11]=l_fd; val[M21]=0; val[M31]=0; - val[M02]=0; val[M12]=0; val[M22]=l_a1; val[M32]=-1; - val[M03]=0; val[M13]=0; val[M23]=l_a2; val[M33]=0; - return this; - } - - /** - * Sets this matrix to an orthographic projection matrix with the - * origin at (x,y) extending by width and height. The near plane - * is set to 0, the far plane is set to 1. - * - * @param x The x-coordinate of the origin - * @param y The y-coordinate of the origin - * @param width The width - * @param height The height - * @return This matrix for chaining - */ - public Matrix4 setToOrtho2D( float x, float y, float width, float height ) - { - setToOrtho( 0, width, 0, height, 0, 1 ); - return this; - } - - /** - * Sets this matrix to an orthographic projection matrix with the - * origin at (x,y) extending by width and height, having a near - * and far plane. - * - * @param x The x-coordinate of the origin - * @param y The y-coordinate of the origin - * @param width The width - * @param height The height - * @param near The near plane - * @param far The far plane - * @return This matrix for chaining - */ - public Matrix4 setToOrtho2D( float x, float y, float width, float height, float near, float far ) - { - setToOrtho( 0, width, 0, height, near, far ); - return this; - } - - /** - * Sets the matrix to an orthographic projection like glOrtho (http://www.opengl.org/sdk/docs/man/xhtml/glOrtho.xml) - * following the OpenGL equivalent - * - * @param left The left clipping plane - * @param right The right clipping plane - * @param bottom The bottom clipping plane - * @param top The top clipping plane - * @param near The near clipping plane - * @param far The far clipping plane - * @return This matrix for chaining - */ - public Matrix4 setToOrtho( float left, float right, float bottom, float top, float near, float far ) - { - - this.idt(); - float x_orth = 2 / ( right - left ); - float y_orth = 2 / ( top - bottom ); - float z_orth = -2 / ( far - near ); - - float tx = -( right + left ) / ( right - left ); - float ty = -( top + bottom ) / ( top - bottom ); - float tz = ( far + near ) / ( far - near ); - - val[M00]=x_orth; val[M10]=0; val[M20]=0; val[M30]=0; - val[M01]=0; val[M11]=y_orth; val[M21]=0; val[M31]=0; - val[M02]=0; val[M12]=0; val[M22]=z_orth;val[M32]=0; - val[M03]=tx; val[M13]=ty; val[M23]=tz; val[M33]=1; - - return this; - } - - /** - * Sets this matrix to a translation matrix, overwriting it first - * by an identity matrix and then setting the 4th column to the - * translation vector. - * - * @param vector The translation vector - * @return This matrix for chaining - */ - public Matrix4 setToTranslation(Vector3 vector) - { - this.idt(); - val[M03]=vector.x; - val[M13]=vector.y; - val[M23]=vector.z; - return this; - } - - /** - * Sets this matrix to a translation matrix, overwriting it first - * by an identity matrix and then setting the 4th column to the - * translation vector. - * - * @param x The x-component of the translation vector - * @param y The y-component of the translation vector - * @param z The z-component of the translation vector - * @return This matrix for chaining - */ - public Matrix4 setToTranslation(float x, float y, float z) - { - idt(); - val[M03]=x; - val[M13]=y; - val[M23]=z; - return this; - } - - /** - * Sets this matrix to a translation and scaling matrix by first - * overwritting it with an identity and then setting the translation - * vector in the 4th column and the scaling vector in the diagonal. - * - * @param translation The translation vector - * @param scaling The scaling vector - * @return This matrix for chaining - */ - public Matrix4 setToTranslationAndScaling(Vector3 translation,Vector3 scaling) - { - idt(); - val[M03]=translation.x; - val[M13]=translation.y; - val[M23]=translation.z; - val[M00]=scaling.x; - val[M11]=scaling.y; - val[M22]=scaling.z; - return this; - } - - /** - * Sets this matrix to a translation and scaling matrix by first - * overwritting it with an identity and then setting the translation - * vector in the 4th column and the scaling vector in the diagonal. - * - * @param translationX The x-component of the translation vector - * @param translationY The y-component of the translation vector - * @param translationZ The z-component of the translation vector - * @param scalingX The x-component of the scaling vector - * @param scalingY The x-component of the scaling vector - * @param scalingZ The x-component of the scaling vector - * @return This matrix for chaining - */ - public Matrix4 setToTranslationAndScaling(float translationX, float translationY, float translationZ, float scalingX, float scalingY, float scalingZ) - { - this.idt(); - val[M03]=translationX; - val[M13]=translationY; - val[M23]=translationZ; - val[M00]=scalingX; - val[M11]=scalingY; - val[M22]=scalingZ; - return this; - } - - static Quaternion quat = new Quaternion(); - - /** - * Sets the matrix to a rotation matrix around the given - * axis. - * - * @param axis The axis - * @param angle The angle in degrees - * @return This matrix for chaining - */ - public Matrix4 setToRotation(Vector3 axis, float angle) - { - idt(); - if(angle==0) return this; - return this.set(quat.set(axis,angle)); - } - - /** - * Sets this matrix to a rotation matrix from the given euler - * angles. - * @param yaw the yaw in degrees - * @param pitch the pitch in degress - * @param roll the roll in degrees - * @return this matrix - */ - public Matrix4 setFromEulerAngles( float yaw, float pitch, float roll ) - { - idt(); - quat.setEulerAngles(yaw, pitch, roll); - return this.set(quat); - } - - /** - * Sets this matrix to a scaling matrix - * - * @param vector The scaling vector - * @return This matrix for chaining. - */ - public Matrix4 setToScaling(Vector3 vector) - { - idt(); - val[M00]=vector.x; - val[M11]=vector.y; - val[M22]=vector.z; - return this; - } - - /** - * Sets this matrix to a scaling matrix - * - * @param x The x-component of the scaling vector - * @param y The y-component of the scaling vector - * @param z The z-component of the scaling vector - * @return This matrix for chaining. - */ - public Matrix4 setToScaling(float x, float y, float z) - { - idt(); - val[M00]=x; - val[M11]=y; - val[M22]=z; - return this; - } - - static Vector3 l_vez = new Vector3( ); - static Vector3 l_vex = new Vector3( ); - static Vector3 l_vey = new Vector3( ); - - /** - * Sets the matrix to a look at matrix with a direction - * and an up vector. Multiply with a translation matrix - * to get a camera model view matrix. - * - * @param direction The direction vector - * @param up The up vector - * @return This matrix for chaining - */ - public Matrix4 setToLookAt(Vector3 direction, Vector3 up) - { + public static final int M00 = 0;// 0; + public static final int M01 = 4;// 1; + public static final int M02 = 8;// 2; + public static final int M03 = 12;// 3; + public static final int M10 = 1;// 4; + public static final int M11 = 5;// 5; + public static final int M12 = 9;// 6; + public static final int M13 = 13;// 7; + public static final int M20 = 2;// 8; + public static final int M21 = 6;// 9; + public static final int M22 = 10;// 10; + public static final int M23 = 14;// 11; + public static final int M30 = 3;// 12; + public static final int M31 = 7;// 13; + public static final int M32 = 11;// 14; + public static final int M33 = 15;// 15; + + public final float tmp[] = new float[16]; + public final float val[] = new float[16]; + + /** + * Constructs an identity matrix + */ + public Matrix4 () { + val[M00] = 1f; + val[M11] = 1f; + val[M22] = 1f; + val[M33] = 1f; + } + + /** + * Constructs a matrix from the given matrix + * + * @param matrix The matrix + */ + public Matrix4 (Matrix4 matrix) { + this.set(matrix); + } + + /** + * Constructs a matrix from the given float array. The array must have at least 16 elements + * @param values The float array + */ + public Matrix4 (float[] values) { + this.set(values); + } + + /** + * Constructs a rotation matrix from the given {@link Quaternion} + * @param quaternion The quaternion + */ + public Matrix4 (Quaternion quaternion) { + this.set(quaternion); + } + + /** + * Sets the matrix to the given matrix. + * + * @param matrix The matrix + * @return This matrix for chaining + */ + public Matrix4 set (Matrix4 matrix) { + return this.set(matrix.val); + } + + /** + * Sets the matrix to the given matrix as a float array. The float array must have at least 16 elements. + * + * @param values The matrix + * @return This matrix for chaining + */ + public Matrix4 set (float[] values) { + val[M00] = values[M00]; + val[M10] = values[M10]; + val[M20] = values[M20]; + val[M30] = values[M30]; + val[M01] = values[M01]; + val[M11] = values[M11]; + val[M21] = values[M21]; + val[M31] = values[M31]; + val[M02] = values[M02]; + val[M12] = values[M12]; + val[M22] = values[M22]; + val[M32] = values[M32]; + val[M03] = values[M03]; + val[M13] = values[M13]; + val[M23] = values[M23]; + val[M33] = values[M33]; + return this; + } + + /** + * Sets the matrix to a rotation matrix representing the quaternion. + * + * @param quaternion The quaternion + * @return This matrix for chaining + */ + public Matrix4 set (Quaternion quaternion) { + // Compute quaternion factors + float l_xx = quaternion.x * quaternion.x; + float l_xy = quaternion.x * quaternion.y; + float l_xz = quaternion.x * quaternion.z; + float l_xw = quaternion.x * quaternion.w; + float l_yy = quaternion.y * quaternion.y; + float l_yz = quaternion.y * quaternion.z; + float l_yw = quaternion.y * quaternion.w; + float l_zz = quaternion.z * quaternion.z; + float l_zw = quaternion.z * quaternion.w; + // Set matrix from quaternion + val[M00] = 1 - 2 * (l_yy + l_zz); + val[M01] = 2 * (l_xy - l_zw); + val[M02] = 2 * (l_xz + l_yw); + val[M10] = 2 * (l_xy + l_zw); + val[M11] = 1 - 2 * (l_xx + l_zz); + val[M12] = 2 * (l_yz - l_xw); + val[M20] = 2 * (l_xz - l_yw); + val[M21] = 2 * (l_yz + l_xw); + val[M22] = 1 - 2 * (l_xx + l_yy); + val[M33] = 1; + return this; + } + + /** + * Sets the four columns of the matrix which correspond to the x-, y- and z-axis of the vector space this matrix creates as + * well as the 4th column representing the translation of any point that is multiplied by this matrix. + * + * @param xAxis The x-axis + * @param yAxis The y-axis + * @param zAxis The z-axis + * @param pos The translation vector + */ + public void set (Vector3 xAxis, Vector3 yAxis, Vector3 zAxis, Vector3 pos) { + val[M00] = xAxis.x; + val[M01] = xAxis.y; + val[M02] = xAxis.z; + val[M10] = yAxis.x; + val[M11] = yAxis.y; + val[M12] = yAxis.z; + val[M20] = -zAxis.x; + val[M21] = -zAxis.y; + val[M22] = -zAxis.z; + val[M03] = pos.x; + val[M13] = pos.y; + val[M23] = pos.z; + val[M30] = 0; + val[M31] = 0; + val[M32] = 0; + val[M33] = 1; + } + + /** + * @return a copy of this matrix + */ + public Matrix4 cpy () { + return new Matrix4(this); + } + + /** + * @return the backing float array + */ + public float[] getValues () { + return val; + } + + /** + * Multiplies this matrix with the given matrix, storing the result in this matrix. + * + * @param matrix The other matrix + * @return This matrix for chaining. + */ + public Matrix4 mul (Matrix4 matrix) { + tmp[M00] = val[M00] * matrix.val[M00] + val[M01] * matrix.val[M10] + val[M02] * matrix.val[M20] + val[M03] + * matrix.val[M30]; + tmp[M01] = val[M00] * matrix.val[M01] + val[M01] * matrix.val[M11] + val[M02] * matrix.val[M21] + val[M03] + * matrix.val[M31]; + tmp[M02] = val[M00] * matrix.val[M02] + val[M01] * matrix.val[M12] + val[M02] * matrix.val[M22] + val[M03] + * matrix.val[M32]; + tmp[M03] = val[M00] * matrix.val[M03] + val[M01] * matrix.val[M13] + val[M02] * matrix.val[M23] + val[M03] + * matrix.val[M33]; + tmp[M10] = val[M10] * matrix.val[M00] + val[M11] * matrix.val[M10] + val[M12] * matrix.val[M20] + val[M13] + * matrix.val[M30]; + tmp[M11] = val[M10] * matrix.val[M01] + val[M11] * matrix.val[M11] + val[M12] * matrix.val[M21] + val[M13] + * matrix.val[M31]; + tmp[M12] = val[M10] * matrix.val[M02] + val[M11] * matrix.val[M12] + val[M12] * matrix.val[M22] + val[M13] + * matrix.val[M32]; + tmp[M13] = val[M10] * matrix.val[M03] + val[M11] * matrix.val[M13] + val[M12] * matrix.val[M23] + val[M13] + * matrix.val[M33]; + tmp[M20] = val[M20] * matrix.val[M00] + val[M21] * matrix.val[M10] + val[M22] * matrix.val[M20] + val[M23] + * matrix.val[M30]; + tmp[M21] = val[M20] * matrix.val[M01] + val[M21] * matrix.val[M11] + val[M22] * matrix.val[M21] + val[M23] + * matrix.val[M31]; + tmp[M22] = val[M20] * matrix.val[M02] + val[M21] * matrix.val[M12] + val[M22] * matrix.val[M22] + val[M23] + * matrix.val[M32]; + tmp[M23] = val[M20] * matrix.val[M03] + val[M21] * matrix.val[M13] + val[M22] * matrix.val[M23] + val[M23] + * matrix.val[M33]; + tmp[M30] = val[M30] * matrix.val[M00] + val[M31] * matrix.val[M10] + val[M32] * matrix.val[M20] + val[M33] + * matrix.val[M30]; + tmp[M31] = val[M30] * matrix.val[M01] + val[M31] * matrix.val[M11] + val[M32] * matrix.val[M21] + val[M33] + * matrix.val[M31]; + tmp[M32] = val[M30] * matrix.val[M02] + val[M31] * matrix.val[M12] + val[M32] * matrix.val[M22] + val[M33] + * matrix.val[M32]; + tmp[M33] = val[M30] * matrix.val[M03] + val[M31] * matrix.val[M13] + val[M32] * matrix.val[M23] + val[M33] + * matrix.val[M33]; + return this.set(tmp); + } + + /** + * Transposes the matrix + * + * @return This matrix for chaining + */ + public Matrix4 tra () { + tmp[M00] = val[M00]; + tmp[M01] = val[M10]; + tmp[M02] = val[M20]; + tmp[M03] = val[M30]; + tmp[M10] = val[M01]; + tmp[M11] = val[M11]; + tmp[M12] = val[M21]; + tmp[M13] = val[M31]; + tmp[M20] = val[M02]; + tmp[M21] = val[M12]; + tmp[M22] = val[M22]; + tmp[M23] = val[M32]; + tmp[M30] = val[M03]; + tmp[M31] = val[M13]; + tmp[M32] = val[M23]; + tmp[M33] = val[M33]; + return this.set(tmp); + } + + /** + * Sets the matrix to an identity matrix + * + * @return This matrix for chaining + */ + public Matrix4 idt () { + val[M00] = 1; + val[M01] = 0; + val[M02] = 0; + val[M03] = 0; + val[M10] = 0; + val[M11] = 1; + val[M12] = 0; + val[M13] = 0; + val[M20] = 0; + val[M21] = 0; + val[M22] = 1; + val[M23] = 0; + val[M30] = 0; + val[M31] = 0; + val[M32] = 0; + val[M33] = 1; + return this; + } + + /** + * Inverts the matrix. Throws a RuntimeException in case the matrix is not invertible. Stores the result in this matrix + * + * @return This matrix for chaining + */ + public Matrix4 inv () { + float l_det = this.det(); + if (l_det == 0f) throw new RuntimeException("non-invertible matrix"); + tmp[M00] = val[M12] * val[M23] * val[M31] - val[M13] * val[M22] * val[M31] + val[M13] * val[M21] * val[M32] - val[M11] + * val[M23] * val[M32] - val[M12] * val[M21] * val[M33] + val[M11] * val[M22] * val[M33]; + tmp[M01] = val[M03] * val[M22] * val[M31] - val[M02] * val[M23] * val[M31] - val[M03] * val[M21] * val[M32] + val[M01] + * val[M23] * val[M32] + val[M02] * val[M21] * val[M33] - val[M01] * val[M22] * val[M33]; + tmp[M02] = val[M02] * val[M13] * val[M31] - val[M03] * val[M12] * val[M31] + val[M03] * val[M11] * val[M32] - val[M01] + * val[M13] * val[M32] - val[M02] * val[M11] * val[M33] + val[M01] * val[M12] * val[M33]; + tmp[M03] = val[M03] * val[M12] * val[M21] - val[M02] * val[M13] * val[M21] - val[M03] * val[M11] * val[M22] + val[M01] + * val[M13] * val[M22] + val[M02] * val[M11] * val[M23] - val[M01] * val[M12] * val[M23]; + tmp[M10] = val[M13] * val[M22] * val[M30] - val[M12] * val[M23] * val[M30] - val[M13] * val[M20] * val[M32] + val[M10] + * val[M23] * val[M32] + val[M12] * val[M20] * val[M33] - val[M10] * val[M22] * val[M33]; + tmp[M11] = val[M02] * val[M23] * val[M30] - val[M03] * val[M22] * val[M30] + val[M03] * val[M20] * val[M32] - val[M00] + * val[M23] * val[M32] - val[M02] * val[M20] * val[M33] + val[M00] * val[M22] * val[M33]; + tmp[M12] = val[M03] * val[M12] * val[M30] - val[M02] * val[M13] * val[M30] - val[M03] * val[M10] * val[M32] + val[M00] + * val[M13] * val[M32] + val[M02] * val[M10] * val[M33] - val[M00] * val[M12] * val[M33]; + tmp[M13] = val[M02] * val[M13] * val[M20] - val[M03] * val[M12] * val[M20] + val[M03] * val[M10] * val[M22] - val[M00] + * val[M13] * val[M22] - val[M02] * val[M10] * val[M23] + val[M00] * val[M12] * val[M23]; + tmp[M20] = val[M11] * val[M23] * val[M30] - val[M13] * val[M21] * val[M30] + val[M13] * val[M20] * val[M31] - val[M10] + * val[M23] * val[M31] - val[M11] * val[M20] * val[M33] + val[M10] * val[M21] * val[M33]; + tmp[M21] = val[M03] * val[M21] * val[M30] - val[M01] * val[M23] * val[M30] - val[M03] * val[M20] * val[M31] + val[M00] + * val[M23] * val[M31] + val[M01] * val[M20] * val[M33] - val[M00] * val[M21] * val[M33]; + tmp[M22] = val[M01] * val[M13] * val[M30] - val[M03] * val[M11] * val[M30] + val[M03] * val[M10] * val[M31] - val[M00] + * val[M13] * val[M31] - val[M01] * val[M10] * val[M33] + val[M00] * val[M11] * val[M33]; + tmp[M23] = val[M03] * val[M11] * val[M20] - val[M01] * val[M13] * val[M20] - val[M03] * val[M10] * val[M21] + val[M00] + * val[M13] * val[M21] + val[M01] * val[M10] * val[M23] - val[M00] * val[M11] * val[M23]; + tmp[M30] = val[M12] * val[M21] * val[M30] - val[M11] * val[M22] * val[M30] - val[M12] * val[M20] * val[M31] + val[M10] + * val[M22] * val[M31] + val[M11] * val[M20] * val[M32] - val[M10] * val[M21] * val[M32]; + tmp[M31] = val[M01] * val[M22] * val[M30] - val[M02] * val[M21] * val[M30] + val[M02] * val[M20] * val[M31] - val[M00] + * val[M22] * val[M31] - val[M01] * val[M20] * val[M32] + val[M00] * val[M21] * val[M32]; + tmp[M32] = val[M02] * val[M11] * val[M30] - val[M01] * val[M12] * val[M30] - val[M02] * val[M10] * val[M31] + val[M00] + * val[M12] * val[M31] + val[M01] * val[M10] * val[M32] - val[M00] * val[M11] * val[M32]; + tmp[M33] = val[M01] * val[M12] * val[M20] - val[M02] * val[M11] * val[M20] + val[M02] * val[M10] * val[M21] - val[M00] + * val[M12] * val[M21] - val[M01] * val[M10] * val[M22] + val[M00] * val[M11] * val[M22]; + this.set(tmp); + val[M00] /= l_det; + val[M01] /= l_det; + val[M02] /= l_det; + val[M03] /= l_det; + val[M10] /= l_det; + val[M11] /= l_det; + val[M12] /= l_det; + val[M13] /= l_det; + val[M20] /= l_det; + val[M21] /= l_det; + val[M22] /= l_det; + val[M23] /= l_det; + val[M30] /= l_det; + val[M31] /= l_det; + val[M32] /= l_det; + val[M33] /= l_det; + return this; + } + + /** + * @return The determinant of this matrix + */ + public float det () { + return val[M30] * val[M21] * val[M12] * val[M03] - val[M20] * val[M31] * val[M12] * val[M03] - val[M30] * val[M11] + * val[M22] * val[M03] + val[M10] * val[M31] * val[M22] * val[M03] + val[M20] * val[M11] * val[M32] * val[M03] - val[M10] + * val[M21] * val[M32] * val[M03] - val[M30] * val[M21] * val[M02] * val[M13] + val[M20] * val[M31] * val[M02] * val[M13] + + val[M30] * val[M01] * val[M22] * val[M13] - val[M00] * val[M31] * val[M22] * val[M13] - val[M20] * val[M01] * val[M32] + * val[M13] + val[M00] * val[M21] * val[M32] * val[M13] + val[M30] * val[M11] * val[M02] * val[M23] - val[M10] * val[M31] + * val[M02] * val[M23] - val[M30] * val[M01] * val[M12] * val[M23] + val[M00] * val[M31] * val[M12] * val[M23] + val[M10] + * val[M01] * val[M32] * val[M23] - val[M00] * val[M11] * val[M32] * val[M23] - val[M20] * val[M11] * val[M02] * val[M33] + + val[M10] * val[M21] * val[M02] * val[M33] + val[M20] * val[M01] * val[M12] * val[M33] - val[M00] * val[M21] * val[M12] + * val[M33] - val[M10] * val[M01] * val[M22] * val[M33] + val[M00] * val[M11] * val[M22] * val[M33]; + } + + /** + * Sets the matrix to a projection matrix with a near- and far plane, a field of view in degrees and an aspect ratio. + * + * @param near The near plane + * @param far The far plane + * @param fov The field of view in degrees + * @param aspectRatio The aspect ratio + * @return This matrix for chaining + */ + public Matrix4 setToProjection (float near, float far, float fov, float aspectRatio) { + this.idt(); + float l_fd = (float)(1.0 / Math.tan((fov * (Math.PI / 180)) / 2.0)); + float l_a1 = -(far + near) / (far - near); + float l_a2 = -(2 * far * near) / (far - near); + val[M00] = l_fd / aspectRatio; + val[M10] = 0; + val[M20] = 0; + val[M30] = 0; + val[M01] = 0; + val[M11] = l_fd; + val[M21] = 0; + val[M31] = 0; + val[M02] = 0; + val[M12] = 0; + val[M22] = l_a1; + val[M32] = -1; + val[M03] = 0; + val[M13] = 0; + val[M23] = l_a2; + val[M33] = 0; + return this; + } + + /** + * Sets this matrix to an orthographic projection matrix with the origin at (x,y) extending by width and height. The near plane + * is set to 0, the far plane is set to 1. + * + * @param x The x-coordinate of the origin + * @param y The y-coordinate of the origin + * @param width The width + * @param height The height + * @return This matrix for chaining + */ + public Matrix4 setToOrtho2D (float x, float y, float width, float height) { + setToOrtho(0, width, 0, height, 0, 1); + return this; + } + + /** + * Sets this matrix to an orthographic projection matrix with the origin at (x,y) extending by width and height, having a near + * and far plane. + * + * @param x The x-coordinate of the origin + * @param y The y-coordinate of the origin + * @param width The width + * @param height The height + * @param near The near plane + * @param far The far plane + * @return This matrix for chaining + */ + public Matrix4 setToOrtho2D (float x, float y, float width, float height, float near, float far) { + setToOrtho(0, width, 0, height, near, far); + return this; + } + + /** + * Sets the matrix to an orthographic projection like glOrtho (http://www.opengl.org/sdk/docs/man/xhtml/glOrtho.xml) following + * the OpenGL equivalent + * + * @param left The left clipping plane + * @param right The right clipping plane + * @param bottom The bottom clipping plane + * @param top The top clipping plane + * @param near The near clipping plane + * @param far The far clipping plane + * @return This matrix for chaining + */ + public Matrix4 setToOrtho (float left, float right, float bottom, float top, float near, float far) { + + this.idt(); + float x_orth = 2 / (right - left); + float y_orth = 2 / (top - bottom); + float z_orth = -2 / (far - near); + + float tx = -(right + left) / (right - left); + float ty = -(top + bottom) / (top - bottom); + float tz = (far + near) / (far - near); + + val[M00] = x_orth; + val[M10] = 0; + val[M20] = 0; + val[M30] = 0; + val[M01] = 0; + val[M11] = y_orth; + val[M21] = 0; + val[M31] = 0; + val[M02] = 0; + val[M12] = 0; + val[M22] = z_orth; + val[M32] = 0; + val[M03] = tx; + val[M13] = ty; + val[M23] = tz; + val[M33] = 1; + + return this; + } + + /** + * Sets this matrix to a translation matrix, overwriting it first by an identity matrix and then setting the 4th column to the + * translation vector. + * + * @param vector The translation vector + * @return This matrix for chaining + */ + public Matrix4 setToTranslation (Vector3 vector) { + this.idt(); + val[M03] = vector.x; + val[M13] = vector.y; + val[M23] = vector.z; + return this; + } + + /** + * Sets this matrix to a translation matrix, overwriting it first by an identity matrix and then setting the 4th column to the + * translation vector. + * + * @param x The x-component of the translation vector + * @param y The y-component of the translation vector + * @param z The z-component of the translation vector + * @return This matrix for chaining + */ + public Matrix4 setToTranslation (float x, float y, float z) { + idt(); + val[M03] = x; + val[M13] = y; + val[M23] = z; + return this; + } + + /** + * Sets this matrix to a translation and scaling matrix by first overwritting it with an identity and then setting the + * translation vector in the 4th column and the scaling vector in the diagonal. + * + * @param translation The translation vector + * @param scaling The scaling vector + * @return This matrix for chaining + */ + public Matrix4 setToTranslationAndScaling (Vector3 translation, Vector3 scaling) { + idt(); + val[M03] = translation.x; + val[M13] = translation.y; + val[M23] = translation.z; + val[M00] = scaling.x; + val[M11] = scaling.y; + val[M22] = scaling.z; + return this; + } + + /** + * Sets this matrix to a translation and scaling matrix by first overwritting it with an identity and then setting the + * translation vector in the 4th column and the scaling vector in the diagonal. + * + * @param translationX The x-component of the translation vector + * @param translationY The y-component of the translation vector + * @param translationZ The z-component of the translation vector + * @param scalingX The x-component of the scaling vector + * @param scalingY The x-component of the scaling vector + * @param scalingZ The x-component of the scaling vector + * @return This matrix for chaining + */ + public Matrix4 setToTranslationAndScaling (float translationX, float translationY, float translationZ, float scalingX, + float scalingY, float scalingZ) { + this.idt(); + val[M03] = translationX; + val[M13] = translationY; + val[M23] = translationZ; + val[M00] = scalingX; + val[M11] = scalingY; + val[M22] = scalingZ; + return this; + } + + static Quaternion quat = new Quaternion(); + + /** + * Sets the matrix to a rotation matrix around the given axis. + * + * @param axis The axis + * @param angle The angle in degrees + * @return This matrix for chaining + */ + public Matrix4 setToRotation (Vector3 axis, float angle) { + idt(); + if (angle == 0) return this; + return this.set(quat.set(axis, angle)); + } + + /** + * Sets this matrix to a rotation matrix from the given euler angles. + * @param yaw the yaw in degrees + * @param pitch the pitch in degress + * @param roll the roll in degrees + * @return this matrix + */ + public Matrix4 setFromEulerAngles (float yaw, float pitch, float roll) { + idt(); + quat.setEulerAngles(yaw, pitch, roll); + return this.set(quat); + } + + /** + * Sets this matrix to a scaling matrix + * + * @param vector The scaling vector + * @return This matrix for chaining. + */ + public Matrix4 setToScaling (Vector3 vector) { + idt(); + val[M00] = vector.x; + val[M11] = vector.y; + val[M22] = vector.z; + return this; + } + + /** + * Sets this matrix to a scaling matrix + * + * @param x The x-component of the scaling vector + * @param y The y-component of the scaling vector + * @param z The z-component of the scaling vector + * @return This matrix for chaining. + */ + public Matrix4 setToScaling (float x, float y, float z) { + idt(); + val[M00] = x; + val[M11] = y; + val[M22] = z; + return this; + } + + static Vector3 l_vez = new Vector3(); + static Vector3 l_vex = new Vector3(); + static Vector3 l_vey = new Vector3(); + + /** + * Sets the matrix to a look at matrix with a direction and an up vector. Multiply with a translation matrix to get a camera + * model view matrix. + * + * @param direction The direction vector + * @param up The up vector + * @return This matrix for chaining + */ + public Matrix4 setToLookAt (Vector3 direction, Vector3 up) { l_vez.set(direction).nor(); l_vex.set(direction).nor(); - l_vex.crs(up).nor(); + l_vex.crs(up).nor(); l_vey.set(l_vex).crs(l_vez).nor(); idt(); - val[M00]=l_vex.x; - val[M01]=l_vex.y; - val[M02]=l_vex.z; - val[M10]=l_vey.x; - val[M11]=l_vey.y; - val[M12]=l_vey.z; - val[M20]=-l_vez.x; - val[M21]=-l_vez.y; - val[M22]=-l_vez.z; - - return this; - } - - /** - * Sets this matrix to a look at matrix with the given - * position, target and up vector. - * - * @param position the position - * @param target the target - * @param up the up vector - * @return this matrix - */ - static final Vector3 tmpVec = new Vector3(); - static final Matrix4 tmpMat = new Matrix4(); - public Matrix4 setToLookAt( Vector3 position, Vector3 target, Vector3 up ) - { - tmpVec.set(target).sub(position); - setToLookAt( tmpVec, up); - this.mul( tmpMat.setToTranslation( position.tmp().mul(-1) ) ); - - return this; - } - - static Vector3 right = new Vector3(); - static Vector3 tmpForward = new Vector3(); - static Vector3 tmpUp = new Vector3(); - public Matrix4 setToWorld( Vector3 position, Vector3 forward, Vector3 up ) - { - tmpForward.set(forward).nor(); - right.set(tmpForward).crs(up).nor(); - tmpUp.set(right).crs(tmpForward).nor(); - - this.set( right, tmpUp, tmpForward, position ); - return this; - } - - /** - * {@inheritDoc} - */ - public String toString() - { - return - "["+val[M00]+"|"+val[M01]+"|"+val[M02]+"|"+val[M03]+"]\n"+ - "["+val[M10]+"|"+val[M11]+"|"+val[M12]+"|"+val[M13]+"]\n"+ - "["+val[M20]+"|"+val[M21]+"|"+val[M22]+"|"+val[M23]+"]\n"+ - "["+val[M30]+"|"+val[M31]+"|"+val[M32]+"|"+val[M33]+"]\n"; - } - - /** - * Linearly interpolates between this matrix and the given matrix mixing by alpha - * @param matrix the matrix - * @param alpha the alpha value in the range [0,1] - */ - public void lerp(Matrix4 matrix, float alpha) - { - for( int i = 0; i < 16; i++ ) - this.val[i] = this.val[i] * (1-alpha) + matrix.val[i] * alpha; - } - - /** - * Sets this matrix to the given 3x3 matrix. The third - * column of this matrix is set to (0,0,1,0). + val[M00] = l_vex.x; + val[M01] = l_vex.y; + val[M02] = l_vex.z; + val[M10] = l_vey.x; + val[M11] = l_vey.y; + val[M12] = l_vey.z; + val[M20] = -l_vez.x; + val[M21] = -l_vez.y; + val[M22] = -l_vez.z; + + return this; + } + + /** + * Sets this matrix to a look at matrix with the given position, target and up vector. + * + * @param position the position + * @param target the target + * @param up the up vector + * @return this matrix + */ + static final Vector3 tmpVec = new Vector3(); + static final Matrix4 tmpMat = new Matrix4(); + + public Matrix4 setToLookAt (Vector3 position, Vector3 target, Vector3 up) { + tmpVec.set(target).sub(position); + setToLookAt(tmpVec, up); + this.mul(tmpMat.setToTranslation(position.tmp().mul(-1))); + + return this; + } + + static Vector3 right = new Vector3(); + static Vector3 tmpForward = new Vector3(); + static Vector3 tmpUp = new Vector3(); + + public Matrix4 setToWorld (Vector3 position, Vector3 forward, Vector3 up) { + tmpForward.set(forward).nor(); + right.set(tmpForward).crs(up).nor(); + tmpUp.set(right).crs(tmpForward).nor(); + + this.set(right, tmpUp, tmpForward, position); + return this; + } + + /** + * {@inheritDoc} + */ + public String toString () { + return "[" + val[M00] + "|" + val[M01] + "|" + val[M02] + "|" + val[M03] + "]\n" + "[" + val[M10] + "|" + val[M11] + "|" + + val[M12] + "|" + val[M13] + "]\n" + "[" + val[M20] + "|" + val[M21] + "|" + val[M22] + "|" + val[M23] + "]\n" + "[" + + val[M30] + "|" + val[M31] + "|" + val[M32] + "|" + val[M33] + "]\n"; + } + + /** + * Linearly interpolates between this matrix and the given matrix mixing by alpha + * @param matrix the matrix + * @param alpha the alpha value in the range [0,1] + */ + public void lerp (Matrix4 matrix, float alpha) { + for (int i = 0; i < 16; i++) + this.val[i] = this.val[i] * (1 - alpha) + matrix.val[i] * alpha; + } + + /** + * Sets this matrix to the given 3x3 matrix. The third column of this matrix is set to (0,0,1,0). * @param mat the matrix */ - public Matrix4 set(Matrix3 mat) - { + public Matrix4 set (Matrix3 mat) { val[0] = mat.vals[0]; val[1] = mat.vals[1]; val[2] = mat.vals[2]; @@ -637,7 +689,10 @@ public final class Matrix4 val[5] = mat.vals[4]; val[6] = mat.vals[5]; val[7] = 0; - val[8] = 0; val[9] = 0; val[10] = 1; val[11] = 0; + val[8] = 0; + val[9] = 0; + val[10] = 1; + val[11] = 0; val[12] = mat.vals[6]; val[13] = mat.vals[7]; val[14] = 0; @@ -645,4 +700,3 @@ public final class Matrix4 return this; } } - diff --git a/gdx/src/com/badlogic/gdx/math/Plane.java b/gdx/src/com/badlogic/gdx/math/Plane.java index 50852f64f..56f8f2fe2 100644 --- a/gdx/src/com/badlogic/gdx/math/Plane.java +++ b/gdx/src/com/badlogic/gdx/math/Plane.java @@ -1,107 +1,91 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math; +import com.badlogic.gdx.math.Plane.PlaneSide; /** - * A plane defined via a unit length normal and the distance from the - * origin, as you learned in your math class. + * A plane defined via a unit length normal and the distance from the origin, as you learned in your math class. * * @author badlogicgames@gmail.com - * + * */ -public final class Plane -{ +public final class Plane { /** - * Enum specifying on which side a point lies respective - * to the plane and it's normal. {@link PlaneSide.Front} - * is the side to which the normal points. + * Enum specifying on which side a point lies respective to the plane and it's normal. {@link PlaneSide.Front} is the side to + * which the normal points. * * @author mzechner - * + * */ - public enum PlaneSide - { - OnPlane, - Back, - Front + public enum PlaneSide { + OnPlane, Back, Front } - + public final Vector3 normal = new Vector3(); public float d = 0; - + /** - * Constructs a new plane based on the normal and distance - * to the origin. + * Constructs a new plane based on the normal and distance to the origin. * * @param normal The plane normal * @param d The distance to the origin */ - public Plane( Vector3 normal, float d ) - { - this.normal.set( normal ).nor(); + public Plane (Vector3 normal, float d) { + this.normal.set(normal).nor(); this.d = d; } - + /** - * Constructs a new plane based on the normal and a - * point on the plane. + * Constructs a new plane based on the normal and a point on the plane. * * @param normal The normal * @param point The point on the plane */ - public Plane( Vector3 normal, Vector3 point ) - { + public Plane (Vector3 normal, Vector3 point) { this.normal.set(normal).nor(); - this.d = -this.normal.dot( point ); + this.d = -this.normal.dot(point); } - + /** - * Constructs a new plane out of the three given points - * that are considered to be on the plane. The normal - * is calculated via a cross product between (point1-point2)x(point2-point3) + * Constructs a new plane out of the three given points that are considered to be on the plane. The normal is calculated via a + * cross product between (point1-point2)x(point2-point3) * - * @param point1 The first point + * @param point1 The first point * @param point2 The second point * @param point3 The third point */ - public Plane( Vector3 point1, Vector3 point2, Vector3 point3 ) - { - set( point1, point2, point3 ); + public Plane (Vector3 point1, Vector3 point2, Vector3 point3) { + set(point1, point2, point3); } - + /** - * Sets the plane normal and distance to the origin based - * on the three given points which are considered to be - * on the plane. The normal is calculated via a cross product - * between (point1-point2)x(point2-point3) + * Sets the plane normal and distance to the origin based on the three given points which are considered to be on the plane. + * The normal is calculated via a cross product between (point1-point2)x(point2-point3) * * @param point1 * @param point2 * @param point3 */ - public void set( Vector3 point1, Vector3 point2, Vector3 point3 ) - { + public void set (Vector3 point1, Vector3 point2, Vector3 point3) { Vector3 l = point1.tmp().sub(point2); Vector3 r = point2.tmp2().sub(point3); - Vector3 nor = l.crs( r ).nor(); - normal.set( nor ); - d = -point1.dot( nor ); + Vector3 nor = l.crs(r).nor(); + normal.set(nor); + d = -point1.dot(nor); } - + /** * Sets the plane normal and distance * @param nx normal x-component @@ -109,101 +93,86 @@ public final class Plane * @param nz normal z-component * @param d distance to origin */ - public void set( float nx, float ny, float nz, float d ) - { - normal.set( nx, ny, nz ); + public void set (float nx, float ny, float nz, float d) { + normal.set(nx, ny, nz); this.d = d; } - + /** - * Calculates the shortest signed distance between the plane and the - * given point. + * Calculates the shortest signed distance between the plane and the given point. * * @param point The point * @return the shortest signed distance between the plane and the point */ - public float distance( Vector3 point ) - { - return normal.dot( point ) + d; + public float distance (Vector3 point) { + return normal.dot(point) + d; } - + /** - * Returns on which side the given point lies relative to the - * plane and its normal. PlaneSide.Front refers to the side - * the plane normal points to. + * Returns on which side the given point lies relative to the plane and its normal. PlaneSide.Front refers to the side the + * plane normal points to. * * @param point The point * @return The side the point lies relative to the plane */ - public PlaneSide testPoint( Vector3 point ) - { - float dist = normal.dot( point ) + d; - - if( dist == 0 ) + public PlaneSide testPoint (Vector3 point) { + float dist = normal.dot(point) + d; + + if (dist == 0) return PlaneSide.OnPlane; + else if (dist < 0) + return PlaneSide.Back; else - if( dist < 0 ) - return PlaneSide.Back; - else - return PlaneSide.Front; + return PlaneSide.Front; } - + /** - * Returns whether the plane is facing the direction vector. - * Think of the direction vector as the direction a camera - * looks in. This method will return true if the front side - * of the plane determined by its normal faces the camera. + * Returns whether the plane is facing the direction vector. Think of the direction vector as the direction a camera looks in. + * This method will return true if the front side of the plane determined by its normal faces the camera. * * @param direction the direction * @return whether the plane is front facing */ - public boolean isFrontFacing( Vector3 direction ) - { - float dot = normal.dot( direction ); + public boolean isFrontFacing (Vector3 direction) { + float dot = normal.dot(direction); return dot <= 0; } - + /** * @return The normal */ - public Vector3 getNormal( ) - { + public Vector3 getNormal () { return normal; } - + /** * @return The distance to the origin */ - public float getD( ) - { + public float getD () { return d; } /** * Sets the plane to the given point and normal. - * + * * @param point the point on the plane * @param normal the normal of the plane */ - public void set(Vector3 point, Vector3 normal) - { - this.normal.set( normal ); - d = -point.dot( normal ); + public void set (Vector3 point, Vector3 normal) { + this.normal.set(normal); + d = -point.dot(normal); } - /** * Sets this plane from the given plane * @param plane the plane */ - public void set(Plane plane) - { + public void set (Plane plane) { this.normal.set(plane.normal); this.d = plane.d; } - - public String toString( ) - { + + public String toString () { return normal.toString() + ", " + d; } } diff --git a/gdx/src/com/badlogic/gdx/math/Quaternion.java b/gdx/src/com/badlogic/gdx/math/Quaternion.java index 9787107e8..cf462fd3a 100644 --- a/gdx/src/com/badlogic/gdx/math/Quaternion.java +++ b/gdx/src/com/badlogic/gdx/math/Quaternion.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math; import java.io.Serializable; @@ -21,165 +19,142 @@ import java.io.Serializable; * A simple quaternion class. See http://en.wikipedia.org/wiki/Quaternion for more information. * * @author badlogicgames@gmail.com - * + * */ -public final class Quaternion implements Serializable -{ +public final class Quaternion implements Serializable { private static final long serialVersionUID = -7661875440774897168L; public float x; public float y; public float z; - public float w; - - - /** - * Constructor, sets the four components of the quaternion. - * @param x The x-component - * @param y The y-component - * @param z The z-component - * @param w The w-component - */ - public Quaternion(float x, float y, float z, float w) - { - this.set(x,y,z,w); - } - - Quaternion( ) - { - - } - - /** - * Constructor, sets the quaternion components from the given - * quaternion. - * - * @param quaternion The quaternion to copy. - */ - public Quaternion(Quaternion quaternion) - { - this.set(quaternion); - } - - /** - * Constructor, sets the quaternion from the given axis vector - * and the angle around that axis in degrees. - * - * @param axis The axis - * @param angle The angle in degrees. - */ - public Quaternion(Vector3 axis, float angle) - { - this.set(axis,angle); - } - - /** - * Sets the components of the quaternion - * @param x The x-component - * @param y The y-component - * @param z The z-component - * @param w The w-component - * @return This quaternion for chaining - */ - public Quaternion set(float x, float y, float z, float w) - { - this.x=x; - this.y=y; - this.z=z; - this.w=w; - return this; - } - - /** - * Sets the quaternion components from the given quaternion. - * @param quaternion The quaternion. - * @return This quaternion for chaining. - */ - public Quaternion set(Quaternion quaternion) - { - return this.set(quaternion.x,quaternion.y,quaternion.z,quaternion.w); - } - - /** - * Sets the quaternion components from the given axis and - * angle around that axis. - * - * @param axis The axis - * @param angle The angle in degrees - * @return This quaternion for chaining. - */ - public Quaternion set(Vector3 axis, float angle) - { - float l_ang= (float)Math.toRadians(angle); - float l_sin = (float)Math.sin(l_ang/2); - float l_cos = (float)Math.cos(l_ang/2); - return this.set(axis.x*l_sin, - axis.y*l_sin, - axis.z*l_sin, - l_cos).nor(); - } - - /** - * @return a copy of this quaternion - */ - public Quaternion cpy() - { - return new Quaternion(this); - } - - /** - * @return the euclidian length of this quaternion - */ - public float len() - { - return (float)Math.sqrt(x * x + y * y + z * z + w * w ); - } - - /** - * Normalizes the quaternion. - * @return This quaternion for chaining. - */ - public Quaternion nor() - { - float l_len=this.len(); - return this.set(x/l_len, - y/l_len, - z/l_len, - w/l_len); - } - - /** - * {@inheritDoc} - */ - public String toString() - { - return "["+x+"|"+y+"|"+z+"|"+w+"]"; - } - - /** - * Sets the quaternion to the given euler angles. - * @param yaw the yaw in degrees - * @param pitch the pitch in degress - * @param roll the roll in degess - * @return this quaternion - */ - public Quaternion setEulerAngles( float yaw, float pitch, float roll ) - { - yaw = (float)Math.toRadians(yaw); - pitch = (float)Math.toRadians(pitch); - roll = (float)Math.toRadians(roll); - float num9 = roll * 0.5f; - float num6 = (float)Math.sin(num9); - float num5 = (float)Math.cos(num9); - float num8 = pitch * 0.5f; - float num4 = (float)Math.sin(num8); - float num3 = (float)Math.cos(num8); - float num7 = yaw * 0.5f; - float num2 = (float)Math.sin(num7); - float num = (float)Math.cos(num7); - x = ((num * num4) * num5) + ((num2 * num3) * num6); - y = ((num2 * num3) * num5) - ((num * num4) * num6); - z = ((num * num3) * num6) - ((num2 * num4) * num5); - w = ((num * num3) * num5) + ((num2 * num4) * num6); - return this; - } + public float w; + + /** + * Constructor, sets the four components of the quaternion. + * @param x The x-component + * @param y The y-component + * @param z The z-component + * @param w The w-component + */ + public Quaternion (float x, float y, float z, float w) { + this.set(x, y, z, w); + } + + Quaternion () { + + } + + /** + * Constructor, sets the quaternion components from the given quaternion. + * + * @param quaternion The quaternion to copy. + */ + public Quaternion (Quaternion quaternion) { + this.set(quaternion); + } + + /** + * Constructor, sets the quaternion from the given axis vector and the angle around that axis in degrees. + * + * @param axis The axis + * @param angle The angle in degrees. + */ + public Quaternion (Vector3 axis, float angle) { + this.set(axis, angle); + } + + /** + * Sets the components of the quaternion + * @param x The x-component + * @param y The y-component + * @param z The z-component + * @param w The w-component + * @return This quaternion for chaining + */ + public Quaternion set (float x, float y, float z, float w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + return this; + } + + /** + * Sets the quaternion components from the given quaternion. + * @param quaternion The quaternion. + * @return This quaternion for chaining. + */ + public Quaternion set (Quaternion quaternion) { + return this.set(quaternion.x, quaternion.y, quaternion.z, quaternion.w); + } + + /** + * Sets the quaternion components from the given axis and angle around that axis. + * + * @param axis The axis + * @param angle The angle in degrees + * @return This quaternion for chaining. + */ + public Quaternion set (Vector3 axis, float angle) { + float l_ang = (float)Math.toRadians(angle); + float l_sin = (float)Math.sin(l_ang / 2); + float l_cos = (float)Math.cos(l_ang / 2); + return this.set(axis.x * l_sin, axis.y * l_sin, axis.z * l_sin, l_cos).nor(); + } + + /** + * @return a copy of this quaternion + */ + public Quaternion cpy () { + return new Quaternion(this); + } + + /** + * @return the euclidian length of this quaternion + */ + public float len () { + return (float)Math.sqrt(x * x + y * y + z * z + w * w); + } + + /** + * Normalizes the quaternion. + * @return This quaternion for chaining. + */ + public Quaternion nor () { + float l_len = this.len(); + return this.set(x / l_len, y / l_len, z / l_len, w / l_len); + } + + /** + * {@inheritDoc} + */ + public String toString () { + return "[" + x + "|" + y + "|" + z + "|" + w + "]"; + } + + /** + * Sets the quaternion to the given euler angles. + * @param yaw the yaw in degrees + * @param pitch the pitch in degress + * @param roll the roll in degess + * @return this quaternion + */ + public Quaternion setEulerAngles (float yaw, float pitch, float roll) { + yaw = (float)Math.toRadians(yaw); + pitch = (float)Math.toRadians(pitch); + roll = (float)Math.toRadians(roll); + float num9 = roll * 0.5f; + float num6 = (float)Math.sin(num9); + float num5 = (float)Math.cos(num9); + float num8 = pitch * 0.5f; + float num4 = (float)Math.sin(num8); + float num3 = (float)Math.cos(num8); + float num7 = yaw * 0.5f; + float num2 = (float)Math.sin(num7); + float num = (float)Math.cos(num7); + x = ((num * num4) * num5) + ((num2 * num3) * num6); + y = ((num2 * num3) * num5) - ((num * num4) * num6); + z = ((num * num3) * num6) - ((num2 * num4) * num5); + w = ((num * num3) * num5) + ((num2 * num4) * num6); + return this; + } } diff --git a/gdx/src/com/badlogic/gdx/math/Rectangle.java b/gdx/src/com/badlogic/gdx/math/Rectangle.java index 7f83fdc06..713764f37 100644 --- a/gdx/src/com/badlogic/gdx/math/Rectangle.java +++ b/gdx/src/com/badlogic/gdx/math/Rectangle.java @@ -1,89 +1,78 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math; /** - * Encapsulates a 2D rectangle defined by it's bottom corner point - * and its extends in x (width) and y (height). + * Encapsulates a 2D rectangle defined by it's bottom corner point and its extends in x (width) and y (height). * @author badlogicgames@gmail.com - * + * */ -public final class Rectangle -{ +public final class Rectangle { private float x, y; private float width, height; - + /** * Constructs a new rectangle with all values set to zero */ - public Rectangle( ) - { - + public Rectangle () { + } - + /** - * Constructs a new rectangle with the given corner point in - * the bottom left and dimensions. + * Constructs a new rectangle with the given corner point in the bottom left and dimensions. * @param x The corner point x-coordinate * @param y The corner point y-coordinate * @param width The width * @param height The height */ - public Rectangle( float x, float y, float width, float height ) - { + public Rectangle (float x, float y, float width, float height) { this.x = x; this.y = y; this.width = width; this.height = height; } - + /** - * Constructs a rectangle based on the given rectangle + * Constructs a rectangle based on the given rectangle * @param rect The rectangle */ - public Rectangle( Rectangle rect ) - { + public Rectangle (Rectangle rect) { x = rect.x; y = rect.y; width = rect.width; height = rect.height; } - + /** * @return the x-coordinate of the bottom left corner */ - public float getX() - { + public float getX () { return x; } - + /** * Sets the x-coordinate of the bottom left corner * @param x The x-coordinate */ - public void setX( float x ) - { + public void setX (float x) { this.x = x; } - + /** * @return the y-coordinate of the bottom left corner */ - public float getY() - { + public float getY () { return y; } @@ -91,42 +80,37 @@ public final class Rectangle * Sets the y-coordinate of the bottom left corner * @param y The y-coordinate */ - public void setY( float y ) - { + public void setY (float y) { this.y = y; } - + /** * @return the width */ - public float getWidth( ) - { + public float getWidth () { return width; } - + /** * Sets the width of this rectangle * @param width The width */ - public void setWidth( float width ) - { + public void setWidth (float width) { this.width = width; } - + /** * @return the height */ - public float getHeight( ) - { + public float getHeight () { return height; } - + /** * Sets the height of this rectangle * @param height The height */ - public void setHeight( float height ) - { + public void setHeight (float height) { this.height = height; } } diff --git a/gdx/src/com/badlogic/gdx/math/Vector2.java b/gdx/src/com/badlogic/gdx/math/Vector2.java index 7328b8743..0010fd53f 100644 --- a/gdx/src/com/badlogic/gdx/math/Vector2.java +++ b/gdx/src/com/badlogic/gdx/math/Vector2.java @@ -1,181 +1,162 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math; /** - * Encapsulates a 2D vector. Allows chaining methods by returning a - * reference to itself + * Encapsulates a 2D vector. Allows chaining methods by returning a reference to itself * @author badlogicgames@gmail.com - * + * */ -public final class Vector2 -{ +public final class Vector2 { /** static temporary vector **/ private final static Vector2 tmp = new Vector2(); - + /** the x-component of this vector **/ public float x; /** the y-component of this vector **/ public float y; - + /** * Constructs a new vector at (0,0) */ - public Vector2( ) - { - + public Vector2 () { + } - + /** * Constructs a vector with the given components * @param x The x-component * @param y The y-component */ - public Vector2( float x, float y ) - { + public Vector2 (float x, float y) { this.x = x; this.y = y; } - + /** * Constructs a vector from the given vector * @param v The vector */ - public Vector2( Vector2 v ) - { - set( v ); + public Vector2 (Vector2 v) { + set(v); } - + /** * @return a copy of this vector */ - public Vector2 cpy( ) - { - return new Vector2( this ); + public Vector2 cpy () { + return new Vector2(this); } - + /** * @return The euclidian length */ - public float len( ) - { - return (float)Math.sqrt( x * x + y * y ); + public float len () { + return (float)Math.sqrt(x * x + y * y); } - + /** * @return The squared euclidian length */ - public float len2( ) - { + public float len2 () { return x * x + y * y; } - + /** * Sets this vector from the given vector * @param v The vector * @return This vector for chaining */ - public Vector2 set( Vector2 v ) - { + public Vector2 set (Vector2 v) { x = v.x; y = v.y; return this; } - + /** * Sets the components of this vector * @param x The x-component * @param y The y-component * @return This vector for chaining */ - public Vector2 set( float x, float y ) - { + public Vector2 set (float x, float y) { this.x = x; this.y = y; return this; } - + /** * Substracts the given vector from this vector. * @param v The vector * @return This vector for chaining */ - public Vector2 sub( Vector2 v ) - { + public Vector2 sub (Vector2 v) { x -= v.x; y -= v.y; return this; } - + /** * Normalizes this vector * @return This vector for chaining */ - public Vector2 nor( ) - { - float len = len( ); - if( len != 0 ) - { + public Vector2 nor () { + float len = len(); + if (len != 0) { x /= len; y /= len; } return this; } - + /** * Adds the given vector to this vector * @param v The vector * @return This vector for chaining */ - public Vector2 add( Vector2 v ) - { + public Vector2 add (Vector2 v) { x += v.x; y += v.y; return this; } - + /** - * Adds the given components to this vector + * Adds the given components to this vector * @param x The x-component * @param y The y-component * @return This vector for chaining */ - public Vector2 add( float x, float y ) - { + public Vector2 add (float x, float y) { this.x += x; this.y += y; return this; } - + /** * @param v The other vector * @return The dot product between this and the other vector */ - public float dot( Vector2 v ) - { + public float dot (Vector2 v) { return x * v.x + y * v.y; } - + /** * Multiplies this vector by a scalar * @param scalar The scalar * @return This vector for chaining */ - public Vector2 mul( float scalar ) - { + public Vector2 mul (float scalar) { x *= scalar; y *= scalar; return this; @@ -185,38 +166,34 @@ public final class Vector2 * @param v The other vector * @return the distance between this and the other vector */ - public float dst(Vector2 v) - { + public float dst (Vector2 v) { float x_d = v.x - x; float y_d = v.y - y; - return (float)Math.sqrt( x_d * x_d + y_d * y_d ); + return (float)Math.sqrt(x_d * x_d + y_d * y_d); } - + /** * @param x The x-component of the other vector * @param y The y-component of the other vector * @return the distance between this and the other vector */ - public float dst( float x, float y ) - { + public float dst (float x, float y) { float x_d = x - this.x; float y_d = y - this.y; - return (float)Math.sqrt( x_d * x_d + y_d * y_d ); + return (float)Math.sqrt(x_d * x_d + y_d * y_d); } - + /** * @param v The other vector * @return the squared distance between this and the other vector */ - public float dst2(Vector2 v) - { + public float dst2 (Vector2 v) { float x_d = v.x - x; float y_d = v.y - y; return x_d * x_d + y_d * y_d; - } - - public String toString( ) - { + } + + public String toString () { return "[" + x + ":" + y + "]"; } @@ -226,28 +203,26 @@ public final class Vector2 * @param y The y-component of the other vector * @return This vector for chaining */ - public Vector2 sub(float x, float y) - { + public Vector2 sub (float x, float y) { this.x -= x; this.y -= y; return this; } - - /** - * @return a temporary copy of this vector. Use with care as this is backed by a single static Vector2 instance. v1.tmp().add( v2.tmp() ) will not work! + + /** + * @return a temporary copy of this vector. Use with care as this is backed by a single static Vector2 instance. v1.tmp().add( + * v2.tmp() ) will not work! */ - public Vector2 tmp( ) - { + public Vector2 tmp () { return tmp.set(this); } - + /** * Multiplies this vector by the given matrix * @param mat the matrix * @return this vector */ - public Vector2 mul( Matrix3 mat ) - { + public Vector2 mul (Matrix3 mat) { float x = this.x * mat.vals[0] + this.y * mat.vals[3] + mat.vals[6]; float y = this.x * mat.vals[1] + this.y * mat.vals[4] + mat.vals[7]; this.x = x; diff --git a/gdx/src/com/badlogic/gdx/math/Vector3.java b/gdx/src/com/badlogic/gdx/math/Vector3.java index 1263bb76a..ab1fd04b6 100644 --- a/gdx/src/com/badlogic/gdx/math/Vector3.java +++ b/gdx/src/com/badlogic/gdx/math/Vector3.java @@ -1,481 +1,422 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ -package com.badlogic.gdx.math; +package com.badlogic.gdx.math; /** - * Encapsulates a 3D vector. Allows chaining operations by - * returning a reference to it self in all modification methods. + * Encapsulates a 3D vector. Allows chaining operations by returning a reference to it self in all modification methods. * * @author badlogicgames@gmail.com - * + * */ -public final class Vector3 -{ +public final class Vector3 { private static final long serialVersionUID = 3840054589595372522L; /** the x-component of this vector **/ public float x; /** the x-component of this vector **/ public float y; /** the x-component of this vector **/ - public float z; - - private static Vector3 tmp = new Vector3(); - private static Vector3 tmp2 = new Vector3(); - private static Vector3 tmp3 = new Vector3(); - - /** - * Constructs a vector at (0,0,0) - */ - public Vector3() - { - } - - /** - * Creates a vector with the given components - * - * @param x The x-component - * @param y The y-component - * @param z The z-component - */ - public Vector3(float x, float y, float z) - { - this.set(x,y,z); - } - - /** - * Creates a vector from the given vector - * - * @param vector The vector - */ - public Vector3(Vector3 vector) - { - this.set(vector); - } - - /** - * Creates a vector from the given array. The - * array must have at least 3 elements. - * - * @param values The array - */ - public Vector3(float[] values) - { - this.set(values[0],values[1],values[2]); - } - - /** - * Sets the vector to the given components - * - * @param x The x-component - * @param y The y-component - * @param z The z-component - * @return this vector for chaining - */ - public Vector3 set(float x, float y, float z) - { - this.x=x; - this.y=y; - this.z=z; - return this; - } - - /** - * Sets the components of the given vector - * - * @param vector The vector - * @return This vector for chaining - */ - public Vector3 set(Vector3 vector) - { - return this.set(vector.x,vector.y,vector.z); - } - - /** - * Sets the components from the array. The array - * must have at least 3 elements - * - * @param values The array - * @return this vector for chaining - */ - public Vector3 set(float[] values) - { - return this.set(values[0],values[1],values[2]); - } - - /** - * @return a copy of this vector - */ - public Vector3 cpy() - { - return new Vector3(this); - } - - /** - * NEVER EVER SAVE THIS REFERENCE! - * - * @return - */ - public Vector3 tmp() - { - return tmp.set( this ); - } - - /** - * NEVER EVER SAVE THIS REFERENCE! - * - * @return - */ - public Vector3 tmp2() - { - return tmp2.set(this); - } - - /** - * NEVER EVER SAVE THIS REFERENCE! - * - * @return - */ - Vector3 tmp3() - { - return tmp3.set(this); - } - - /** - * Adds the given vector to this vector - * - * @param vector The other vector - * @return This vector for chaining - */ - public Vector3 add(Vector3 vector) - { - return this.add(vector.x,vector.y,vector.z); - } - - /** - * Adds the given vector to this component - * @param x The x-component of the other vector - * @param y The y-component of the other vector - * @param z The z-component of the other vector - * @return This vector for chaining. - */ - public Vector3 add(float x, float y, float z) - { - return this.set(this.x+x,this.y+y,this.z+z); - } - - /** - * Adds the given value to all three components of the - * vector. - * - * @param values The value - * @return This vector for chaining - */ - public Vector3 add(float values) - { - return this.set(this.x+values,this.y+values,this.z+values); - } - - /** - * Subtracts the given vector from this vector - * @param a_vec The other vector - * @return This vector for chaining - */ - public Vector3 sub(Vector3 a_vec) - { - return this.sub(a_vec.x,a_vec.y,a_vec.z); - } - - /** - * Subtracts the other vector from this vector. - * - * @param x The x-component of the other vector - * @param y The y-component of the other vector - * @param z The z-component of the other vector - * @return This vector for chaining - */ - public Vector3 sub(float x, float y, float z) - { - return this.set(this.x-x,this.y-y,this.z-z); - } - - /** - * Subtracts the given value from all components of this vector - * - * @param value The value - * @return This vector for chaining - */ - public Vector3 sub(float value) - { - return this.set(this.x-value,this.y-value,this.z-value); - } - - /** - * Multiplies all components of this vector by the given value - * - * @param value The value - * @return This vector for chaining - */ - public Vector3 mul(float value) - { - return this.set(this.x*value,this.y*value,this.z*value); - } - - /** - * Divides all components of this vector by the given value - * - * @param value The value - * @return This vector for chaining - */ - public Vector3 div(float value) - { - float d = 1 / value; - return this.set(this.x*d,this.y*d,this.z*d); - } - - /** - * @return The euclidian length - */ - public float len() - { - return (float)Math.sqrt(x*x+y*y+z*z); - } - - /** - * @return The squared euclidian length - */ - public float len2( ) - { - return x * x + y * y + z * z; - } - - /** - * @param vector The other vector - * @return Wether this and the other vector are equal - */ - public boolean idt(Vector3 vector) - { - return x==vector.x && - y==vector.y && - z==vector.z; - } - - /** - * @param vector The other vector - * @return The euclidian distance between this and the other vector - */ - public float dst(Vector3 vector) - { - float a = vector.x-x; - float b = vector.y-y; - float c = vector.z-z; - - a *= a; - b *= b; - c *= c; - - return (float)Math.sqrt( a + b + c ); - } - - /** - * @param vector The other vector - * @return The squared euclidian distance between this and the other vector - */ - public float dist2( Vector3 vector ) - { - float a = vector.x - x; - float b = vector.y - y; - float c = vector.z - z; - return a * a + b * b + c * c; - } - - /** - * Normalizes this vector to unit length - * - * @return This vector for chaining - */ - public Vector3 nor() - { - if( x == 0 && y == 0 && z == 0 ) - return this; - else - return this.div(this.len()); - } - - /** - * @param vector The other vector - * @return The dot product between this and the other vector - */ - public float dot(Vector3 vector) - { - return x*vector.x+y*vector.y+z*vector.z; - } - - /** - * Sets this vector to the cross product between it and the other vector. - * @param vector The other vector - * @return This vector for chaining - */ - public Vector3 crs(Vector3 vector) - { - return this.set(y*vector.z-z*vector.y, - z*vector.x-x*vector.z, - x*vector.y-y*vector.x); - } - - /** - * Sets this vector to the cross product between it and the other vector. - * @param x The x-component of the other vector - * @param y The y-component of the other vector - * @param z The z-component of the other vector - * @return This vector for chaining - */ - public Vector3 crs(float x, float y, float z) - { - return this.set(y*z-z*y, - z*x-x*z, - x*y-y*x); - } - - /** - * Multiplies the vector by the given matrix. - * @param matrix The matrix - * @return This vector for chaining - */ - public Vector3 mul(Matrix4 matrix) - { - float l_mat[] = matrix.val; - return this.set(x*l_mat[Matrix4.M00]+y*l_mat[Matrix4.M01]+z*l_mat[Matrix4.M02]+l_mat[Matrix4.M03], - x*l_mat[Matrix4.M10]+y*l_mat[Matrix4.M11]+z*l_mat[Matrix4.M12]+l_mat[Matrix4.M13], - x*l_mat[Matrix4.M20]+y*l_mat[Matrix4.M21]+z*l_mat[Matrix4.M22]+l_mat[Matrix4.M23]); - } - - /** - * Multiplies this vector by the given matrix dividing by - * w. This is mostly used to project/unproject vectors - * via a perspective projection matrix. - * - * @param matrix The matrix. - * @return This vector for chaining - */ - public Vector3 prj(Matrix4 matrix) - { - float l_mat[] = matrix.val; - float l_w = x*l_mat[Matrix4.M30]+y*l_mat[Matrix4.M31]+z*l_mat[Matrix4.M32]+l_mat[Matrix4.M33]; - return this.set((x*l_mat[Matrix4.M00]+y*l_mat[Matrix4.M01]+z*l_mat[Matrix4.M02]+l_mat[Matrix4.M03])/l_w, - (x*l_mat[Matrix4.M10]+y*l_mat[Matrix4.M11]+z*l_mat[Matrix4.M12]+l_mat[Matrix4.M13])/l_w, - (x*l_mat[Matrix4.M20]+y*l_mat[Matrix4.M21]+z*l_mat[Matrix4.M22]+l_mat[Matrix4.M23])/l_w); - } - - /** - * Multiplies this vector by the first three columns of the - * matrix, essentially only applying rotation and scaling. - * - * @param matrix The matrix - * @return This vector for chaining - */ - public Vector3 rot(Matrix4 matrix) - { - float l_mat[] = matrix.val; - return this.set(x*l_mat[Matrix4.M00]+y*l_mat[Matrix4.M01]+z*l_mat[Matrix4.M02], - x*l_mat[Matrix4.M10]+y*l_mat[Matrix4.M11]+z*l_mat[Matrix4.M12], - x*l_mat[Matrix4.M20]+y*l_mat[Matrix4.M21]+z*l_mat[Matrix4.M22]); - } - - /** - * @return Wether this vector is a unit length vector - */ - public boolean isUnit() - { - return this.len()==1; - } - - /** - * @return Wether this vector is a zero vector - */ - public boolean isZero() - { - return x==0 && y==0 && z==0; - } - - /** - * Linearly interpolates between this vector and the - * target vector by alpha which is in the range [0,1]. The result - * is stored in this vector. - * - * @param target The target vector - * @param alpha The interpolation coefficient - * @return This vector for chaining. - */ - public Vector3 lerp( Vector3 target, float alpha ) - { - Vector3 r = this.mul( 1.0f - alpha ); - r.add( target.tmp().mul( alpha ) ); - return r; - } - - /** - * Spherically interpolates between this vector and the - * target vector by alpha which is in the range [0,1]. The result - * is stored in this vector. - * - * @param target The target vector - * @param alpha The interpolation coefficient - * @return This vector for chaining. - */ - public Vector3 slerp( Vector3 target, float alpha ) - { - float dot = dot( target ); - if( dot > 0.99995 || dot < 0.9995 ) - { - this.add(target.tmp().sub(this).mul(alpha)); - this.nor(); - return this; - } - - if( dot > 1 ) - dot = 1; - if( dot < -1 ) - dot = -1; - - float theta0 = (float)Math.acos(dot); - float theta = theta0 * alpha; - Vector3 v2 = target.tmp().sub( x * dot, y * dot, z * dot ); - v2.nor(); - return this.mul((float)Math.cos(theta)).add( v2.mul((float)Math.sin(theta) ) ).nor(); - } - - /** - * {@inheritDoc} - */ - public String toString() - { - return String.format( "%.4f", x ) + ", " + String.format( "%.4f", y ) + ", " + String.format( "%.4f", z ); - } - - /** - * Returns the dot product between this and the given - * vector. - * - * @param x The x-component of the other vector - * @param y The y-component of the other vector - * @param z The z-component of the other vector - * @return The dot product - */ - public float dot(float x, float y, float z) { + public float z; + + private static Vector3 tmp = new Vector3(); + private static Vector3 tmp2 = new Vector3(); + private static Vector3 tmp3 = new Vector3(); + + /** + * Constructs a vector at (0,0,0) + */ + public Vector3 () { + } + + /** + * Creates a vector with the given components + * + * @param x The x-component + * @param y The y-component + * @param z The z-component + */ + public Vector3 (float x, float y, float z) { + this.set(x, y, z); + } + + /** + * Creates a vector from the given vector + * + * @param vector The vector + */ + public Vector3 (Vector3 vector) { + this.set(vector); + } + + /** + * Creates a vector from the given array. The array must have at least 3 elements. + * + * @param values The array + */ + public Vector3 (float[] values) { + this.set(values[0], values[1], values[2]); + } + + /** + * Sets the vector to the given components + * + * @param x The x-component + * @param y The y-component + * @param z The z-component + * @return this vector for chaining + */ + public Vector3 set (float x, float y, float z) { + this.x = x; + this.y = y; + this.z = z; + return this; + } + + /** + * Sets the components of the given vector + * + * @param vector The vector + * @return This vector for chaining + */ + public Vector3 set (Vector3 vector) { + return this.set(vector.x, vector.y, vector.z); + } + + /** + * Sets the components from the array. The array must have at least 3 elements + * + * @param values The array + * @return this vector for chaining + */ + public Vector3 set (float[] values) { + return this.set(values[0], values[1], values[2]); + } + + /** + * @return a copy of this vector + */ + public Vector3 cpy () { + return new Vector3(this); + } + + /** + * NEVER EVER SAVE THIS REFERENCE! + * + * @return + */ + public Vector3 tmp () { + return tmp.set(this); + } + + /** + * NEVER EVER SAVE THIS REFERENCE! + * + * @return + */ + public Vector3 tmp2 () { + return tmp2.set(this); + } + + /** + * NEVER EVER SAVE THIS REFERENCE! + * + * @return + */ + Vector3 tmp3 () { + return tmp3.set(this); + } + + /** + * Adds the given vector to this vector + * + * @param vector The other vector + * @return This vector for chaining + */ + public Vector3 add (Vector3 vector) { + return this.add(vector.x, vector.y, vector.z); + } + + /** + * Adds the given vector to this component + * @param x The x-component of the other vector + * @param y The y-component of the other vector + * @param z The z-component of the other vector + * @return This vector for chaining. + */ + public Vector3 add (float x, float y, float z) { + return this.set(this.x + x, this.y + y, this.z + z); + } + + /** + * Adds the given value to all three components of the vector. + * + * @param values The value + * @return This vector for chaining + */ + public Vector3 add (float values) { + return this.set(this.x + values, this.y + values, this.z + values); + } + + /** + * Subtracts the given vector from this vector + * @param a_vec The other vector + * @return This vector for chaining + */ + public Vector3 sub (Vector3 a_vec) { + return this.sub(a_vec.x, a_vec.y, a_vec.z); + } + + /** + * Subtracts the other vector from this vector. + * + * @param x The x-component of the other vector + * @param y The y-component of the other vector + * @param z The z-component of the other vector + * @return This vector for chaining + */ + public Vector3 sub (float x, float y, float z) { + return this.set(this.x - x, this.y - y, this.z - z); + } + + /** + * Subtracts the given value from all components of this vector + * + * @param value The value + * @return This vector for chaining + */ + public Vector3 sub (float value) { + return this.set(this.x - value, this.y - value, this.z - value); + } + + /** + * Multiplies all components of this vector by the given value + * + * @param value The value + * @return This vector for chaining + */ + public Vector3 mul (float value) { + return this.set(this.x * value, this.y * value, this.z * value); + } + + /** + * Divides all components of this vector by the given value + * + * @param value The value + * @return This vector for chaining + */ + public Vector3 div (float value) { + float d = 1 / value; + return this.set(this.x * d, this.y * d, this.z * d); + } + + /** + * @return The euclidian length + */ + public float len () { + return (float)Math.sqrt(x * x + y * y + z * z); + } + + /** + * @return The squared euclidian length + */ + public float len2 () { + return x * x + y * y + z * z; + } + + /** + * @param vector The other vector + * @return Wether this and the other vector are equal + */ + public boolean idt (Vector3 vector) { + return x == vector.x && y == vector.y && z == vector.z; + } + + /** + * @param vector The other vector + * @return The euclidian distance between this and the other vector + */ + public float dst (Vector3 vector) { + float a = vector.x - x; + float b = vector.y - y; + float c = vector.z - z; + + a *= a; + b *= b; + c *= c; + + return (float)Math.sqrt(a + b + c); + } + + /** + * @param vector The other vector + * @return The squared euclidian distance between this and the other vector + */ + public float dist2 (Vector3 vector) { + float a = vector.x - x; + float b = vector.y - y; + float c = vector.z - z; + return a * a + b * b + c * c; + } + + /** + * Normalizes this vector to unit length + * + * @return This vector for chaining + */ + public Vector3 nor () { + if (x == 0 && y == 0 && z == 0) + return this; + else + return this.div(this.len()); + } + + /** + * @param vector The other vector + * @return The dot product between this and the other vector + */ + public float dot (Vector3 vector) { + return x * vector.x + y * vector.y + z * vector.z; + } + + /** + * Sets this vector to the cross product between it and the other vector. + * @param vector The other vector + * @return This vector for chaining + */ + public Vector3 crs (Vector3 vector) { + return this.set(y * vector.z - z * vector.y, z * vector.x - x * vector.z, x * vector.y - y * vector.x); + } + + /** + * Sets this vector to the cross product between it and the other vector. + * @param x The x-component of the other vector + * @param y The y-component of the other vector + * @param z The z-component of the other vector + * @return This vector for chaining + */ + public Vector3 crs (float x, float y, float z) { + return this.set(y * z - z * y, z * x - x * z, x * y - y * x); + } + + /** + * Multiplies the vector by the given matrix. + * @param matrix The matrix + * @return This vector for chaining + */ + public Vector3 mul (Matrix4 matrix) { + float l_mat[] = matrix.val; + return this.set(x * l_mat[Matrix4.M00] + y * l_mat[Matrix4.M01] + z * l_mat[Matrix4.M02] + l_mat[Matrix4.M03], x + * l_mat[Matrix4.M10] + y * l_mat[Matrix4.M11] + z * l_mat[Matrix4.M12] + l_mat[Matrix4.M13], x * l_mat[Matrix4.M20] + y + * l_mat[Matrix4.M21] + z * l_mat[Matrix4.M22] + l_mat[Matrix4.M23]); + } + + /** + * Multiplies this vector by the given matrix dividing by w. This is mostly used to project/unproject vectors via a perspective + * projection matrix. + * + * @param matrix The matrix. + * @return This vector for chaining + */ + public Vector3 prj (Matrix4 matrix) { + float l_mat[] = matrix.val; + float l_w = x * l_mat[Matrix4.M30] + y * l_mat[Matrix4.M31] + z * l_mat[Matrix4.M32] + l_mat[Matrix4.M33]; + return this.set((x * l_mat[Matrix4.M00] + y * l_mat[Matrix4.M01] + z * l_mat[Matrix4.M02] + l_mat[Matrix4.M03]) / l_w, (x + * l_mat[Matrix4.M10] + y * l_mat[Matrix4.M11] + z * l_mat[Matrix4.M12] + l_mat[Matrix4.M13]) + / l_w, (x * l_mat[Matrix4.M20] + y * l_mat[Matrix4.M21] + z * l_mat[Matrix4.M22] + l_mat[Matrix4.M23]) / l_w); + } + + /** + * Multiplies this vector by the first three columns of the matrix, essentially only applying rotation and scaling. + * + * @param matrix The matrix + * @return This vector for chaining + */ + public Vector3 rot (Matrix4 matrix) { + float l_mat[] = matrix.val; + return this.set(x * l_mat[Matrix4.M00] + y * l_mat[Matrix4.M01] + z * l_mat[Matrix4.M02], x * l_mat[Matrix4.M10] + y + * l_mat[Matrix4.M11] + z * l_mat[Matrix4.M12], x * l_mat[Matrix4.M20] + y * l_mat[Matrix4.M21] + z * l_mat[Matrix4.M22]); + } + + /** + * @return Wether this vector is a unit length vector + */ + public boolean isUnit () { + return this.len() == 1; + } + + /** + * @return Wether this vector is a zero vector + */ + public boolean isZero () { + return x == 0 && y == 0 && z == 0; + } + + /** + * Linearly interpolates between this vector and the target vector by alpha which is in the range [0,1]. The result is stored + * in this vector. + * + * @param target The target vector + * @param alpha The interpolation coefficient + * @return This vector for chaining. + */ + public Vector3 lerp (Vector3 target, float alpha) { + Vector3 r = this.mul(1.0f - alpha); + r.add(target.tmp().mul(alpha)); + return r; + } + + /** + * Spherically interpolates between this vector and the target vector by alpha which is in the range [0,1]. The result is + * stored in this vector. + * + * @param target The target vector + * @param alpha The interpolation coefficient + * @return This vector for chaining. + */ + public Vector3 slerp (Vector3 target, float alpha) { + float dot = dot(target); + if (dot > 0.99995 || dot < 0.9995) { + this.add(target.tmp().sub(this).mul(alpha)); + this.nor(); + return this; + } + + if (dot > 1) dot = 1; + if (dot < -1) dot = -1; + + float theta0 = (float)Math.acos(dot); + float theta = theta0 * alpha; + Vector3 v2 = target.tmp().sub(x * dot, y * dot, z * dot); + v2.nor(); + return this.mul((float)Math.cos(theta)).add(v2.mul((float)Math.sin(theta))).nor(); + } + + /** + * {@inheritDoc} + */ + public String toString () { + return String.format("%.4f", x) + ", " + String.format("%.4f", y) + ", " + String.format("%.4f", z); + } + + /** + * Returns the dot product between this and the given vector. + * + * @param x The x-component of the other vector + * @param y The y-component of the other vector + * @param z The z-component of the other vector + * @return The dot product + */ + public float dot (float x, float y, float z) { return this.x * x + this.y * y + this.z * z; } @@ -485,17 +426,17 @@ public final class Vector3 * @param point The other point * @return The squared distance */ - public float dst2(Vector3 point) { + public float dst2 (Vector3 point) { - float a = point.x-x; - float b = point.y-y; - float c = point.z-z; - - a *= a; - b *= b; - c *= c; - - return a + b + c; + float a = point.x - x; + float b = point.y - y; + float c = point.z - z; + + a *= a; + b *= b; + c *= c; + + return a + b + c; } /** @@ -506,30 +447,28 @@ public final class Vector3 * @param z The z-component of the other point * @return The squared distance */ - public float dst2(float x, float y, float z) { - float a = x-this.x; - float b = y-this.y; - float c = z-this.z; - - a *= a; - b *= b; - c *= c; - - return a + b + c; + public float dst2 (float x, float y, float z) { + float a = x - this.x; + float b = y - this.y; + float c = z - this.z; + + a *= a; + b *= b; + c *= c; + + return a + b + c; } - public float dst(float x, float y, float z) - { - return (float)Math.sqrt( dst2( x, y, z )); + public float dst (float x, float y, float z) { + return (float)Math.sqrt(dst2(x, y, z)); } - + /** * {@inheritDoc} */ - @Override - public int hashCode() { + @Override public int hashCode () { final int prime = 31; - int result = 1; + int result = 1; result = prime * result + Float.floatToIntBits(x); result = prime * result + Float.floatToIntBits(y); result = prime * result + Float.floatToIntBits(z); @@ -539,21 +478,14 @@ public final class Vector3 /** * {@inheritDoc} */ - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Vector3 other = (Vector3) obj; - if (Float.floatToIntBits(x) != Float.floatToIntBits(other.x)) - return false; - if (Float.floatToIntBits(y) != Float.floatToIntBits(other.y)) - return false; - if (Float.floatToIntBits(z) != Float.floatToIntBits(other.z)) - return false; + @Override public boolean equals (Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; + Vector3 other = (Vector3)obj; + if (Float.floatToIntBits(x) != Float.floatToIntBits(other.x)) return false; + if (Float.floatToIntBits(y) != Float.floatToIntBits(other.y)) return false; + if (Float.floatToIntBits(z) != Float.floatToIntBits(other.z)) return false; return true; } @@ -564,8 +496,7 @@ public final class Vector3 * @param scalarY * @param scalarZ */ - public Vector3 scale(float scalarX, float scalarY, float scalarZ) - { + public Vector3 scale (float scalarX, float scalarY, float scalarZ) { x *= scalarX; y *= scalarY; z *= scalarZ; diff --git a/gdx/src/com/badlogic/gdx/math/WindowedMean.java b/gdx/src/com/badlogic/gdx/math/WindowedMean.java index d8b0bf019..677e71678 100644 --- a/gdx/src/com/badlogic/gdx/math/WindowedMean.java +++ b/gdx/src/com/badlogic/gdx/math/WindowedMean.java @@ -1,152 +1,119 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math; /** - * A simple class keeping track - * of the mean of a stream of values - * within a certain window. the WindowedMean - * will only return a value in case enough - * data has been sampled. After enough - * data has been sampled the oldest sample - * will be replaced by the newest in case - * a new sample is added. + * A simple class keeping track of the mean of a stream of values within a certain window. the WindowedMean will only return a + * value in case enough data has been sampled. After enough data has been sampled the oldest sample will be replaced by the newest + * in case a new sample is added. * * @author badlogicgames@gmail.com - * + * */ -public final class WindowedMean -{ +public final class WindowedMean { float values[]; int added_values = 0; - int last_value; + int last_value; float mean = 0; boolean dirty = true; - + /** - * constructor, window_size specifies - * the number of samples we will continuously - * get the mean and variance from. the - * class will only return meaning full values - * if at least window_size values have been - * added. + * constructor, window_size specifies the number of samples we will continuously get the mean and variance from. the class will + * only return meaning full values if at least window_size values have been added. * * @param window_size size of the sample window */ - public WindowedMean( int window_size ) - { - values = new float[window_size]; + public WindowedMean (int window_size) { + values = new float[window_size]; } - + /** * @return wheter the value returned will be meaningfull */ - public boolean hasEnoughData() - { + public boolean hasEnoughData () { return added_values >= values.length; } - + /** - * clears this WindowedMean. The class will - * only return meaningfull values after enough - * data has been added again. + * clears this WindowedMean. The class will only return meaningfull values after enough data has been added again. */ - public void clear( ) - { + public void clear () { added_values = 0; last_value = 0; - for( int i = 0; i < values.length; i++ ) + for (int i = 0; i < values.length; i++) values[i] = 0; dirty = true; } - + /** - * adds a new sample to this mean. in case the - * window is full the oldest value will be replaced - * by this new value. + * adds a new sample to this mean. in case the window is full the oldest value will be replaced by this new value. * * @param value The value to add */ - public void addValue( float value ) - { + public void addValue (float value) { added_values++; values[last_value++] = value; - if( last_value > values.length - 1 ) - last_value = 0; + if (last_value > values.length - 1) last_value = 0; dirty = true; } - + /** - * returns the mean of the samples added - * to this instance. only returns meaningfull - * results when at least window_size samples - * as specified in the constructor have been - * added. + * returns the mean of the samples added to this instance. only returns meaningfull results when at least window_size samples + * as specified in the constructor have been added. * @return the mean */ - public float getMean( ) - { - if( hasEnoughData() ) - { - if( dirty == true ) - { - float mean = 0; - for( int i = 0; i < values.length; i++ ) + public float getMean () { + if (hasEnoughData()) { + if (dirty == true) { + float mean = 0; + for (int i = 0; i < values.length; i++) mean += values[i]; - - this.mean = mean / values.length; + + this.mean = mean / values.length; dirty = false; } return this.mean; - } - else + } else return 0; - } - + } + /** * @return the oldest value in the window */ - public float getOldest( ) - { - return last_value == values.length - 1 ? values[0]: values[last_value+1]; + public float getOldest () { + return last_value == values.length - 1 ? values[0] : values[last_value + 1]; } /** * @return the value last added */ - public float getLatest() - { - return values[last_value-1 == -1?values.length-1:last_value-1]; + public float getLatest () { + return values[last_value - 1 == -1 ? values.length - 1 : last_value - 1]; } /** * @return The standard deviation */ - public float standardDeviation() - { - if( !hasEnoughData() ) - return 0; - + public float standardDeviation () { + if (!hasEnoughData()) return 0; + float mean = getMean(); float sum = 0; - for( int i = 0; i < values.length; i++ ) - { + for (int i = 0; i < values.length; i++) { sum += (values[i] - mean) * (values[i] - mean); } - - return (float)Math.sqrt( sum / values.length ); + + return (float)Math.sqrt(sum / values.length); } } diff --git a/gdx/src/com/badlogic/gdx/math/collision/BoundingBox.java b/gdx/src/com/badlogic/gdx/math/collision/BoundingBox.java index 7649216bd..00ee3e8c8 100644 --- a/gdx/src/com/badlogic/gdx/math/collision/BoundingBox.java +++ b/gdx/src/com/badlogic/gdx/math/collision/BoundingBox.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math.collision; import java.util.List; @@ -21,366 +19,293 @@ import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; /** - * Encapsulates an axis aligned bounding box represented by a - * minimum and a maximum Vector. Additionally you can query for - * the bounding box's center, dimensions and corner points. + * Encapsulates an axis aligned bounding box represented by a minimum and a maximum Vector. Additionally you can query for the + * bounding box's center, dimensions and corner points. * * @author badlogicgames@gmail.com - * + * */ -public final class BoundingBox -{ +public final class BoundingBox { private static final long serialVersionUID = -1286036817192127343L; final Vector3 crn[] = new Vector3[8]; - public final Vector3 min = new Vector3(); - public final Vector3 max = new Vector3(); - final Vector3 cnt = new Vector3(); - final Vector3 dim = new Vector3(); - boolean crn_dirty = true; - - - /** - * @return the center of the bounding box - */ - public Vector3 getCenter() - { - return cnt; - } - - protected void updateCorners( ) - { - if( !crn_dirty ) - return; - - crn[0].set(min.x,min.y,min.z); - crn[1].set(max.x,min.y,min.z); - crn[2].set(max.x,max.y,min.z); - crn[3].set(min.x,max.y,min.z); - crn[4].set(min.x,min.y,max.z); - crn[5].set(max.x,min.y,max.z); - crn[6].set(max.x,max.y,max.z); - crn[7].set(min.x,max.y,max.z); - crn_dirty = false; - } + public final Vector3 min = new Vector3(); + public final Vector3 max = new Vector3(); + final Vector3 cnt = new Vector3(); + final Vector3 dim = new Vector3(); + boolean crn_dirty = true; - /** - * @return the corners of this bounding box - */ - public Vector3[] getCorners() - { - updateCorners(); - return crn; - } - - /** - * @return The dimensions of this bounding box on all three axis - */ - public Vector3 getDimensions( ) - { - return dim; - } + /** + * @return the center of the bounding box + */ + public Vector3 getCenter () { + return cnt; + } - /** - * @return The minimum vector - */ - public Vector3 getMin() - { - return min; - } + protected void updateCorners () { + if (!crn_dirty) return; - /** - * @return The maximum vector - */ - public synchronized Vector3 getMax() - { - return max; - } + crn[0].set(min.x, min.y, min.z); + crn[1].set(max.x, min.y, min.z); + crn[2].set(max.x, max.y, min.z); + crn[3].set(min.x, max.y, min.z); + crn[4].set(min.x, min.y, max.z); + crn[5].set(max.x, min.y, max.z); + crn[6].set(max.x, max.y, max.z); + crn[7].set(min.x, max.y, max.z); + crn_dirty = false; + } - /** - * Constructs a new bounding box with the minimum - * and maximum vector set to zeros. - */ - public BoundingBox() - { - crn_dirty = true; - for(int l_idx=0;l_idx<8;l_idx++) - crn[l_idx]=new Vector3(); - clr(); - } + /** + * @return the corners of this bounding box + */ + public Vector3[] getCorners () { + updateCorners(); + return crn; + } - /** - * Constructs a new bounding box from the given - * bounding box. - * - * @param bounds The bounding box to copy - */ - public BoundingBox(BoundingBox bounds) - { - crn_dirty = true; - for(int l_idx=0;l_idx<8;l_idx++) - crn[l_idx]=new Vector3(); - this.set(bounds); - } + /** + * @return The dimensions of this bounding box on all three axis + */ + public Vector3 getDimensions () { + return dim; + } - /** - * Constructs the new bounding box using the given - * minimum and maximum vector. - * - * @param minimum The minimum vector - * @param maximum The maximum vector - */ - public BoundingBox(Vector3 minimum, Vector3 maximum) - { - crn_dirty = true; - for(int l_idx=0;l_idx<8;l_idx++) - crn[l_idx]=new Vector3(); - this.set(minimum,maximum); - } + /** + * @return The minimum vector + */ + public Vector3 getMin () { + return min; + } - /** - * Sets the given bounding box. - * - * @param bounds The bounds. - * @return This bounding box for chaining. - */ - public BoundingBox set(BoundingBox bounds) - { - crn_dirty = true; - return this.set(bounds.min,bounds.max); - } + /** + * @return The maximum vector + */ + public synchronized Vector3 getMax () { + return max; + } - /** - * Sets the given minimum and maximum vector. - * - * @param minimum The minimum vector - * @param maximum The maximum vector - * @return This bounding box for chaining. - */ - public BoundingBox set(Vector3 minimum, Vector3 maximum) - { - min.set(minimum.xmaximum.x?minimum.x:maximum.x, - minimum.y>maximum.y?minimum.y:maximum.y, - minimum.z>maximum.z?minimum.z:maximum.z); - cnt.set(min).add(max).mul(0.5f); - dim.set(max).sub( min ); - crn_dirty = true; - return this; - } - - /** - * Sets the bounding box minimum and maximum vector - * from the given points. - * - * @param points The points. - * @return This bounding box for chaining. - */ - public BoundingBox set(Vector3[] points) - { - this.inf(); - for(Vector3 l_point: points) - this.ext(l_point); - crn_dirty = true; - return this; - } + /** + * Constructs a new bounding box with the minimum and maximum vector set to zeros. + */ + public BoundingBox () { + crn_dirty = true; + for (int l_idx = 0; l_idx < 8; l_idx++) + crn[l_idx] = new Vector3(); + clr(); + } - /** - * Sets the bounding box minimum and maximum vector - * from the given points. - * - * @param points The points. - * @return This bounding box for chaining. - */ - public BoundingBox set(List points) - { - this.inf(); - for(Vector3 l_point: points) - this.ext(l_point); - crn_dirty = true; - return this; - } + /** + * Constructs a new bounding box from the given bounding box. + * + * @param bounds The bounding box to copy + */ + public BoundingBox (BoundingBox bounds) { + crn_dirty = true; + for (int l_idx = 0; l_idx < 8; l_idx++) + crn[l_idx] = new Vector3(); + this.set(bounds); + } - /** - * Sets the minimum and maximum vector to positive and - * negative infinity. - * - * @return This bounding box for chaining. - */ - public BoundingBox inf() - { - min.set(Float.POSITIVE_INFINITY,Float.POSITIVE_INFINITY,Float.POSITIVE_INFINITY); - max.set(Float.NEGATIVE_INFINITY,Float.NEGATIVE_INFINITY,Float.NEGATIVE_INFINITY); - cnt.set(0,0,0); - dim.set(0,0,0); - crn_dirty = true; - return this; - } + /** + * Constructs the new bounding box using the given minimum and maximum vector. + * + * @param minimum The minimum vector + * @param maximum The maximum vector + */ + public BoundingBox (Vector3 minimum, Vector3 maximum) { + crn_dirty = true; + for (int l_idx = 0; l_idx < 8; l_idx++) + crn[l_idx] = new Vector3(); + this.set(minimum, maximum); + } - /** - * Extends the bounding box to incorporate the given - * {@link Vector3}. - * - * @param point The vector - * @return This bounding box for chaining. - */ - public BoundingBox ext(Vector3 point) - { - crn_dirty = true; - return this.set( - min.set(min(min.x,point.x), - min(min.y,point.y), - min(min.z,point.z)), - max.set(Math.max(max.x,point.x), - Math.max(max.y,point.y), - Math.max(max.z,point.z)) - ); - } + /** + * Sets the given bounding box. + * + * @param bounds The bounds. + * @return This bounding box for chaining. + */ + public BoundingBox set (BoundingBox bounds) { + crn_dirty = true; + return this.set(bounds.min, bounds.max); + } - /** - * Sets the minimum and maximum vector to zeros - * - * @return This bounding box for chaining. - */ - public BoundingBox clr() - { - crn_dirty = true; - return this.set(min.set(0,0,0),max.set(0,0,0)); - } + /** + * Sets the given minimum and maximum vector. + * + * @param minimum The minimum vector + * @param maximum The maximum vector + * @return This bounding box for chaining. + */ + public BoundingBox set (Vector3 minimum, Vector3 maximum) { + min.set(minimum.x < maximum.x ? minimum.x : maximum.x, minimum.y < maximum.y ? minimum.y : maximum.y, + minimum.z < maximum.z ? minimum.z : maximum.z); + max.set(minimum.x > maximum.x ? minimum.x : maximum.x, minimum.y > maximum.y ? minimum.y : maximum.y, + minimum.z > maximum.z ? minimum.z : maximum.z); + cnt.set(min).add(max).mul(0.5f); + dim.set(max).sub(min); + crn_dirty = true; + return this; + } - /** - * Returns wheter this bounding box is valid. This means - * that min != max and min < max. - * - * @return True in case the bounding box is valid, false otherwise - */ - public boolean isValid() - { - return !(min.x==max.x && min.y==max.y && min.z==max.z); - } + /** + * Sets the bounding box minimum and maximum vector from the given points. + * + * @param points The points. + * @return This bounding box for chaining. + */ + public BoundingBox set (Vector3[] points) { + this.inf(); + for (Vector3 l_point : points) + this.ext(l_point); + crn_dirty = true; + return this; + } - /** - * Extends this bounding box by the given bounding box. - * - * @param a_bounds The bounding box - * @return This bounding box for chaining. - */ - public BoundingBox ext(BoundingBox a_bounds) - { - crn_dirty = true; - return this.set( - min.set(min(min.x,a_bounds.min.x), - min(min.y,a_bounds.min.y), - min(min.z,a_bounds.min.z)), - max.set(max(max.x,a_bounds.max.x), - max(max.y,a_bounds.max.y), - max(max.z,a_bounds.max.z)) - ); - } + /** + * Sets the bounding box minimum and maximum vector from the given points. + * + * @param points The points. + * @return This bounding box for chaining. + */ + public BoundingBox set (List points) { + this.inf(); + for (Vector3 l_point : points) + this.ext(l_point); + crn_dirty = true; + return this; + } - /** - * Multiplies the bounding box by the given matrix. This - * is achieved by multiplying the 8 corner points and then - * calculating the minimum and maximum vectors from the - * transformed points. - * - * @param matrix The matrix - * @return This bounding box for chaining. - */ - public BoundingBox mul(Matrix4 matrix) - { - updateCorners(); - this.inf(); - for(Vector3 l_pnt: crn) - { - l_pnt.mul(matrix); - min.set(min(min.x,l_pnt.x), - min(min.y,l_pnt.y), - min(min.z,l_pnt.z)); - max.set(max(max.x,l_pnt.x), - max(max.y,l_pnt.y), - max(max.z,l_pnt.z)); - } - crn_dirty = true; - return this.set(min,max); - } + /** + * Sets the minimum and maximum vector to positive and negative infinity. + * + * @return This bounding box for chaining. + */ + public BoundingBox inf () { + min.set(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY); + max.set(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY); + cnt.set(0, 0, 0); + dim.set(0, 0, 0); + crn_dirty = true; + return this; + } + + /** + * Extends the bounding box to incorporate the given {@link Vector3}. + * + * @param point The vector + * @return This bounding box for chaining. + */ + public BoundingBox ext (Vector3 point) { + crn_dirty = true; + return this.set(min.set(min(min.x, point.x), min(min.y, point.y), min(min.z, point.z)), + max.set(Math.max(max.x, point.x), Math.max(max.y, point.y), Math.max(max.z, point.z))); + } + + /** + * Sets the minimum and maximum vector to zeros + * + * @return This bounding box for chaining. + */ + public BoundingBox clr () { + crn_dirty = true; + return this.set(min.set(0, 0, 0), max.set(0, 0, 0)); + } + + /** + * Returns wheter this bounding box is valid. This means that min != max and min < max. + * + * @return True in case the bounding box is valid, false otherwise + */ + public boolean isValid () { + return !(min.x == max.x && min.y == max.y && min.z == max.z); + } + + /** + * Extends this bounding box by the given bounding box. + * + * @param a_bounds The bounding box + * @return This bounding box for chaining. + */ + public BoundingBox ext (BoundingBox a_bounds) { + crn_dirty = true; + return this.set(min.set(min(min.x, a_bounds.min.x), min(min.y, a_bounds.min.y), min(min.z, a_bounds.min.z)), + max.set(max(max.x, a_bounds.max.x), max(max.y, a_bounds.max.y), max(max.z, a_bounds.max.z))); + } + + /** + * Multiplies the bounding box by the given matrix. This is achieved by multiplying the 8 corner points and then calculating + * the minimum and maximum vectors from the transformed points. + * + * @param matrix The matrix + * @return This bounding box for chaining. + */ + public BoundingBox mul (Matrix4 matrix) { + updateCorners(); + this.inf(); + for (Vector3 l_pnt : crn) { + l_pnt.mul(matrix); + min.set(min(min.x, l_pnt.x), min(min.y, l_pnt.y), min(min.z, l_pnt.z)); + max.set(max(max.x, l_pnt.x), max(max.y, l_pnt.y), max(max.z, l_pnt.z)); + } + crn_dirty = true; + return this.set(min, max); + } - /** - * Returns wheter the given bounding box is contained - * in this bounding box. - * @param bounds The bounding box - * @return Wheter the given bounding box is contained - */ - public boolean contains(BoundingBox bounds) - { - if(!isValid()) return true; - if(min.x>bounds.max.x) return false; - if(min.y>bounds.max.y) return false; - if(min.z>bounds.max.z) return false; - if(max.x v.x ) - return false; - if( max.x < v.x ) - return false; - if( min.y > v.y ) - return false; - if( max.y < v.y ) - return false; - if( min.z > v.z ) - return false; - if( max.z < v.z ) - return false; - - return true; - } + /** + * Returns wheter the given bounding box is contained in this bounding box. + * @param bounds The bounding box + * @return Wheter the given bounding box is contained + */ + public boolean contains (BoundingBox bounds) { + if (!isValid()) return true; + if (min.x > bounds.max.x) return false; + if (min.y > bounds.max.y) return false; + if (min.z > bounds.max.z) return false; + if (max.x < bounds.min.x) return false; + if (max.y < bounds.min.y) return false; + if (max.z < bounds.min.z) return false; + return true; + } - public String toString() - { - return "["+min+"|"+max+"]"; - } + /** + * Returns wheter the given vector is contained in this bounding box. + * @param v The vector + * @return Wheter the vector is contained or not. + */ + public boolean contains (Vector3 v) { + if (min.x > v.x) return false; + if (max.x < v.x) return false; + if (min.y > v.y) return false; + if (max.y < v.y) return false; + if (min.z > v.z) return false; + if (max.z < v.z) return false; - /** - * Extends the bounding box by the given vector. - * - * @param x The x-coordinate - * @param y The y-coordinate - * @param z The z-coordinate - * @return This bounding box for chaining. - */ - public BoundingBox ext(float x, float y, float z) - { + return true; + } + + public String toString () { + return "[" + min + "|" + max + "]"; + } + + /** + * Extends the bounding box by the given vector. + * + * @param x The x-coordinate + * @param y The y-coordinate + * @param z The z-coordinate + * @return This bounding box for chaining. + */ + public BoundingBox ext (float x, float y, float z) { crn_dirty = true; - return this.set( - min.set(min(min.x,x), - min(min.y,y), - min(min.z,z)), - max.set(max(max.x,x), - max(max.y,y), - max(max.z,z)) - ); + return this.set(min.set(min(min.x, x), min(min.y, y), min(min.z, z)), max.set(max(max.x, x), max(max.y, y), max(max.z, z))); } - - static float min( float a, float b ) - { - return a > b? b: a; + + static float min (float a, float b) { + return a > b ? b : a; } - - static float max( float a, float b ) - { - return a > b? a: b; + + static float max (float a, float b) { + return a > b ? a : b; } } diff --git a/gdx/src/com/badlogic/gdx/math/collision/Ray.java b/gdx/src/com/badlogic/gdx/math/collision/Ray.java index afd29c1a0..104f3da89 100644 --- a/gdx/src/com/badlogic/gdx/math/collision/Ray.java +++ b/gdx/src/com/badlogic/gdx/math/collision/Ray.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math.collision; import com.badlogic.gdx.math.Matrix4; @@ -22,91 +20,78 @@ import com.badlogic.gdx.math.Vector3; * Encapsulates a ray having a starting position and a unit length direction. * * @author badlogicgames@gmail.com - * + * */ -public final class Ray -{ +public final class Ray { public final Vector3 origin = new Vector3(); - public final Vector3 direction = new Vector3(); - + public final Vector3 direction = new Vector3(); + /** - * Constructor, sets the starting position of the ray - * and the direction. + * Constructor, sets the starting position of the ray and the direction. * * @param origin The starting position * @param direction The direction */ - public Ray( Vector3 origin, Vector3 direction ) - { + public Ray (Vector3 origin, Vector3 direction) { this.origin.set(origin); this.direction.set(direction).nor(); } - + /** * @return a copy of this ray. */ - public Ray cpy() - { - return new Ray( this.origin, this.direction ); + public Ray cpy () { + return new Ray(this.origin, this.direction); } - + /** - * Returns and endpoint given the distance. This is - * calculated as startpoint + distance * direction. + * Returns and endpoint given the distance. This is calculated as startpoint + distance * direction. * * @param distance The distance from the end point to the start point. * @return The end point */ - public Vector3 getEndPoint( float distance ) - { - return new Vector3( origin ).add( direction.tmp().mul( distance ) ); + public Vector3 getEndPoint (float distance) { + return new Vector3(origin).add(direction.tmp().mul(distance)); } - - static Vector3 tmp = new Vector3( ); - + + static Vector3 tmp = new Vector3(); + /** - * Multiplies the ray by the given matrix. Use - * this to transform a ray into another coordinate - * system. + * Multiplies the ray by the given matrix. Use this to transform a ray into another coordinate system. * - * @param matrix The matrix + * @param matrix The matrix * @return This ray for chaining. */ - public Ray mul( Matrix4 matrix ) - { - tmp.set( origin ).add( direction ); - tmp.mul( matrix ); - origin.mul( matrix ); - direction.set( tmp.sub( origin ) ); + public Ray mul (Matrix4 matrix) { + tmp.set(origin).add(direction); + tmp.mul(matrix); + origin.mul(matrix); + direction.set(tmp.sub(origin)); return this; } - + /** * {@inheritDoc} */ - public String toString() - { + public String toString () { return "ray [" + origin + ":" + direction + "]"; } /** - * Sets the starting position and the direction - * of this ray. + * Sets the starting position and the direction of this ray. * * @param origin The starting position * @param direction The direction * @return this ray for chaining */ - public Ray set( Vector3 origin, Vector3 direction ) - { + public Ray set (Vector3 origin, Vector3 direction) { this.origin.set(origin); this.direction.set(direction); return this; } - + /** - * Sets this ray from the given starting position - * and direction. + * Sets this ray from the given starting position and direction. * * @param x The x-component of the starting position * @param y The y-component of the starting position @@ -116,20 +101,19 @@ public final class Ray * @param dz The z-component of the direction * @return this ray for chaining */ - public Ray set( float x, float y, float z, float dx, float dy, float dz ) - { - this.origin.set( x, y, z ); - this.direction.set( dx, dy, dz ); + public Ray set (float x, float y, float z, float dx, float dy, float dz) { + this.origin.set(x, y, z); + this.direction.set(dx, dy, dz); return this; } - + /** * Sets the starting position and direction from the given ray * * @param ray The ray * @return This ray for chaining */ - public Ray set(Ray ray) { + public Ray set (Ray ray) { this.origin.set(ray.origin); this.direction.set(ray.direction); diff --git a/gdx/src/com/badlogic/gdx/math/collision/Segment.java b/gdx/src/com/badlogic/gdx/math/collision/Segment.java index 1e1e63f9b..eb7b75717 100644 --- a/gdx/src/com/badlogic/gdx/math/collision/Segment.java +++ b/gdx/src/com/badlogic/gdx/math/collision/Segment.java @@ -1,46 +1,40 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math.collision; import com.badlogic.gdx.math.Vector3; /** - * A Segment is a line in 3-space having a staring - * and an ending position. + * A Segment is a line in 3-space having a staring and an ending position. * * @author mzechner - * + * */ -public class Segment -{ +public class Segment { /** the starting position **/ - public final Vector3 a = new Vector3( ); - + public final Vector3 a = new Vector3(); + /** the ending position **/ - public final Vector3 b = new Vector3( ); - + public final Vector3 b = new Vector3(); + /** - * Constructs a new Segment from the two points - * given. + * Constructs a new Segment from the two points given. * * @param a the first point * @param b the second point */ - public Segment( Vector3 a, Vector3 b ) - { + public Segment (Vector3 a, Vector3 b) { this.a.set(a); this.b.set(b); } @@ -54,9 +48,8 @@ public class Segment * @param bY the y-coordinate of the second point * @param bZ the z-coordinate of the second point */ - public Segment( float aX, float aY, float aZ, float bX, float bY, float bZ ) - { - this.a.set( aX, aY, aZ ); - this.b.set( bX, bY, bZ ); + public Segment (float aX, float aY, float aZ, float bX, float bY, float bZ) { + this.a.set(aX, aY, aZ); + this.b.set(bX, bY, bZ); } } diff --git a/gdx/src/com/badlogic/gdx/math/collision/Sphere.java b/gdx/src/com/badlogic/gdx/math/collision/Sphere.java index 318a12805..8cf6c44b4 100644 --- a/gdx/src/com/badlogic/gdx/math/collision/Sphere.java +++ b/gdx/src/com/badlogic/gdx/math/collision/Sphere.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math.collision; import com.badlogic.gdx.math.Vector3; @@ -21,23 +19,21 @@ import com.badlogic.gdx.math.Vector3; * Encapsulates a 3D sphere with a center and a radius * * @author badlogicgames@gmail.com - * + * */ -public final class Sphere -{ +public final class Sphere { /** the radius of the sphere **/ public float radius; /** the center of the sphere **/ public final Vector3 center; - + /** * Constructs a sphere with the given center and radius * @param center The center * @param radius The radius */ - public Sphere( Vector3 center, float radius ) - { - this.center = new Vector3( center ); - this.radius = radius; + public Sphere (Vector3 center, float radius) { + this.center = new Vector3(center); + this.radius = radius; } } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/Body.java b/gdx/src/com/badlogic/gdx/physics/box2d/Body.java index a1c48bb8b..782b2e161 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/Body.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/Body.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; import java.util.ArrayList; @@ -23,296 +21,277 @@ import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; /** * A rigid body. These are created via World.CreateBody. * @author mzechner - * + * */ -public class Body -{ +public class Body { /** the address of the body **/ protected final long addr; - + /** temporary float array **/ private final float[] tmp = new float[4]; - + /** World **/ private final World world; - + /** Fixtures of this body **/ private ArrayList fixtures = new ArrayList(2); - + /** Joints of this body **/ - protected ArrayList joints = new ArrayList(2); - + protected ArrayList joints = new ArrayList(2); + /** user data **/ private Object userData; - + /** * Constructs a new body with the given address * @param world the world * @param addr the address */ - protected Body( World world, long addr ) - { + protected Body (World world, long addr) { this.world = world; this.addr = addr; } - - /** - * Creates a fixture and attach it to this body. Use this function if you need - * to set some fixture parameters, like friction. Otherwise you can create the - * fixture directly from a shape. - * If the density is non-zero, this function automatically updates the mass of the body. - * Contacts are not created until the next time step. - * @param def the fixture definition. - * @warning This function is locked during callbacks. - */ - public Fixture createFixture(FixtureDef def) - { - Fixture fixture = new Fixture( this, jniCreateFixture(addr, def.shape.addr, def.friction, def.restitution, def.density, def.isSensor, def.filter.categoryBits, def.filter.maskBits, def.filter.groupIndex) ); - this.world.fixtures.put( fixture.addr, fixture ); - this.fixtures.add( fixture ); + + /** + * Creates a fixture and attach it to this body. Use this function if you need to set some fixture parameters, like friction. + * Otherwise you can create the fixture directly from a shape. If the density is non-zero, this function automatically updates + * the mass of the body. Contacts are not created until the next time step. + * @param def the fixture definition. + * @warning This function is locked during callbacks. + */ + public Fixture createFixture (FixtureDef def) { + Fixture fixture = new Fixture(this, jniCreateFixture(addr, def.shape.addr, def.friction, def.restitution, def.density, + def.isSensor, def.filter.categoryBits, def.filter.maskBits, def.filter.groupIndex)); + this.world.fixtures.put(fixture.addr, fixture); + this.fixtures.add(fixture); return fixture; } - - private native long jniCreateFixture( long addr, long shapeAddr, float friction, float restitution, float density, boolean isSensor, short filterCategoryBits, short filterMaskBits, short filterGroupIndex ); - + + private native long jniCreateFixture (long addr, long shapeAddr, float friction, float restitution, float density, + boolean isSensor, short filterCategoryBits, short filterMaskBits, short filterGroupIndex); + /** - * Creates a fixture from a shape and attach it to this body. - * This is a convenience function. Use b2FixtureDef if you need to set parameters - * like friction, restitution, user data, or filtering. - * If the density is non-zero, this function automatically updates the mass of the body. + * Creates a fixture from a shape and attach it to this body. This is a convenience function. Use b2FixtureDef if you need to + * set parameters like friction, restitution, user data, or filtering. If the density is non-zero, this function automatically + * updates the mass of the body. * @param shape the shape to be cloned. * @param density the shape density (set to zero for static bodies). - * @warning This function is locked during callbacks. + * @warning This function is locked during callbacks. */ - public Fixture createFixture(Shape shape, float density) - { - Fixture fixture = new Fixture( this, jniCreateFixture(addr, shape.addr, density)); - this.world.fixtures.put( fixture.addr, fixture ); - this.fixtures.add( fixture ); + public Fixture createFixture (Shape shape, float density) { + Fixture fixture = new Fixture(this, jniCreateFixture(addr, shape.addr, density)); + this.world.fixtures.put(fixture.addr, fixture); + this.fixtures.add(fixture); return fixture; } - - private native long jniCreateFixture( long addr, long shapeAddr, float density ); - + + private native long jniCreateFixture (long addr, long shapeAddr, float density); + /** - * Destroy a fixture. This removes the fixture from the broad-phase and - * destroys all contacts associated with this fixture. This will - * automatically adjust the mass of the body if the body is dynamic and the - * fixture has positive density. - * All fixtures attached to a body are implicitly destroyed when the body is destroyed. + * Destroy a fixture. This removes the fixture from the broad-phase and destroys all contacts associated with this fixture. + * This will automatically adjust the mass of the body if the body is dynamic and the fixture has positive density. All + * fixtures attached to a body are implicitly destroyed when the body is destroyed. * @param fixture the fixture to be removed. - * @warning This function is locked during callbacks. + * @warning This function is locked during callbacks. */ - public void destroyFixture(Fixture fixture) - { - jniDestroyFixture( addr, fixture.addr ); + public void destroyFixture (Fixture fixture) { + jniDestroyFixture(addr, fixture.addr); this.world.fixtures.remove(fixture.addr); this.fixtures.remove(fixture); } - - private native void jniDestroyFixture( long addr, long fixtureAddr ); - /** - * Set the position of the body's origin and rotation. - * This breaks any contacts and wakes the other bodies. - * Manipulating a body's transform may cause non-physical behavior. + private native void jniDestroyFixture (long addr, long fixtureAddr); + + /** + * Set the position of the body's origin and rotation. This breaks any contacts and wakes the other bodies. Manipulating a + * body's transform may cause non-physical behavior. * @param position the world position of the body's local origin. * @param angle the world rotation in radians. */ - public void setTransform(Vector2 position, float angle) - { - jniSetTransform( addr, position.x, position.y, angle); - } - - private native void jniSetTransform( long addr, float positionX, float positionY, float angle ); - - /** + public void setTransform (Vector2 position, float angle) { + jniSetTransform(addr, position.x, position.y, angle); + } + + private native void jniSetTransform (long addr, float positionX, float positionY, float angle); + + /** * Get the body transform for the body's origin. FIXME - */ - private final Transform transform = new Transform( ); - public Transform getTransform() - { - jniGetTransform( addr, transform.vals ); + */ + private final Transform transform = new Transform(); + + public Transform getTransform () { + jniGetTransform(addr, transform.vals); return transform; } - private native void jniGetTransform( long addr, float[] vals ); - + private native void jniGetTransform (long addr, float[] vals); + /** * Get the world body origin position. * @return the world position of the body's origin. - */ - private final Vector2 position = new Vector2( ); - public Vector2 getPosition() - { - jniGetPosition( addr, tmp ); - position.x = tmp[0]; position.y = tmp[1]; + */ + private final Vector2 position = new Vector2(); + + public Vector2 getPosition () { + jniGetPosition(addr, tmp); + position.x = tmp[0]; + position.y = tmp[1]; return position; } - private native void jniGetPosition( long addr, float[] position ); - + private native void jniGetPosition (long addr, float[] position); + /** * Get the angle in radians. * @return the current world rotation angle in radians. */ - public float getAngle() - { - return jniGetAngle( addr ); + public float getAngle () { + return jniGetAngle(addr); } - private native float jniGetAngle( long addr ); - + private native float jniGetAngle (long addr); + /** - * Get the world position of the center of mass. - */ - private final Vector2 worldCenter = new Vector2( ); - public Vector2 getWorldCenter() - { - jniGetWorldCenter( addr, tmp ); - worldCenter.x = tmp[0]; worldCenter.y = tmp[1]; + * Get the world position of the center of mass. + */ + private final Vector2 worldCenter = new Vector2(); + + public Vector2 getWorldCenter () { + jniGetWorldCenter(addr, tmp); + worldCenter.x = tmp[0]; + worldCenter.y = tmp[1]; return worldCenter; } - private native void jniGetWorldCenter( long addr, float[] worldCenter ); - + private native void jniGetWorldCenter (long addr, float[] worldCenter); + /** - * Get the local position of the center of mass. - */ - private final Vector2 localCenter = new Vector2( ); - public Vector2 getLocalCenter() - { - jniGetLocalCenter( addr, tmp ); - localCenter.x = tmp[0]; localCenter.y = tmp[1]; + * Get the local position of the center of mass. + */ + private final Vector2 localCenter = new Vector2(); + + public Vector2 getLocalCenter () { + jniGetLocalCenter(addr, tmp); + localCenter.x = tmp[0]; + localCenter.y = tmp[1]; return localCenter; } - - private native void jniGetLocalCenter( long addr, float[] localCenter ); + + private native void jniGetLocalCenter (long addr, float[] localCenter); /** - * Set the linear velocity of the center of mass. + * Set the linear velocity of the center of mass. */ - public void setLinearVelocity(Vector2 v) - { - jniSetLinearVelocity( addr, v.x, v.y ); + public void setLinearVelocity (Vector2 v) { + jniSetLinearVelocity(addr, v.x, v.y); } - - private native void jniSetLinearVelocity( long addr, float x, float y ); + + private native void jniSetLinearVelocity (long addr, float x, float y); /** * Get the linear velocity of the center of mass. - */ - private final Vector2 linearVelocity = new Vector2( ); - public Vector2 getLinearVelocity() - { - jniGetLinearVelocity( addr, tmp ); - linearVelocity.x = tmp[0]; linearVelocity.y = tmp[1]; + */ + private final Vector2 linearVelocity = new Vector2(); + + public Vector2 getLinearVelocity () { + jniGetLinearVelocity(addr, tmp); + linearVelocity.x = tmp[0]; + linearVelocity.y = tmp[1]; return linearVelocity; } - private native void jniGetLinearVelocity( long addr, float[] tmpLinearVelocity ); - + private native void jniGetLinearVelocity (long addr, float[] tmpLinearVelocity); + /** * Set the angular velocity. */ - public void setAngularVelocity(float omega) - { + public void setAngularVelocity (float omega) { jniSetAngularVelocity(addr, omega); } - - private native void jniSetAngularVelocity( long addr, float omega ); + + private native void jniSetAngularVelocity (long addr, float omega); /** * Get the angular velocity. */ - public float getAngularVelocity() - { - return jniGetAngularVelocity( addr ); + public float getAngularVelocity () { + return jniGetAngularVelocity(addr); } - - private native float jniGetAngularVelocity( long addr ); + + private native float jniGetAngularVelocity (long addr); /** - * Apply a force at a world point. If the force is not - * applied at the center of mass, it will generate a torque and - * affect the angular velocity. This wakes up the body. + * Apply a force at a world point. If the force is not applied at the center of mass, it will generate a torque and affect the + * angular velocity. This wakes up the body. * @param force the world force vector, usually in Newtons (N). * @param point the world position of the point of application. */ - public void applyForce(Vector2 force, Vector2 point) - { - jniApplyForce( addr, force.x, force.y, point.x, point.y ); + public void applyForce (Vector2 force, Vector2 point) { + jniApplyForce(addr, force.x, force.y, point.x, point.y); } - - private native void jniApplyForce( long addr, float forceX, float forceY, float pointX, float pointY ); + + private native void jniApplyForce (long addr, float forceX, float forceY, float pointX, float pointY); /** - * Apply a torque. This affects the angular velocity - * without affecting the linear velocity of the center of mass. - * This wakes up the body. + * Apply a torque. This affects the angular velocity without affecting the linear velocity of the center of mass. This wakes up + * the body. * @param torque about the z-axis (out of the screen), usually in N-m. */ - public void applyTorque(float torque) - { - jniApplyTorque( addr, torque ); + public void applyTorque (float torque) { + jniApplyTorque(addr, torque); } - - private native void jniApplyTorque( long addr, float torque ); + + private native void jniApplyTorque (long addr, float torque); /** - * Apply an impulse at a point. This immediately modifies the velocity. - * It also modifies the angular velocity if the point of application - * is not at the center of mass. This wakes up the body. + * Apply an impulse at a point. This immediately modifies the velocity. It also modifies the angular velocity if the point of + * application is not at the center of mass. This wakes up the body. * @param impulse the world impulse vector, usually in N-seconds or kg-m/s. * @param point the world position of the point of application. */ - public void applyLinearImpulse(Vector2 impulse, Vector2 point) - { - jniApplyLinearImpulse( addr, impulse.x, impulse.y, point.x, point.y ); + public void applyLinearImpulse (Vector2 impulse, Vector2 point) { + jniApplyLinearImpulse(addr, impulse.x, impulse.y, point.x, point.y); } - - private native void jniApplyLinearImpulse( long addr, float impulseX, float impulseY, float pointX, float pointY ); + + private native void jniApplyLinearImpulse (long addr, float impulseX, float impulseY, float pointX, float pointY); /** * Apply an angular impulse. * @param impulse the angular impulse in units of kg*m*m/s */ - public void applyAngularImpulse(float impulse) - { - jniApplyAngularImpulse( addr, impulse ); + public void applyAngularImpulse (float impulse) { + jniApplyAngularImpulse(addr, impulse); } - - private native void jniApplyAngularImpulse( long addr, float impulse ); + + private native void jniApplyAngularImpulse (long addr, float impulse); /** * Get the total mass of the body. * @return the mass, usually in kilograms (kg). */ - public float getMass() - { - return jniGetMass( addr ); + public float getMass () { + return jniGetMass(addr); } - - private native float jniGetMass( long addr ); + + private native float jniGetMass (long addr); /** * Get the rotational inertia of the body about the local origin. * @return the rotational inertia, usually in kg-m^2. */ - public float getInertia() - { - return jniGetInertia( addr ); + public float getInertia () { + return jniGetInertia(addr); } - - private native float jniGetInertia( long addr ); + + private native float jniGetInertia (long addr); /** * Get the mass data of the body. * @return a struct containing the mass, inertia and center of the body. - */ - private final MassData massData = new MassData( ); - public MassData getMassData() - { + */ + private final MassData massData = new MassData(); + + public MassData getMassData () { jniGetMassData(addr, tmp); massData.mass = tmp[0]; massData.center.x = tmp[1]; @@ -320,359 +299,323 @@ public class Body massData.I = tmp[3]; return massData; } - - private native void jniGetMassData( long addr, float[] massData ); + + private native void jniGetMassData (long addr, float[] massData); /** - * Set the mass properties to override the mass properties of the fixtures. - * Note that this changes the center of mass position. - * Note that creating or destroying fixtures can also alter the mass. - * This function has no effect if the body isn't dynamic. + * Set the mass properties to override the mass properties of the fixtures. Note that this changes the center of mass position. + * Note that creating or destroying fixtures can also alter the mass. This function has no effect if the body isn't dynamic. * @param massData the mass properties. */ - public void setMassData(MassData data) - { - jniSetMassData( addr, data.mass, data.center.x, data.center.y, data.I ); + public void setMassData (MassData data) { + jniSetMassData(addr, data.mass, data.center.x, data.center.y, data.I); } - - private native void jniSetMassData( long addr, float mass, float centerX, float centerY, float I ); + + private native void jniSetMassData (long addr, float mass, float centerX, float centerY, float I); /** - * This resets the mass properties to the sum of the mass properties of the fixtures. - * This normally does not need to be called unless you called SetMassData to override - * the mass and you later want to reset the mass. + * This resets the mass properties to the sum of the mass properties of the fixtures. This normally does not need to be called + * unless you called SetMassData to override the mass and you later want to reset the mass. */ - public void resetMassData() - { - jniResetMassData( addr ); + public void resetMassData () { + jniResetMassData(addr); } - - private native void jniResetMassData( long addr ); + + private native void jniResetMassData (long addr); /** - * Get the world coordinates of a point given the local coordinates. + * Get the world coordinates of a point given the local coordinates. * @param localPoint a point on the body measured relative the the body's origin. * @return the same point expressed in world coordinates. - */ - private final Vector2 localPoint = new Vector2( ); - public Vector2 getWorldPoint(Vector2 localPoint) - { - jniGetWorldPoint( addr, localPoint.x, localPoint.y, tmp ); - this.localPoint.x = tmp[0]; this.localPoint.y = tmp[1]; + */ + private final Vector2 localPoint = new Vector2(); + + public Vector2 getWorldPoint (Vector2 localPoint) { + jniGetWorldPoint(addr, localPoint.x, localPoint.y, tmp); + this.localPoint.x = tmp[0]; + this.localPoint.y = tmp[1]; return this.localPoint; } - private native void jniGetWorldPoint( long addr, float localPointX, float localPointY, float[] worldPoint ); - + private native void jniGetWorldPoint (long addr, float localPointX, float localPointY, float[] worldPoint); + /** - * Get the world coordinates of a vector given the local coordinates. + * Get the world coordinates of a vector given the local coordinates. * @param localVector a vector fixed in the body. * @return the same vector expressed in world coordinates. - */ - private final Vector2 worldVector = new Vector2( ); - public Vector2 getWorldVector(Vector2 localVector) - { - jniGetWorldVector( addr, localVector.x, localVector.y, tmp ); - worldVector.x = tmp[0]; worldVector.y = tmp[1]; + */ + private final Vector2 worldVector = new Vector2(); + + public Vector2 getWorldVector (Vector2 localVector) { + jniGetWorldVector(addr, localVector.x, localVector.y, tmp); + worldVector.x = tmp[0]; + worldVector.y = tmp[1]; return worldVector; } - - private native void jniGetWorldVector( long addr, float localVectorX, float localVectorY, float[] worldVector ); + + private native void jniGetWorldVector (long addr, float localVectorX, float localVectorY, float[] worldVector); /** - * Gets a local point relative to the body's origin given a world point. + * Gets a local point relative to the body's origin given a world point. * @param a point in world coordinates. * @return the corresponding local point relative to the body's origin. - */ - public final Vector2 localPoint2 = new Vector2( ); - public Vector2 getLocalPoint(Vector2 worldPoint) - { - jniGetLocalPoint( addr, worldPoint.x, worldPoint.y, tmp ); - localPoint2.x = tmp[0]; localPoint2.y = tmp[1]; + */ + public final Vector2 localPoint2 = new Vector2(); + + public Vector2 getLocalPoint (Vector2 worldPoint) { + jniGetLocalPoint(addr, worldPoint.x, worldPoint.y, tmp); + localPoint2.x = tmp[0]; + localPoint2.y = tmp[1]; return localPoint2; } - private native void jniGetLocalPoint( long addr, float worldPointX, float worldPointY, float[] localPoint ); - + private native void jniGetLocalPoint (long addr, float worldPointX, float worldPointY, float[] localPoint); + /** - * Gets a local vector given a world vector. + * Gets a local vector given a world vector. * @param a vector in world coordinates. * @return the corresponding local vector. - */ - public final Vector2 localVector = new Vector2( ); - public Vector2 getLocalVector(Vector2 worldVector) - { - jniGetLocalVector( addr, worldVector.x, worldVector.y, tmp ); - localVector.x = tmp[0]; localVector.y = tmp[1]; + */ + public final Vector2 localVector = new Vector2(); + + public Vector2 getLocalVector (Vector2 worldVector) { + jniGetLocalVector(addr, worldVector.x, worldVector.y, tmp); + localVector.x = tmp[0]; + localVector.y = tmp[1]; return localVector; } - - private native void jniGetLocalVector( long addr, float worldVectorX, float worldVectorY, float[] worldVector ); + + private native void jniGetLocalVector (long addr, float worldVectorX, float worldVectorY, float[] worldVector); /** - * Get the world linear velocity of a world point attached to this body. + * Get the world linear velocity of a world point attached to this body. * @param a point in world coordinates. * @return the world velocity of a point. - */ - public final Vector2 linVelWorld = new Vector2( ); - public Vector2 getLinearVelocityFromWorldPoint(Vector2 worldPoint) - { - jniGetLinearVelocityFromWorldPoint( addr, worldPoint.x, worldPoint.y, tmp ); - linVelWorld.x = tmp[0]; linVelWorld.y = tmp[1]; + */ + public final Vector2 linVelWorld = new Vector2(); + + public Vector2 getLinearVelocityFromWorldPoint (Vector2 worldPoint) { + jniGetLinearVelocityFromWorldPoint(addr, worldPoint.x, worldPoint.y, tmp); + linVelWorld.x = tmp[0]; + linVelWorld.y = tmp[1]; return linVelWorld; } - - private native void jniGetLinearVelocityFromWorldPoint( long addr, float worldPointX, float worldPointY, float[] linVelWorld ); + + private native void jniGetLinearVelocityFromWorldPoint (long addr, float worldPointX, float worldPointY, float[] linVelWorld); /** - * Get the world velocity of a local point. + * Get the world velocity of a local point. * @param a point in local coordinates. * @return the world velocity of a point. - */ - public final Vector2 linVelLoc = new Vector2( ); - - public Vector2 getLinearVelocityFromLocalPoint(Vector2 localPoint) - { - jniGetLinearVelocityFromLocalPoint( addr, localPoint.x, localPoint.y, tmp ); - linVelLoc.x = tmp[0]; linVelLoc.y = tmp[1]; + */ + public final Vector2 linVelLoc = new Vector2(); + + public Vector2 getLinearVelocityFromLocalPoint (Vector2 localPoint) { + jniGetLinearVelocityFromLocalPoint(addr, localPoint.x, localPoint.y, tmp); + linVelLoc.x = tmp[0]; + linVelLoc.y = tmp[1]; return linVelLoc; } - private native void jniGetLinearVelocityFromLocalPoint( long addr, float localPointX, float localPointY, float[] linVelLoc ); - + private native void jniGetLinearVelocityFromLocalPoint (long addr, float localPointX, float localPointY, float[] linVelLoc); + /** - * Get the linear damping of the body. + * Get the linear damping of the body. */ - public float getLinearDamping() - { - return jniGetLinearDamping( addr ); + public float getLinearDamping () { + return jniGetLinearDamping(addr); } - - private native float jniGetLinearDamping( long add ); + + private native float jniGetLinearDamping (long add); /** - * Set the linear damping of the body. + * Set the linear damping of the body. */ - public void setLinearDamping(float linearDamping) - { - jniSetLinearDamping( addr, linearDamping ); + public void setLinearDamping (float linearDamping) { + jniSetLinearDamping(addr, linearDamping); } - private native void jniSetLinearDamping( long addr, float linearDamping ); - + private native void jniSetLinearDamping (long addr, float linearDamping); + /** * Get the angular damping of the body. */ - public float getAngularDamping() - { - return jniGetAngularDamping( addr ); + public float getAngularDamping () { + return jniGetAngularDamping(addr); } - - private native float jniGetAngularDamping( long addr ); + + private native float jniGetAngularDamping (long addr); /** - * Set the angular damping of the body. + * Set the angular damping of the body. */ - public void setAngularDamping(float angularDamping) - { - jniSetAngularDamping( addr, angularDamping ); + public void setAngularDamping (float angularDamping) { + jniSetAngularDamping(addr, angularDamping); } - - private native void jniSetAngularDamping( long addr, float angularDamping ); + + private native void jniSetAngularDamping (long addr, float angularDamping); /** - * Set the type of this body. This may alter the mass and velocity. + * Set the type of this body. This may alter the mass and velocity. */ - public void setType(BodyType type) - { - jniSetType( addr, type.getValue() ); + public void setType (BodyType type) { + jniSetType(addr, type.getValue()); } - - private native void jniSetType( long addr, int type ); + + private native void jniSetType (long addr, int type); /** * Get the type of this body. */ - public BodyType getType() - { - int type = jniGetType( addr ); - if( type == 0 ) - return BodyType.StaticBody; - if( type == 1 ) - return BodyType.KinematicBody; - if( type == 2 ) - return BodyType.DynamicBody; + public BodyType getType () { + int type = jniGetType(addr); + if (type == 0) return BodyType.StaticBody; + if (type == 1) return BodyType.KinematicBody; + if (type == 2) return BodyType.DynamicBody; return BodyType.StaticBody; } - - private native int jniGetType( long addr ); + + private native int jniGetType (long addr); /** * Should this body be treated like a bullet for continuous collision detection? */ - public void setBullet(boolean flag) - { - jniSetBullet( addr, flag ); + public void setBullet (boolean flag) { + jniSetBullet(addr, flag); } - - private native void jniSetBullet( long addr, boolean flag ); + + private native void jniSetBullet (long addr, boolean flag); /** - * Is this body treated like a bullet for continuous collision detection? + * Is this body treated like a bullet for continuous collision detection? */ - public boolean isBullet() - { - return jniIsBullet( addr ); + public boolean isBullet () { + return jniIsBullet(addr); } - - private native boolean jniIsBullet( long addr ); + + private native boolean jniIsBullet (long addr); /** - * You can disable sleeping on this body. If you disable sleeping, the + * You can disable sleeping on this body. If you disable sleeping, the */ - public void setSleepingAllowed(boolean flag) - { - jniSetSleepingAllowed( addr, flag ); + public void setSleepingAllowed (boolean flag) { + jniSetSleepingAllowed(addr, flag); } - - private native void jniSetSleepingAllowed( long addr, boolean flag ); + + private native void jniSetSleepingAllowed (long addr, boolean flag); /** - * Is this body allowed to sleep + * Is this body allowed to sleep */ - public boolean isSleepingAllowed() - { - return jniIsSleepingAllowed( addr ); + public boolean isSleepingAllowed () { + return jniIsSleepingAllowed(addr); } - - private native boolean jniIsSleepingAllowed( long addr ); + + private native boolean jniIsSleepingAllowed (long addr); /** - * Set the sleep state of the body. A sleeping body has very - * low CPU cost. + * Set the sleep state of the body. A sleeping body has very low CPU cost. * @param flag set to true to put body to sleep, false to wake it. */ - public void setAwake(boolean flag) - { - jniSetAwake( addr, flag ); + public void setAwake (boolean flag) { + jniSetAwake(addr, flag); } - - private native void jniSetAwake( long addr, boolean flag ); + + private native void jniSetAwake (long addr, boolean flag); /** - * Get the sleeping state of this body. + * Get the sleeping state of this body. * @return true if the body is sleeping. */ - public boolean isAwake() - { - return jniIsAwake( addr ); + public boolean isAwake () { + return jniIsAwake(addr); } - - private native boolean jniIsAwake( long addr ); + + private native boolean jniIsAwake (long addr); /** - * Set the active state of the body. An inactive body is not - * simulated and cannot be collided with or woken up. - * If you pass a flag of true, all fixtures will be added to the - * broad-phase. - * If you pass a flag of false, all fixtures will be removed from - * the broad-phase and all contacts will be destroyed. - * Fixtures and joints are otherwise unaffected. You may continue - * to create/destroy fixtures and joints on inactive bodies. - * Fixtures on an inactive body are implicitly inactive and will - * not participate in collisions, ray-casts, or queries. - * Joints connected to an inactive body are implicitly inactive. - * An inactive body is still owned by a b2World object and remains - * in the body list. + * Set the active state of the body. An inactive body is not simulated and cannot be collided with or woken up. If you pass a + * flag of true, all fixtures will be added to the broad-phase. If you pass a flag of false, all fixtures will be removed from + * the broad-phase and all contacts will be destroyed. Fixtures and joints are otherwise unaffected. You may continue to + * create/destroy fixtures and joints on inactive bodies. Fixtures on an inactive body are implicitly inactive and will not + * participate in collisions, ray-casts, or queries. Joints connected to an inactive body are implicitly inactive. An inactive + * body is still owned by a b2World object and remains in the body list. */ - public void setActive(boolean flag) - { - jniSetActive( addr, flag ); + public void setActive (boolean flag) { + jniSetActive(addr, flag); } - - private native void jniSetActive( long addr, boolean flag ); + + private native void jniSetActive (long addr, boolean flag); /** - * Get the active state of the body. + * Get the active state of the body. */ - public boolean isActive() - { - return jniIsActive( addr ); + public boolean isActive () { + return jniIsActive(addr); } - - private native boolean jniIsActive( long addr ); + + private native boolean jniIsActive (long addr); /** - * Set this body to have fixed rotation. This causes the mass - * to be reset. + * Set this body to have fixed rotation. This causes the mass to be reset. */ - public void setFixedRotation(boolean flag) - { - jniSetFixedRotation( addr, flag ); + public void setFixedRotation (boolean flag) { + jniSetFixedRotation(addr, flag); } - - private native void jniSetFixedRotation( long addr, boolean flag ); - /** + private native void jniSetFixedRotation (long addr, boolean flag); + + /** * Does this body have fixed rotation? */ - public boolean isFixedRotation() - { - return jniIsFixedRotation( addr ); + public boolean isFixedRotation () { + return jniIsFixedRotation(addr); } - - private native boolean jniIsFixedRotation( long addr ); - + + private native boolean jniIsFixedRotation (long addr); + /** - * Get the list of all fixtures attached to this body. - * Do not modify the list! + * Get the list of all fixtures attached to this body. Do not modify the list! */ - public ArrayList getFixtureList() - { + public ArrayList getFixtureList () { return fixtures; } /** - * Get the list of all joints attached to this body. - * Do not modify the list! + * Get the list of all joints attached to this body. Do not modify the list! */ - public ArrayList getJointList() - { + public ArrayList getJointList () { return joints; - } + } /** - * Get the list of all contacts attached to this body. - * @warning this list changes during the time step and you may - * miss some collisions if you don't use b2ContactListener. - * Do not modify the returned list! + * Get the list of all contacts attached to this body. + * @warning this list changes during the time step and you may miss some collisions if you don't use b2ContactListener. Do not + * modify the returned list! */ -// ArrayList getContactList() -// { -// return contacts; -// } - +// ArrayList getContactList() +// { +// return contacts; +// } + /** - * Get the parent world of this body. + * Get the parent world of this body. */ - public World getWorld() - { + public World getWorld () { return world; } - + /** * Get the user data */ - public Object getUserData( ) - { + public Object getUserData () { return userData; } - + /** * Set the user data */ - public void setUserData( Object userData ) - { + public void setUserData (Object userData) { this.userData = userData; } } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/BodyDef.java b/gdx/src/com/badlogic/gdx/physics/box2d/BodyDef.java index ce1a96cd7..431c2b3ce 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/BodyDef.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/BodyDef.java @@ -1,62 +1,54 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; import com.badlogic.gdx.math.Vector2; /** - * A body definition holds all the data needed to construct a rigid body. - * You can safely re-use body definitions. Shapes are added to a body after construction. + * A body definition holds all the data needed to construct a rigid body. You can safely re-use body definitions. Shapes are added + * to a body after construction. * * @author mzechner - * + * */ -public class BodyDef -{ +public class BodyDef { /** - * The body type. - * static: zero mass, zero velocity, may be manually moved - * kinematic: zero mass, non-zero velocity set by user, moved by solver - * dynamic: positive mass, non-zero velocity determined by forces, moved by solver + * The body type. static: zero mass, zero velocity, may be manually moved kinematic: zero mass, non-zero velocity set by user, + * moved by solver dynamic: positive mass, non-zero velocity determined by forces, moved by solver */ - public enum BodyType - { - StaticBody( 0 ), - KinematicBody( 1 ), - DynamicBody( 2 ); - + public enum BodyType { + StaticBody(0), KinematicBody(1), DynamicBody(2); + private int value; - - private BodyType( int value ) - { + + private BodyType (int value) { this.value = value; } - - public int getValue() - { + + public int getValue () { return value; } }; - - /** The body type: static, kinematic, or dynamic. - Note: if a dynamic body would have zero mass, the mass is set to one. **/ + + /** + * The body type: static, kinematic, or dynamic. Note: if a dynamic body would have zero mass, the mass is set to one. + **/ public BodyType type = BodyType.StaticBody; - /** The world position of the body. Avoid creating bodies at the origin - since this can lead to many overlapping shapes. **/ + /** + * The world position of the body. Avoid creating bodies at the origin since this can lead to many overlapping shapes. + **/ public final Vector2 position = new Vector2(); /** The world angle of the body in radians. **/ @@ -68,18 +60,21 @@ public class BodyDef /** The angular velocity of the body. **/ public float angularVelocity = 0; - /** Linear damping is use to reduce the linear velocity. The damping parameter - can be larger than 1.0f but the damping effect becomes sensitive to the - time step when the damping parameter is large. **/ + /** + * Linear damping is use to reduce the linear velocity. The damping parameter can be larger than 1.0f but the damping effect + * becomes sensitive to the time step when the damping parameter is large. + **/ public float linearDamping = 0; - /** Angular damping is use to reduce the angular velocity. The damping parameter - can be larger than 1.0f but the damping effect becomes sensitive to the - time step when the damping parameter is large. **/ + /** + * Angular damping is use to reduce the angular velocity. The damping parameter can be larger than 1.0f but the damping effect + * becomes sensitive to the time step when the damping parameter is large. + **/ public float angularDamping = 0; - /** Set this flag to false if this body should never fall asleep. Note that - this increases CPU usage. **/ + /** + * Set this flag to false if this body should never fall asleep. Note that this increases CPU usage. + **/ public boolean allowSleep = true; /** Is this body initially awake or sleeping? **/ @@ -88,10 +83,11 @@ public class BodyDef /** Should this body be prevented from rotating? Useful for characters. **/ public boolean fixedRotation = false; - /** Is this a fast moving body that should be prevented from tunneling through - other moving bodies? Note that all bodies are prevented from tunneling through - kinematic and static bodies. This setting is only considered on dynamic bodies. - @warning You should use this flag sparingly since it increases processing time. **/ + /** + * Is this a fast moving body that should be prevented from tunneling through other moving bodies? Note that all bodies are + * prevented from tunneling through kinematic and static bodies. This setting is only considered on dynamic bodies. + * @warning You should use this flag sparingly since it increases processing time. + **/ public boolean bullet = false; /** Does this body start out active? **/ diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/Box2DDebugRenderer.java b/gdx/src/com/badlogic/gdx/physics/box2d/Box2DDebugRenderer.java index a1feff48c..3d3cdcb1f 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/Box2DDebugRenderer.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/Box2DDebugRenderer.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; import java.util.List; @@ -20,207 +18,177 @@ import java.util.List; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Font; +import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.ImmediateModeRenderer; import com.badlogic.gdx.graphics.SpriteBatch; -import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.JointDef.JointType; import com.badlogic.gdx.physics.box2d.Shape.Type; import com.badlogic.gdx.physics.box2d.joints.PulleyJoint; -public class Box2DDebugRenderer -{ - +public class Box2DDebugRenderer { + /** the immediate mode renderer to output our debug drawings **/ protected ImmediateModeRenderer renderer; - + /** a spritebatch and a font for text rendering **/ public SpriteBatch batch; public Font font; - + /** vertices for polygon rendering **/ private static Vector2[] vertices = new Vector2[100]; - - public Box2DDebugRenderer( ) - { + + public Box2DDebugRenderer () { // next we setup the immediate mode renderer renderer = new ImmediateModeRenderer(); - + // next we create a SpriteBatch and a font batch = new SpriteBatch(); - font = Gdx.graphics.newFont( "Arial", 12, FontStyle.Plain ); - + font = Gdx.graphics.newFont("Arial", 12, FontStyle.Plain); + // initialize vertices array - for( int i = 0; i < vertices.length; i++ ) - vertices[i] = new Vector2( ); + for (int i = 0; i < vertices.length; i++) + vertices[i] = new Vector2(); } - + /** - * This assumes that the projection matrix has already been - * set. + * This assumes that the projection matrix has already been set. */ - public void render( World world ) - { - renderBodies( world ); + public void render (World world) { + renderBodies(world); } - - private final Color SHAPE_NOT_ACTIVE = new Color( 0.5f, 0.5f, 0.3f, 1 ); - private final Color SHAPE_STATIC = new Color( 0.5f, 0.9f, 0.5f, 1 ); - private final Color SHAPE_KINEMATIC = new Color( 0.5f, 0.5f, 0.9f, 1 ); - private final Color SHAPE_NOT_AWAKE = new Color( 0.6f, 0.6f, 0.6f, 1 ); - private final Color SHAPE_AWAKE = new Color( 0.9f, 0.7f, 0.7f, 1 ); - private final Color JOINT_COLOR = new Color( 0.5f, 0.8f, 0.8f, 1 ); - - private void renderBodies( World world ) - { - for( Body body: world.getBodies() ) - { - Transform transform = body.getTransform( ); + + private final Color SHAPE_NOT_ACTIVE = new Color(0.5f, 0.5f, 0.3f, 1); + private final Color SHAPE_STATIC = new Color(0.5f, 0.9f, 0.5f, 1); + private final Color SHAPE_KINEMATIC = new Color(0.5f, 0.5f, 0.9f, 1); + private final Color SHAPE_NOT_AWAKE = new Color(0.6f, 0.6f, 0.6f, 1); + private final Color SHAPE_AWAKE = new Color(0.9f, 0.7f, 0.7f, 1); + private final Color JOINT_COLOR = new Color(0.5f, 0.8f, 0.8f, 1); + + private void renderBodies (World world) { + for (Body body : world.getBodies()) { + Transform transform = body.getTransform(); int len = body.getFixtureList().size(); List fixtures = body.getFixtureList(); - for( int i = 0; i < len; i++ ) - { - Fixture fixture = fixtures.get( i ); - if( body.isActive() == false ) - drawShape( fixture, transform, SHAPE_NOT_ACTIVE ); - else - if( body.getType() == BodyType.StaticBody ) - drawShape( fixture, transform, SHAPE_STATIC ); - else - if( body.getType() == BodyType.KinematicBody ) - drawShape( fixture, transform, SHAPE_KINEMATIC ); - else - if( body.isAwake() == false ) - drawShape( fixture, transform, SHAPE_NOT_AWAKE ); + for (int i = 0; i < len; i++) { + Fixture fixture = fixtures.get(i); + if (body.isActive() == false) + drawShape(fixture, transform, SHAPE_NOT_ACTIVE); + else if (body.getType() == BodyType.StaticBody) + drawShape(fixture, transform, SHAPE_STATIC); + else if (body.getType() == BodyType.KinematicBody) + drawShape(fixture, transform, SHAPE_KINEMATIC); + else if (body.isAwake() == false) + drawShape(fixture, transform, SHAPE_NOT_AWAKE); else - drawShape( fixture, transform, SHAPE_AWAKE ); + drawShape(fixture, transform, SHAPE_AWAKE); } } - - for( Joint joint: world.getJoints() ) - drawJoint( joint ); - + + for (Joint joint : world.getJoints()) + drawJoint(joint); + int len = world.getContactList().size(); - for( int i = 0; i < len; i++ ) - drawContact( world.getContactList().get(i) ); + for (int i = 0; i < len; i++) + drawContact(world.getContactList().get(i)); } - + private static Vector2 t = new Vector2(); - private static Vector2 axis = new Vector2(); - private void drawShape( Fixture fixture, Transform transform, Color color ) - { - if( fixture.getType() == Type.Circle ) - { - CircleShape circle = (CircleShape)fixture.getShape(); - t.set( circle.getPosition() ); - transform.mul( t ); - drawSolidCircle( t, circle.getRadius(), axis.set( transform.vals[Transform.COL1_X], transform.vals[Transform.COL1_Y] ), color ); - } - else - { + private static Vector2 axis = new Vector2(); + + private void drawShape (Fixture fixture, Transform transform, Color color) { + if (fixture.getType() == Type.Circle) { + CircleShape circle = (CircleShape)fixture.getShape(); + t.set(circle.getPosition()); + transform.mul(t); + drawSolidCircle(t, circle.getRadius(), axis.set(transform.vals[Transform.COL1_X], transform.vals[Transform.COL1_Y]), + color); + } else { PolygonShape poly = (PolygonShape)fixture.getShape(); int vertexCount = poly.getVertexCount(); - for( int i = 0; i < vertexCount; i++ ) - { + for (int i = 0; i < vertexCount; i++) { poly.getVertex(i, vertices[i]); - transform.mul( vertices[i] ); + transform.mul(vertices[i]); } - drawSolidPolygon( vertices, vertexCount, color ); + drawSolidPolygon(vertices, vertexCount, color); } } - - - private final Vector2 v = new Vector2( ); - private void drawSolidCircle( Vector2 center, float radius, Vector2 axis, Color color ) - { - renderer.begin( GL10.GL_LINE_LOOP ); + + private final Vector2 v = new Vector2(); + + private void drawSolidCircle (Vector2 center, float radius, Vector2 axis, Color color) { + renderer.begin(GL10.GL_LINE_LOOP); float angle = 0; float angleInc = 2 * (float)Math.PI / 20; - for( int i = 0; i < 20; i++, angle += angleInc ) - { - v.set( (float)Math.cos(angle) * radius + center.x, (float)Math.sin(angle) * radius + center.y ); - renderer.color( color.r, color.g, color.b, color.a ); - renderer.vertex( v.x, v.y, 0 ); + for (int i = 0; i < 20; i++, angle += angleInc) { + v.set((float)Math.cos(angle) * radius + center.x, (float)Math.sin(angle) * radius + center.y); + renderer.color(color.r, color.g, color.b, color.a); + renderer.vertex(v.x, v.y, 0); } - renderer.end( ); - - renderer.begin( GL10.GL_LINES ); - renderer.color( color.r, color.g, color.b, color.a ); - renderer.vertex( center.x, center.y, 0 ); - renderer.color( color.r, color.g, color.b, color.a ); - renderer.vertex( center.x + axis.x * radius, center.y + axis.y * radius, 0 ); - renderer.end( ); + renderer.end(); + + renderer.begin(GL10.GL_LINES); + renderer.color(color.r, color.g, color.b, color.a); + renderer.vertex(center.x, center.y, 0); + renderer.color(color.r, color.g, color.b, color.a); + renderer.vertex(center.x + axis.x * radius, center.y + axis.y * radius, 0); + renderer.end(); } - - private void drawSolidPolygon( Vector2[] vertices, int vertexCount, Color color ) - { - renderer.begin( GL10.GL_LINE_LOOP ); - for( int i = 0; i < vertexCount; i++ ) - { + + private void drawSolidPolygon (Vector2[] vertices, int vertexCount, Color color) { + renderer.begin(GL10.GL_LINE_LOOP); + for (int i = 0; i < vertexCount; i++) { Vector2 v = vertices[i]; - renderer.color( color.r, color.g, color.b, color.a ); - renderer.vertex( v.x, v.y, 0 ); + renderer.color(color.r, color.g, color.b, color.a); + renderer.vertex(v.x, v.y, 0); } renderer.end(); - } - - private void drawJoint( Joint joint ) - { + } + + private void drawJoint (Joint joint) { Body bodyA = joint.getBodyA(); Body bodyB = joint.getBodyB(); Transform xf1 = bodyA.getTransform(); Transform xf2 = bodyB.getTransform(); - + Vector2 x1 = xf1.getPosition(); Vector2 x2 = xf2.getPosition(); Vector2 p1 = joint.getAnchorA(); Vector2 p2 = joint.getAnchorB(); - - if( joint.getType() == JointType.DistanceJoint ) - { - drawSegment( p1, p2, JOINT_COLOR ); - } - else - if( joint.getType() == JointType.PulleyJoint ) - { + + if (joint.getType() == JointType.DistanceJoint) { + drawSegment(p1, p2, JOINT_COLOR); + } else if (joint.getType() == JointType.PulleyJoint) { PulleyJoint pulley = (PulleyJoint)joint; Vector2 s1 = pulley.getGroundAnchorA(); Vector2 s2 = pulley.getGroundAnchorB(); - drawSegment( s1, p1, JOINT_COLOR); - drawSegment( s2, p2, JOINT_COLOR ); - drawSegment( s1, s2, JOINT_COLOR ); - } - else - if( joint.getType() == JointType.MouseJoint ) - { - } - else - { - drawSegment( x1, p1, JOINT_COLOR ); - drawSegment( p1, p2, JOINT_COLOR ); - drawSegment( x2, p2, JOINT_COLOR ); + drawSegment(s1, p1, JOINT_COLOR); + drawSegment(s2, p2, JOINT_COLOR); + drawSegment(s1, s2, JOINT_COLOR); + } else if (joint.getType() == JointType.MouseJoint) { + } else { + drawSegment(x1, p1, JOINT_COLOR); + drawSegment(p1, p2, JOINT_COLOR); + drawSegment(x2, p2, JOINT_COLOR); } } - - private void drawSegment( Vector2 x1, Vector2 x2, Color color ) - { - renderer.begin( GL10.GL_LINES ); - renderer.color( color.r, color.g, color.b, color.a ); - renderer.vertex( x1.x, x1.y, 0 ); - renderer.color( color.r, color.g, color.b, color.a ); - renderer.vertex( x2.x, x2.y, 0 ); + + private void drawSegment (Vector2 x1, Vector2 x2, Color color) { + renderer.begin(GL10.GL_LINES); + renderer.color(color.r, color.g, color.b, color.a); + renderer.vertex(x1.x, x1.y, 0); + renderer.color(color.r, color.g, color.b, color.a); + renderer.vertex(x2.x, x2.y, 0); renderer.end(); } - - private void drawContact( Contact contact ) - { - + + private void drawContact (Contact contact) { + } - - public void dispose( ) - { + + public void dispose () { batch.dispose(); font.dispose(); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/CircleShape.java b/gdx/src/com/badlogic/gdx/physics/box2d/CircleShape.java index 77f949e9e..0384c902c 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/CircleShape.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/CircleShape.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; import com.badlogic.gdx.math.Vector2; @@ -20,52 +18,47 @@ import com.badlogic.gdx.math.Vector2; /** * A circle shape. * @author mzechner - * + * */ -public class CircleShape extends Shape -{ - public CircleShape( ) - { - addr = newCircleShape( ); +public class CircleShape extends Shape { + public CircleShape () { + addr = newCircleShape(); } - - private native long newCircleShape( ); - - protected CircleShape( long addr ) - { + + private native long newCircleShape (); + + protected CircleShape (long addr) { this.addr = addr; } - + /** * {@inheritDoc} */ - @Override - public Type getType() - { + @Override public Type getType () { return Type.Circle; } - + /** * Returns the position of the shape */ private final float[] tmp = new float[2]; - private final Vector2 position = new Vector2( ); - public Vector2 getPosition( ) - { - jniGetPosition( addr, tmp ); - position.x = tmp[0]; position.y = tmp[1]; + private final Vector2 position = new Vector2(); + + public Vector2 getPosition () { + jniGetPosition(addr, tmp); + position.x = tmp[0]; + position.y = tmp[1]; return position; } - - private native void jniGetPosition( long addr, float[] position ); - + + private native void jniGetPosition (long addr, float[] position); + /** * Sets the position of the shape */ - public void setPosition( Vector2 position ) - { - jniSetPosition( addr, position.x, position.y ); + public void setPosition (Vector2 position) { + jniSetPosition(addr, position.x, position.y); } - - private native void jniSetPosition( long addr, float positionX, float positionY ); + + private native void jniSetPosition (long addr, float positionX, float positionY); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/Contact.java b/gdx/src/com/badlogic/gdx/physics/box2d/Contact.java index 6ccd3468a..a0d88920b 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/Contact.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/Contact.java @@ -1,114 +1,102 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; import com.badlogic.gdx.math.Vector2; /** - * The class manages contact between two shapes. A contact exists for each overlapping - * AABB in the broad-phase (except if filtered). Therefore a contact object may exist - * that has no contact points. + * The class manages contact between two shapes. A contact exists for each overlapping AABB in the broad-phase (except if + * filtered). Therefore a contact object may exist that has no contact points. * @author mzechner - * + * */ -public class Contact -{ +public class Contact { /** the address **/ protected long addr; - + /** the world **/ protected World world; - + /** the world manifold **/ - protected final WorldManifold worldManifold = new WorldManifold( ); - - protected Contact( World world, long addr ) - { + protected final WorldManifold worldManifold = new WorldManifold(); + + protected Contact (World world, long addr) { this.addr = addr; - this.world = world; + this.world = world; } - + /** * Get the world manifold. - */ + */ private final float[] tmp = new float[6]; - public WorldManifold GetWorldManifold() - { - int numContactPoints = jniGetWorldManifold( addr, tmp ); - + + public WorldManifold GetWorldManifold () { + int numContactPoints = jniGetWorldManifold(addr, tmp); + worldManifold.numContactPoints = numContactPoints; - worldManifold.normal.set( tmp[0], tmp[1] ); - for( int i = 0; i < numContactPoints; i++ ) - { + worldManifold.normal.set(tmp[0], tmp[1]); + for (int i = 0; i < numContactPoints; i++) { Vector2 point = worldManifold.points[i]; - point.x = tmp[2+i*2]; - point.y = tmp[2+i*2 + 1]; + point.x = tmp[2 + i * 2]; + point.y = tmp[2 + i * 2 + 1]; } - + return worldManifold; } - - private native int jniGetWorldManifold( long addr, float[] manifold ); - - public boolean isTouching( ) - { - return jniIsTouching( addr ); + + private native int jniGetWorldManifold (long addr, float[] manifold); + + public boolean isTouching () { + return jniIsTouching(addr); } - - private native boolean jniIsTouching( long addr ); - + + private native boolean jniIsTouching (long addr); + /** - * Enable/disable this contact. This can be used inside the pre-solve - * contact listener. The contact is only disabled for the current - * time step (or sub-step in continuous collisions). + * Enable/disable this contact. This can be used inside the pre-solve contact listener. The contact is only disabled for the + * current time step (or sub-step in continuous collisions). */ - public void setEnabled(boolean flag) - { - jniSetEnabled( addr, flag ); + public void setEnabled (boolean flag) { + jniSetEnabled(addr, flag); } - - private native void jniSetEnabled( long addr, boolean flag ); + + private native void jniSetEnabled (long addr, boolean flag); /** - * Has this contact been disabled? + * Has this contact been disabled? */ - public boolean isEnabled() - { - return jniIsEnabled( addr ); + public boolean isEnabled () { + return jniIsEnabled(addr); } - - private native boolean jniIsEnabled( long addr ); + + private native boolean jniIsEnabled (long addr); /** - * Get the first fixture in this contact. + * Get the first fixture in this contact. */ - public Fixture getFixtureA() - { - return world.fixtures.get( jniGetFixtureA( addr ) ); - } - - private native long jniGetFixtureA( long addr ); + public Fixture getFixtureA () { + return world.fixtures.get(jniGetFixtureA(addr)); + } + + private native long jniGetFixtureA (long addr); /** - * Get the second fixture in this contact. + * Get the second fixture in this contact. */ - public Fixture getFixtureB() - { - return world.fixtures.get( jniGetFixtureB( addr ) ); - } - - private native long jniGetFixtureB( long addr ); + public Fixture getFixtureB () { + return world.fixtures.get(jniGetFixtureB(addr)); + } + + private native long jniGetFixtureB (long addr); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/ContactFilter.java b/gdx/src/com/badlogic/gdx/physics/box2d/ContactFilter.java index a20fa2369..78b6dd751 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/ContactFilter.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/ContactFilter.java @@ -1,27 +1,24 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; /** - * Implement this class to provide collision filtering. In other words, you can implement - * this class if you want finer control over contact creation. + * Implement this class to provide collision filtering. In other words, you can implement this class if you want finer control + * over contact creation. * @author mzechner - * + * */ -public interface ContactFilter -{ - boolean shouldCollide( Fixture fixtureA, Fixture fixtureB ); +public interface ContactFilter { + boolean shouldCollide (Fixture fixtureA, Fixture fixtureB); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/ContactListener.java b/gdx/src/com/badlogic/gdx/physics/box2d/ContactListener.java index 5a0e10e85..47c271f85 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/ContactListener.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/ContactListener.java @@ -1,29 +1,26 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; -public interface ContactListener -{ +public interface ContactListener { /** * Called when two fixtures begin to touch. */ - public void beginContact( Contact contact ); - + public void beginContact (Contact contact); + /** * Called when two fixtures cease to touch. */ - public void endContact( Contact contact ); + public void endContact (Contact contact); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/DestructionListener.java b/gdx/src/com/badlogic/gdx/physics/box2d/DestructionListener.java index e6feb92e9..1e4248061 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/DestructionListener.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/DestructionListener.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; public interface DestructionListener { diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/Filter.java b/gdx/src/com/badlogic/gdx/physics/box2d/Filter.java index cf17924ab..59e62214f 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/Filter.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/Filter.java @@ -1,42 +1,37 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; /** * This holds contact filtering data. * @author mzechner - * + * */ -public class Filter -{ +public class Filter { /** * The collision category bits. Normally you would just set one bit. */ public short categoryBits = 0x0001; - + /** - * The collision mask bits. This states the categories that this - * shape would accept for collision. + * The collision mask bits. This states the categories that this shape would accept for collision. */ public short maskBits = -1; - + /** - * Collision groups allow a certain group of objects to never collide (negative) - * or always collide (positive). Zero means no collision group. Non-zero group - * filtering always wins against the mask bits. - */ + * Collision groups allow a certain group of objects to never collide (negative) or always collide (positive). Zero means no + * collision group. Non-zero group filtering always wins against the mask bits. + */ public short groupIndex = 0; } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/Fixture.java b/gdx/src/com/badlogic/gdx/physics/box2d/Fixture.java index bcf924cf9..c477c5dfb 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/Fixture.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/Fixture.java @@ -1,234 +1,216 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Shape.Type; -public class Fixture -{ +public class Fixture { /** body **/ private final Body body; - + /** the address of the fixture **/ protected final long addr; - + /** the shape, initialized lazy **/ protected Shape shape; - + /** * Constructs a new fixture * @param addr the address of the fixture */ - protected Fixture( Body body, long addr ) - { + protected Fixture (Body body, long addr) { this.body = body; this.addr = addr; } - + /** * Get the type of the child shape. You can use this to down cast to the concrete shape. * @return the shape type. */ - public Type getType() - { - int type = jniGetType( addr ); - if( type == 0 ) + public Type getType () { + int type = jniGetType(addr); + if (type == 0) return Type.Circle; else - return Type.Polygon; + return Type.Polygon; } - - private native int jniGetType( long addr ); + + private native int jniGetType (long addr); /** * Returns the shape of this fixture */ - public Shape getShape( ) - { - if( shape == null ) - { - long shapeAddr = jniGetShape( addr ); - int type = Shape.jniGetType( shapeAddr ); - - if( type == 0 ) - shape = new CircleShape( shapeAddr ); + public Shape getShape () { + if (shape == null) { + long shapeAddr = jniGetShape(addr); + int type = Shape.jniGetType(shapeAddr); + + if (type == 0) + shape = new CircleShape(shapeAddr); else - shape = new PolygonShape( shapeAddr ); + shape = new PolygonShape(shapeAddr); } - + return shape; } - - private native long jniGetShape( long addr ); - + + private native long jniGetShape (long addr); + /** - * Set if this fixture is a sensor. + * Set if this fixture is a sensor. */ - public void setSensor(boolean sensor) - { - jniSetSensor( addr, sensor ); + public void setSensor (boolean sensor) { + jniSetSensor(addr, sensor); } - - private native void jniSetSensor( long addr, boolean sensor ); + + private native void jniSetSensor (long addr, boolean sensor); /** * Is this fixture a sensor (non-solid)? * @return the true if the shape is a sensor. - */ - public boolean isSensor() - { - return jniIsSensor( addr ); + */ + public boolean isSensor () { + return jniIsSensor(addr); } - - private native boolean jniIsSensor( long addr ); + + private native boolean jniIsSensor (long addr); /** - * Set the contact filtering data. This will not update contacts until the next time - * step when either parent body is active and awake. + * Set the contact filtering data. This will not update contacts until the next time step when either parent body is active and + * awake. */ - public void setFilterData(Filter filter) - { - jniSetFilterData( addr, filter.categoryBits, filter.maskBits, filter.groupIndex ); + public void setFilterData (Filter filter) { + jniSetFilterData(addr, filter.categoryBits, filter.maskBits, filter.groupIndex); } - - private native void jniSetFilterData( long addr, short categoryBits, short maskBits, short groupIndex ); + + private native void jniSetFilterData (long addr, short categoryBits, short maskBits, short groupIndex); /** - * Get the contact filtering data. + * Get the contact filtering data. */ private final short[] tmp = new short[3]; - private final Filter filter = new Filter( ); - public Filter getFilterData() - { - jniGetFilterData( addr, tmp ); + private final Filter filter = new Filter(); + + public Filter getFilterData () { + jniGetFilterData(addr, tmp); filter.categoryBits = tmp[0]; filter.maskBits = tmp[1]; filter.groupIndex = tmp[2]; return filter; } - - private native void jniGetFilterData( long addr, short[] filter ); + + private native void jniGetFilterData (long addr, short[] filter); /** - * Get the parent body of this fixture. This is NULL if the fixture is not attached. + * Get the parent body of this fixture. This is NULL if the fixture is not attached. */ - public Body getBody() - { + public Body getBody () { return body; } - - /** - * Test a point for containment in this fixture. + + /** + * Test a point for containment in this fixture. * @param p a point in world coordinates. */ - public boolean testPoint(Vector2 p) - { - return jniTestPoint( addr, p.x, p.y ); + public boolean testPoint (Vector2 p) { + return jniTestPoint(addr, p.x, p.y); } - - private native boolean jniTestPoint( long addr, float x, float y ); - -// const b2Body* GetBody() const; + + private native boolean jniTestPoint (long addr, float x, float y); + +// const b2Body* GetBody() const; // -// /// Get the next fixture in the parent body's fixture list. -// /// @return the next shape. -// b2Fixture* GetNext(); -// const b2Fixture* GetNext() const; +// /// Get the next fixture in the parent body's fixture list. +// /// @return the next shape. +// b2Fixture* GetNext(); +// const b2Fixture* GetNext() const; // -// /// Get the user data that was assigned in the fixture definition. Use this to -// /// store your application specific data. -// void* GetUserData() const; +// /// Get the user data that was assigned in the fixture definition. Use this to +// /// store your application specific data. +// void* GetUserData() const; // -// /// Set the user data. Use this to store your application specific data. -// void SetUserData(void* data); +// /// Set the user data. Use this to store your application specific data. +// void SetUserData(void* data); // -// /// Cast a ray against this shape. -// /// @param output the ray-cast results. -// /// @param input the ray-cast input parameters. -// bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const; +// /// Cast a ray against this shape. +// /// @param output the ray-cast results. +// /// @param input the ray-cast input parameters. +// bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const; // -// /// Get the mass data for this fixture. The mass data is based on the density and -// /// the shape. The rotational inertia is about the shape's origin. This operation -// /// may be expensive. -// void GetMassData(b2MassData* massData) const; +// /// Get the mass data for this fixture. The mass data is based on the density and +// /// the shape. The rotational inertia is about the shape's origin. This operation +// /// may be expensive. +// void GetMassData(b2MassData* massData) const; /** - * Set the density of this fixture. This will _not_ automatically adjust the mass - * of the body. You must call b2Body::ResetMassData to update the body's mass. + * Set the density of this fixture. This will _not_ automatically adjust the mass of the body. You must call + * b2Body::ResetMassData to update the body's mass. */ - public void setDensity(float density) - { - jniSetDensity( addr, density ); + public void setDensity (float density) { + jniSetDensity(addr, density); } - - private native void jniSetDensity( long addr, float density ); + + private native void jniSetDensity (long addr, float density); /** - * Get the density of this fixture. + * Get the density of this fixture. */ - public float getDensity() - { - return jniGetDensity( addr ); + public float getDensity () { + return jniGetDensity(addr); } - - private native float jniGetDensity( long addr ); + + private native float jniGetDensity (long addr); /** - * Get the coefficient of friction. + * Get the coefficient of friction. */ - public float getFriction() - { - return jniGetFriction( addr ); + public float getFriction () { + return jniGetFriction(addr); } - - private native float jniGetFriction( long addr ); + + private native float jniGetFriction (long addr); /** - * Set the coefficient of friction. + * Set the coefficient of friction. */ - public void setFriction(float friction) - { - jniSetFriction( addr, friction ); + public void setFriction (float friction) { + jniSetFriction(addr, friction); } - - private native void jniSetFriction( long addr, float friction ); + + private native void jniSetFriction (long addr, float friction); /** * Get the coefficient of restitution. */ - public float getRestitution() - { - return jniGetRestitution( addr ); + public float getRestitution () { + return jniGetRestitution(addr); } - - private native float jniGetRestitution( long addr ); - /** + private native float jniGetRestitution (long addr); + + /** * Set the coefficient of restitution. */ - public void setRestitution(float restitution) - { - jniSetRestitution( addr, restitution ); + public void setRestitution (float restitution) { + jniSetRestitution(addr, restitution); } - - private native void jniSetRestitution( long addr, float restitution ); -// /// Get the fixture's AABB. This AABB may be enlarge and/or stale. -// /// If you need a more accurate AABB, compute it using the shape and -// /// the body transform. -// const b2AABB& GetAABB() const; + private native void jniSetRestitution (long addr, float restitution); + +// /// Get the fixture's AABB. This AABB may be enlarge and/or stale. +// /// If you need a more accurate AABB, compute it using the shape and +// /// the body transform. +// const b2AABB& GetAABB() const; } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/FixtureDef.java b/gdx/src/com/badlogic/gdx/physics/box2d/FixtureDef.java index 81f6941d4..17f3e6a54 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/FixtureDef.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/FixtureDef.java @@ -1,49 +1,44 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; /** - * A fixture definition is used to create a fixture. This class defines an - * abstract fixture definition. You can reuse fixture definitions safely. + * A fixture definition is used to create a fixture. This class defines an abstract fixture definition. You can reuse fixture + * definitions safely. * @author mzechner - * + * */ -public class FixtureDef -{ +public class FixtureDef { /** - * The shape, this must be set. The shape will be cloned, so you - * can create the shape on the stack. + * The shape, this must be set. The shape will be cloned, so you can create the shape on the stack. */ public Shape shape; - + /** The friction coefficient, usually in the range [0,1]. **/ public float friction = 0.2f; - + /** The restitution (elasticity) usually in the range [0,1]. **/ public float restitution = 0; - + /** The density, usually in kg/m^2. **/ public float density = 0; - + /** - * A sensor shape collects contact information but never generates a collision - * response. + * A sensor shape collects contact information but never generates a collision response. */ public boolean isSensor = false; - + /** Contact filtering data. **/ public final Filter filter = new Filter(); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/Joint.java b/gdx/src/com/badlogic/gdx/physics/box2d/Joint.java index 79223e208..3f1ee2b65 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/Joint.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/Joint.java @@ -1,149 +1,143 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.JointDef.JointType; -public abstract class Joint -{ +public abstract class Joint { /** the address of the joint **/ protected long addr; - + /** world **/ private final World world; - + /** temporary float array **/ private final float[] tmp = new float[2]; - + /** joint edge a **/ protected JointEdge jointEdgeA; - + /** joint edge b **/ protected JointEdge jointEdgeB; - + /** * Constructs a new joint * @param addr the address of the joint */ - protected Joint( World world, long addr ) - { + protected Joint (World world, long addr) { this.world = world; this.addr = addr; } - + /** - * Get the type of the concrete joint. + * Get the type of the concrete joint. */ - public JointType getType() - { - int type = jniGetType( addr ); - if( type > 0 && type < JointType.valueTypes.length ) + public JointType getType () { + int type = jniGetType(addr); + if (type > 0 && type < JointType.valueTypes.length) return JointType.valueTypes[type]; else return JointType.Unknown; } - - private native int jniGetType( long addr ); + + private native int jniGetType (long addr); /** - * Get the first body attached to this joint. + * Get the first body attached to this joint. */ - public Body getBodyA() - { - return world.bodies.get( jniGetBodyA( addr ) ); - } - - private native long jniGetBodyA( long addr ); + public Body getBodyA () { + return world.bodies.get(jniGetBodyA(addr)); + } + + private native long jniGetBodyA (long addr); /** - * Get the second body attached to this joint. + * Get the second body attached to this joint. */ - public Body getBodyB() - { - return world.bodies.get( jniGetBodyB( addr ) ); - } - - private native long jniGetBodyB( long addr ); + public Body getBodyB () { + return world.bodies.get(jniGetBodyB(addr)); + } + + private native long jniGetBodyB (long addr); /** - * Get the anchor point on bodyA in world coordinates. - */ + * Get the anchor point on bodyA in world coordinates. + */ private final Vector2 anchorA = new Vector2(); - public Vector2 getAnchorA() - { - jniGetAnchorA( addr, tmp ); - anchorA.x = tmp[0]; anchorA.y = tmp[1]; + + public Vector2 getAnchorA () { + jniGetAnchorA(addr, tmp); + anchorA.x = tmp[0]; + anchorA.y = tmp[1]; return anchorA; } - private native void jniGetAnchorA( long addr, float[] anchorA ); - - /** + private native void jniGetAnchorA (long addr, float[] anchorA); + + /** * Get the anchor point on bodyB in world coordinates. - */ + */ private final Vector2 anchorB = new Vector2(); - public Vector2 getAnchorB() - { - jniGetAnchorB( addr, tmp ); - anchorB.x = tmp[0]; anchorB.y = tmp[1]; + + public Vector2 getAnchorB () { + jniGetAnchorB(addr, tmp); + anchorB.x = tmp[0]; + anchorB.y = tmp[1]; return anchorB; } - private native void jniGetAnchorB( long addr, float[] anchorB ); - + private native void jniGetAnchorB (long addr, float[] anchorB); + /** - * Get the reaction force on body2 at the joint anchor in Newtons. - */ - private final Vector2 reactionForce = new Vector2( ); - public Vector2 getReactionForce(float inv_dt) - { - jniGetReactionForce( addr, inv_dt, tmp ); - reactionForce.x = tmp[0]; reactionForce.y = tmp[1]; + * Get the reaction force on body2 at the joint anchor in Newtons. + */ + private final Vector2 reactionForce = new Vector2(); + + public Vector2 getReactionForce (float inv_dt) { + jniGetReactionForce(addr, inv_dt, tmp); + reactionForce.x = tmp[0]; + reactionForce.y = tmp[1]; return reactionForce; } - private native void jniGetReactionForce( long addr, float inv_dt, float[] reactionForce ); - + private native void jniGetReactionForce (long addr, float inv_dt, float[] reactionForce); + /** - * Get the reaction torque on body2 in N*m. + * Get the reaction torque on body2 in N*m. */ - public float getReactionTorque(float inv_dt) - { - return jniGetReactionTorque( addr, inv_dt ); + public float getReactionTorque (float inv_dt) { + return jniGetReactionTorque(addr, inv_dt); } - - private native float jniGetReactionTorque( long addr, float inv_dt ); -// /// Get the next joint the world joint list. -// b2Joint* GetNext(); + private native float jniGetReactionTorque (long addr, float inv_dt); + +// /// Get the next joint the world joint list. +// b2Joint* GetNext(); // -// /// Get the user data pointer. -// void* GetUserData() const; +// /// Get the user data pointer. +// void* GetUserData() const; // -// /// Set the user data pointer. -// void SetUserData(void* data); +// /// Set the user data pointer. +// void SetUserData(void* data); /** - * Short-cut function to determine if either body is inactive. + * Short-cut function to determine if either body is inactive. */ - public boolean isActive() - { - return jniIsActive( addr ); + public boolean isActive () { + return jniIsActive(addr); } - - private native boolean jniIsActive( long addr ); + + private native boolean jniIsActive (long addr); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/JointDef.java b/gdx/src/com/badlogic/gdx/physics/box2d/JointDef.java index 706d27e52..7321a03c7 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/JointDef.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/JointDef.java @@ -1,62 +1,45 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; -public class JointDef -{ - public enum JointType - { - Unknown(0), - RevoluteJoint(1), - PrismaticJoint(2), - DistanceJoint(3), - PulleyJoint(4), - MouseJoint(5), - GearJoint(6), - LineJoint(7), - WeldJoint(8), - FrictionJoint(9); - - public static JointType[] valueTypes = new JointType[] { Unknown, RevoluteJoint, - PrismaticJoint, DistanceJoint, - PulleyJoint, MouseJoint, - GearJoint, LineJoint, - WeldJoint, FrictionJoint} ; +public class JointDef { + public enum JointType { + Unknown(0), RevoluteJoint(1), PrismaticJoint(2), DistanceJoint(3), PulleyJoint(4), MouseJoint(5), GearJoint(6), LineJoint(7), WeldJoint( + 8), FrictionJoint(9); + + public static JointType[] valueTypes = new JointType[] {Unknown, RevoluteJoint, PrismaticJoint, DistanceJoint, PulleyJoint, + MouseJoint, GearJoint, LineJoint, WeldJoint, FrictionJoint}; private int value; - - JointType( int value ) - { + + JointType (int value) { this.value = value; } - - public int getValue( ) - { + + public int getValue () { return value; } } - + /** The joint type is set automatically for concrete joint types. **/ public JointType type = JointType.Unknown; - + /** The first attached body. **/ public Body bodyA = null; - + /** The second attached body **/ public Body bodyB = null; - + /** Set this flag to true if the attached bodies should collide. **/ public boolean collideConnected = false; } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/JointEdge.java b/gdx/src/com/badlogic/gdx/physics/box2d/JointEdge.java index 2464e0700..b370aacca 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/JointEdge.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/JointEdge.java @@ -1,34 +1,28 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; /** - * A joint edge is used to connect bodies and joints together - * in a joint graph where each body is a node and each joint - * is an edge. A joint edge belongs to a doubly linked list - * maintained in each attached body. Each joint has two joint - * nodes, one for each attached body. + * A joint edge is used to connect bodies and joints together in a joint graph where each body is a node and each joint is an + * edge. A joint edge belongs to a doubly linked list maintained in each attached body. Each joint has two joint nodes, one for + * each attached body. */ -public class JointEdge -{ +public class JointEdge { public final Body other; public final Joint joint; - - protected JointEdge( Body other, Joint joint ) - { + + protected JointEdge (Body other, Joint joint) { this.other = other; this.joint = joint; } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/MassData.java b/gdx/src/com/badlogic/gdx/physics/box2d/MassData.java index ba7630450..5bcdf5d59 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/MassData.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/MassData.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; import com.badlogic.gdx.math.Vector2; @@ -20,10 +18,9 @@ import com.badlogic.gdx.math.Vector2; /** * This holds the mass data computed for a shape. * @author mzechner - * + * */ -public class MassData -{ +public class MassData { /** The mass of the shape, usually in kilograms. **/ public float mass; diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/PolygonShape.java b/gdx/src/com/badlogic/gdx/physics/box2d/PolygonShape.java index dcfdaaff6..b452725c6 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/PolygonShape.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/PolygonShape.java @@ -1,123 +1,110 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; import com.badlogic.gdx.math.Vector2; -public class PolygonShape extends Shape -{ +public class PolygonShape extends Shape { /** * Constructs a new polygon */ - public PolygonShape( ) - { - addr = newPolygonShape( ); + public PolygonShape () { + addr = newPolygonShape(); } - - protected PolygonShape( long addr ) - { + + protected PolygonShape (long addr) { this.addr = addr; } - - private native long newPolygonShape( ); - + + private native long newPolygonShape (); + /** * {@inheritDoc} */ - @Override - public Type getType() - { + @Override public Type getType () { return Type.Polygon; } - + /** - * Copy vertices. This assumes the vertices define a convex polygon. - * It is assumed that the exterior is the the right of each edge. + * Copy vertices. This assumes the vertices define a convex polygon. It is assumed that the exterior is the the right of each + * edge. */ - public void set(Vector2[] vertices) - { - float[] verts = new float[vertices.length*2]; - for( int i = 0, j=0; i < vertices.length * 2; i+=2, j++ ) - { + public void set (Vector2[] vertices) { + float[] verts = new float[vertices.length * 2]; + for (int i = 0, j = 0; i < vertices.length * 2; i += 2, j++) { verts[i] = vertices[j].x; - verts[i+1] = vertices[j].y; + verts[i + 1] = vertices[j].y; } - jniSet( addr, verts ); + jniSet(addr, verts); } - - private native void jniSet( long addr, float[] verts ); + + private native void jniSet (long addr, float[] verts); /** * Build vertices to represent an axis-aligned box. * @param hx the half-width. * @param hy the half-height. */ - public void setAsBox(float hx, float hy) - { - jniSetAsBox( addr, hx, hy ); + public void setAsBox (float hx, float hy) { + jniSetAsBox(addr, hx, hy); } - - private native void jniSetAsBox( long addr, float hx, float hy ); + + private native void jniSetAsBox (long addr, float hx, float hy); /** - * Build vertices to represent an oriented box. + * Build vertices to represent an oriented box. * @param hx the half-width. * @param hy the half-height. * @param center the center of the box in local coordinates. * @param angle the rotation of the box in local coordinates. */ - public void setAsBox(float hx, float hy, Vector2 center, float angle) - { - jniSetAsBox( addr, hx, hy, center.x, center.y, angle ); + public void setAsBox (float hx, float hy, Vector2 center, float angle) { + jniSetAsBox(addr, hx, hy, center.x, center.y, angle); } - - private native void jniSetAsBox( long addr, float hx, float hy, float centerX, float centerY, float angle ); + + private native void jniSetAsBox (long addr, float hx, float hy, float centerX, float centerY, float angle); /** * Set this as a single edge. */ - public void setAsEdge(Vector2 v1, Vector2 v2) - { - jniSetAsEdge( addr, v1.x, v1.y, v2.x, v2.y ); + public void setAsEdge (Vector2 v1, Vector2 v2) { + jniSetAsEdge(addr, v1.x, v1.y, v2.x, v2.y); } - - private native void jniSetAsEdge( long addr, float v1x, float v1y, float v2x, float v2y ); - + + private native void jniSetAsEdge (long addr, float v1x, float v1y, float v2x, float v2y); + /** * @return the number of vertices */ - public int getVertexCount( ) - { - return jniGetVertexCount( addr ); + public int getVertexCount () { + return jniGetVertexCount(addr); } - - private native int jniGetVertexCount( long addr ); - + + private native int jniGetVertexCount (long addr); + /** * Returns the vertex at the given position. - * @param index the index of the vertex 0 <= index < getVertexCount( ) + * @param index the index of the vertex 0 <= index < getVertexCount( ) * @param vertex vertex */ private static float[] verts = new float[2]; - public void getVertex( int index, Vector2 vertex ) - { - jniGetVertex( addr, index, verts ); + + public void getVertex (int index, Vector2 vertex) { + jniGetVertex(addr, index, verts); vertex.x = verts[0]; vertex.y = verts[1]; } - - private native void jniGetVertex( long addr, int index, float[] verts ); + + private native void jniGetVertex (long addr, int index, float[] verts); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/QueryCallback.java b/gdx/src/com/badlogic/gdx/physics/box2d/QueryCallback.java index aecc2a90b..efe349042 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/QueryCallback.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/QueryCallback.java @@ -1,28 +1,25 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; /** - * Callback class for AABB queries. + * Callback class for AABB queries. */ -public interface QueryCallback -{ +public interface QueryCallback { /** - * Called for each fixture found in the query AABB. + * Called for each fixture found in the query AABB. * @return false to terminate the query. */ - public boolean reportFixture(Fixture fixture); + public boolean reportFixture (Fixture fixture); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/Shape.java b/gdx/src/com/badlogic/gdx/physics/box2d/Shape.java index de0228697..a234f4664 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/Shape.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/Shape.java @@ -1,104 +1,93 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; /** - * A shape is used for collision detection. You can create a shape however you like. - * Shapes used for simulation in b2World are created automatically when a b2Fixture - * is created. + * A shape is used for collision detection. You can create a shape however you like. Shapes used for simulation in b2World are + * created automatically when a b2Fixture is created. * - * NOTE: YOU NEED TO DISPOSE SHAPES AFTER YOU NO LONGER USE THEM! E.g. after calling - * body.createFixture(); + * NOTE: YOU NEED TO DISPOSE SHAPES AFTER YOU NO LONGER USE THEM! E.g. after calling body.createFixture(); * @author mzechner - * + * */ -public abstract class Shape -{ +public abstract class Shape { /** * Enum describing the type of a shape * @author mzechner - * + * */ - public enum Type - { - Circle, - Polygon, + public enum Type { + Circle, Polygon, }; - + /** the address of the shape **/ protected long addr; - + /** - * Get the type of this shape. You can use this to down cast to the concrete shape. + * Get the type of this shape. You can use this to down cast to the concrete shape. * @return the shape type. */ - public abstract Type getType(); - + public abstract Type getType (); + /** * Returns the radius of this shape */ - public float getRadius( ) - { - return jniGetRadius( addr ); + public float getRadius () { + return jniGetRadius(addr); } - - private native float jniGetRadius( long addr ); - + + private native float jniGetRadius (long addr); + /** * Sets the radius of this shape */ - public void setRadius( float radius ) - { - jniSetRadius( addr, radius ); + public void setRadius (float radius) { + jniSetRadius(addr, radius); } - - private native void jniSetRadius( long addr, float radius ); - + + private native void jniSetRadius (long addr, float radius); + /** - * Needs to be called when the shape is no longer used, e.g. after a fixture was - * created based on the shape. + * Needs to be called when the shape is no longer used, e.g. after a fixture was created based on the shape. */ - public void dispose( ) - { - jniDispose( addr ); + public void dispose () { + jniDispose(addr); } - - private native void jniDispose( long addr ); - - protected static native int jniGetType( long addr ); -// /// Test a point for containment in this shape. This only works for convex shapes. -// /// @param xf the shape world transform. -// /// @param p a point in world coordinates. -// virtual bool TestPoint(const b2Transform& xf, const b2Vec2& p) const = 0; + private native void jniDispose (long addr); + + protected static native int jniGetType (long addr); + +// /// Test a point for containment in this shape. This only works for convex shapes. +// /// @param xf the shape world transform. +// /// @param p a point in world coordinates. +// virtual bool TestPoint(const b2Transform& xf, const b2Vec2& p) const = 0; // -// /// Cast a ray against this shape. -// /// @param output the ray-cast results. -// /// @param input the ray-cast input parameters. -// /// @param transform the transform to be applied to the shape. -// virtual bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& transform) const = 0; +// /// Cast a ray against this shape. +// /// @param output the ray-cast results. +// /// @param input the ray-cast input parameters. +// /// @param transform the transform to be applied to the shape. +// virtual bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& transform) const = 0; // -// /// Given a transform, compute the associated axis aligned bounding box for this shape. -// /// @param aabb returns the axis aligned box. -// /// @param xf the world transform of the shape. -// virtual void ComputeAABB(b2AABB* aabb, const b2Transform& xf) const = 0; +// /// Given a transform, compute the associated axis aligned bounding box for this shape. +// /// @param aabb returns the axis aligned box. +// /// @param xf the world transform of the shape. +// virtual void ComputeAABB(b2AABB* aabb, const b2Transform& xf) const = 0; // -// /// Compute the mass properties of this shape using its dimensions and density. -// /// The inertia tensor is computed about the local origin. -// /// @param massData returns the mass data for this shape. -// /// @param density the density in kilograms per meter squared. -// virtual void ComputeMass(b2MassData* massData, float32 density) const = 0; +// /// Compute the mass properties of this shape using its dimensions and density. +// /// The inertia tensor is computed about the local origin. +// /// @param massData returns the mass data for this shape. +// /// @param density the density in kilograms per meter squared. +// virtual void ComputeMass(b2MassData* massData, float32 density) const = 0; } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/Transform.java b/gdx/src/com/badlogic/gdx/physics/box2d/Transform.java index 1ff447901..53d25497a 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/Transform.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/Transform.java @@ -1,69 +1,61 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; import com.badlogic.gdx.math.Vector2; /** - * Encodes a Box2D transform. We are lazy so we only store a 6 float wide - * array. First two floats are the position of the b2Transform struct. Next - * two floats are the b2Transform.R.col1 x and y coordinates. Final 2 floats - * are the b2Transform.R.col2 x and y coordinates; + * Encodes a Box2D transform. We are lazy so we only store a 6 float wide array. First two floats are the position of the + * b2Transform struct. Next two floats are the b2Transform.R.col1 x and y coordinates. Final 2 floats are the b2Transform.R.col2 x + * and y coordinates; * @author mzechner - * + * */ -public class Transform -{ +public class Transform { public static final int POS_X = 0; public static final int POS_Y = 1; public static final int COL1_X = 2; public static final int COL1_Y = 3; public static final int COL2_X = 4; public static final int COL2_Y = 5; - + public float[] vals = new float[6]; - private Vector2 position = new Vector2( ); - - public Transform( ) - { - + private Vector2 position = new Vector2(); + + public Transform () { + } - + /** - * Constructs a new Transform instance with the - * given position and angle + * Constructs a new Transform instance with the given position and angle * @param position the position * @param angle the angle in radians */ - public Transform( Vector2 position, float angle ) - { - setPosition( position ); - setRotation( angle ); + public Transform (Vector2 position, float angle) { + setPosition(position); + setRotation(angle); } - + /** * Transforms the given vector by this transform * @param v the vector */ - public Vector2 mul(Vector2 v) - { + public Vector2 mul (Vector2 v) { float x = vals[POS_X] + vals[COL1_X] * v.x + vals[COL2_X] * v.y; float y = vals[POS_Y] + vals[COL1_Y] * v.x + vals[COL2_Y] * v.y; - + v.x = x; v.y = y; return v; @@ -72,28 +64,27 @@ public class Transform /** * @return the position, modification of the vector has no effect on the Transform */ - public Vector2 getPosition( ) - { - return position.set( vals[0], vals[1] ); + public Vector2 getPosition () { + return position.set(vals[0], vals[1]); } /** * Sets the rotation of this transform * @param angle angle in radians */ - public void setRotation( float angle ) - { - float c = (float)Math.cos( angle ), s = (float)Math.sin( angle ); - vals[COL1_X] = c; vals[COL2_X] = -s; - vals[COL1_Y] = s; vals[COL2_Y] = c; + public void setRotation (float angle) { + float c = (float)Math.cos(angle), s = (float)Math.sin(angle); + vals[COL1_X] = c; + vals[COL2_X] = -s; + vals[COL1_Y] = s; + vals[COL2_Y] = c; } /** * Sets the position of this transform * @param pos the position */ - public void setPosition(Vector2 pos) - { + public void setPosition (Vector2 pos) { this.vals[POS_X] = pos.x; this.vals[POS_Y] = pos.y; } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/World.java b/gdx/src/com/badlogic/gdx/physics/box2d/World.java index 503464cb7..f69f5651f 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/World.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/World.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; import java.util.ArrayList; @@ -41,606 +39,442 @@ import com.badlogic.gdx.physics.box2d.joints.WeldJointDef; import com.badlogic.gdx.utils.LongHashMap; /** - * The world class manages all physics entities, dynamic simulation, - * and asynchronous queries. The world also contains efficient memory - * management facilities. + * The world class manages all physics entities, dynamic simulation, and asynchronous queries. The world also contains efficient + * memory management facilities. * @author mzechner */ -public class World -{ +public class World { /** the address of the world instance **/ private final long addr; - + /** all known bodies **/ protected final LongHashMap bodies = new LongHashMap(100); - + /** all known fixtures **/ protected final LongHashMap fixtures = new LongHashMap(100); - + /** all known joints **/ - protected final LongHashMap joints = new LongHashMap( 100 ); - + protected final LongHashMap joints = new LongHashMap(100); + /** Contact filter **/ protected ContactFilter contactFilter = null; - + /** Contact listener **/ - protected ContactListener contactListener = null; - + protected ContactListener contactListener = null; + /** * Construct a world object. * @param gravity the world gravity vector. * @param doSleep improve performance by not simulating inactive bodies. */ - public World( Vector2 gravity, boolean doSleep ) - { - addr = newWorld( gravity.x, gravity.y, doSleep ); - - for( int i = 0; i < 200; i++ ) - freeContacts.add( new Contact( this, 0 ) ); + public World (Vector2 gravity, boolean doSleep) { + addr = newWorld(gravity.x, gravity.y, doSleep); + + for (int i = 0; i < 200; i++) + freeContacts.add(new Contact(this, 0)); } - - private native long newWorld( float gravityX, float gravityY, boolean doSleep ); - + + private native long newWorld (float gravityX, float gravityY, boolean doSleep); + /** - * Register a destruction listener. The listener is owned by you and must - * remain in scope. + * Register a destruction listener. The listener is owned by you and must remain in scope. */ - public void setDestructionListener(DestructionListener listener) - { - + public void setDestructionListener (DestructionListener listener) { + } /** - * Register a contact filter to provide specific control over collision. - * Otherwise the default filter is used (b2_defaultFilter). The listener is - * owned by you and must remain in scope. - */ - public void setContactFilter(ContactFilter filter) - { + * Register a contact filter to provide specific control over collision. Otherwise the default filter is used + * (b2_defaultFilter). The listener is owned by you and must remain in scope. + */ + public void setContactFilter (ContactFilter filter) { this.contactFilter = filter; } /** - * Register a contact event listener. The listener is owned by you and must - * remain in scope. + * Register a contact event listener. The listener is owned by you and must remain in scope. */ - public void setContactListener(ContactListener listener) - { + public void setContactListener (ContactListener listener) { this.contactListener = listener; } /** - * Create a rigid body given a definition. No reference to the definition - * is retained. + * Create a rigid body given a definition. No reference to the definition is retained. * @warning This function is locked during callbacks. */ - public Body createBody(BodyDef def) - { - Body body = new Body( this, jniCreateBody( addr, - def.type.getValue(), - def.position.x, def.position.y, - def.angle, - def.linearVelocity.x, def.linearVelocity.y, - def.angularVelocity, - def.linearDamping, - def.angularDamping, - def.allowSleep, - def.awake, - def.fixedRotation, - def.bullet, - def.active, - def.inertiaScale) ); - this.bodies.put( body.addr, body ); + public Body createBody (BodyDef def) { + Body body = new Body(this, jniCreateBody(addr, def.type.getValue(), def.position.x, def.position.y, def.angle, + def.linearVelocity.x, def.linearVelocity.y, def.angularVelocity, def.linearDamping, def.angularDamping, def.allowSleep, + def.awake, def.fixedRotation, def.bullet, def.active, def.inertiaScale)); + this.bodies.put(body.addr, body); return body; } - - private native long jniCreateBody( long addr, - int type, - float positionX, float positionY, - float angle, - float linearVelocityX, float linearVelocityY, - float angularVelocity, - float linearDamping, - float angularDamping, - boolean allowSleep, - boolean awake, - boolean fixedRotation, - boolean bullet, - boolean active, - float intertiaScale ); + + private native long jniCreateBody (long addr, int type, float positionX, float positionY, float angle, float linearVelocityX, + float linearVelocityY, float angularVelocity, float linearDamping, float angularDamping, boolean allowSleep, boolean awake, + boolean fixedRotation, boolean bullet, boolean active, float intertiaScale); /** - * Destroy a rigid body given a definition. No reference to the definition - * is retained. This function is locked during callbacks. + * Destroy a rigid body given a definition. No reference to the definition is retained. This function is locked during + * callbacks. * @warning This automatically deletes all associated shapes and joints. * @warning This function is locked during callbacks. */ - public void destroyBody(Body body) - { - this.bodies.remove( body.addr ); - for( int i = 0; i < body.getFixtureList().size(); i++ ) + public void destroyBody (Body body) { + this.bodies.remove(body.addr); + for (int i = 0; i < body.getFixtureList().size(); i++) this.fixtures.remove(body.getFixtureList().get(i).addr); - for( int i = 0; i < body.getJointList().size(); i++ ) + for (int i = 0; i < body.getJointList().size(); i++) this.joints.remove(body.getJointList().get(i).joint.addr); - jniDestroyBody( addr, body.addr ); + jniDestroyBody(addr, body.addr); } - private native void jniDestroyBody( long addr, long bodyAddr ); - - /** - * Create a joint to constrain bodies together. No reference to the definition - * is retained. This may cause the connected bodies to cease colliding. + private native void jniDestroyBody (long addr, long bodyAddr); + + /** + * Create a joint to constrain bodies together. No reference to the definition is retained. This may cause the connected bodies + * to cease colliding. * @warning This function is locked during callbacks. */ - public Joint createJoint(JointDef def) - { - long jointAddr = createProperJoint( def ); + public Joint createJoint (JointDef def) { + long jointAddr = createProperJoint(def); Joint joint = null; - if( def.type == JointType.DistanceJoint ) - joint = new DistanceJoint( this, jointAddr ); - if( def.type == JointType.FrictionJoint ) - joint = new FrictionJoint( this, jointAddr ); - if( def.type == JointType.GearJoint ) - joint = new GearJoint( this, jointAddr ); - if( def.type == JointType.LineJoint ) - joint = new LineJoint( this, jointAddr ); - if( def.type == JointType.MouseJoint ) - joint = new MouseJoint( this, jointAddr ); - if( def.type == JointType.PrismaticJoint ) - joint = new PrismaticJoint( this, jointAddr); - if( def.type == JointType.PulleyJoint ) - joint = new PulleyJoint( this, jointAddr ); - if( def.type == JointType.RevoluteJoint ) - joint = new RevoluteJoint( this, jointAddr ); - if( def.type == JointType.WeldJoint ) - joint = new WeldJoint( this, jointAddr ); - if( joint != null ) - joints.put( joint.addr, joint ); - JointEdge jointEdgeA = new JointEdge( def.bodyB, joint ); - JointEdge jointEdgeB = new JointEdge( def.bodyA, joint ); + if (def.type == JointType.DistanceJoint) joint = new DistanceJoint(this, jointAddr); + if (def.type == JointType.FrictionJoint) joint = new FrictionJoint(this, jointAddr); + if (def.type == JointType.GearJoint) joint = new GearJoint(this, jointAddr); + if (def.type == JointType.LineJoint) joint = new LineJoint(this, jointAddr); + if (def.type == JointType.MouseJoint) joint = new MouseJoint(this, jointAddr); + if (def.type == JointType.PrismaticJoint) joint = new PrismaticJoint(this, jointAddr); + if (def.type == JointType.PulleyJoint) joint = new PulleyJoint(this, jointAddr); + if (def.type == JointType.RevoluteJoint) joint = new RevoluteJoint(this, jointAddr); + if (def.type == JointType.WeldJoint) joint = new WeldJoint(this, jointAddr); + if (joint != null) joints.put(joint.addr, joint); + JointEdge jointEdgeA = new JointEdge(def.bodyB, joint); + JointEdge jointEdgeB = new JointEdge(def.bodyA, joint); joint.jointEdgeA = jointEdgeA; joint.jointEdgeB = jointEdgeB; - def.bodyA.joints.add( jointEdgeA ); - def.bodyB.joints.add( jointEdgeB ); + def.bodyA.joints.add(jointEdgeA); + def.bodyB.joints.add(jointEdgeB); return joint; } - - private long createProperJoint( JointDef def ) - { - if( def.type == JointType.DistanceJoint ) - { + + private long createProperJoint (JointDef def) { + if (def.type == JointType.DistanceJoint) { DistanceJointDef d = (DistanceJointDef)def; - return jniCreateDistanceJoint( addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, - d.localAnchorA.x, d.localAnchorA.y, - d.localAnchorB.x, d.localAnchorB.y, - d.length, d.frequencyHz, d.dampingRatio); - } - if( def.type == JointType.FrictionJoint ) - { + return jniCreateDistanceJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, + d.localAnchorB.x, d.localAnchorB.y, d.length, d.frequencyHz, d.dampingRatio); + } + if (def.type == JointType.FrictionJoint) { FrictionJointDef d = (FrictionJointDef)def; - return jniCreateFrictionJoint( addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, - d.localAnchorA.x, d.localAnchorA.y, - d.localAnchorB.x, d.localAnchorB.y, - d.maxForce, - d.maxTorque ); + return jniCreateFrictionJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, + d.localAnchorB.x, d.localAnchorB.y, d.maxForce, d.maxTorque); } - if( def.type == JointType.GearJoint ) - { + if (def.type == JointType.GearJoint) { GearJointDef d = (GearJointDef)def; - return jniCreateGearJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, - d.joint1.addr, d.joint2.addr, d.ratio ); + return jniCreateGearJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.joint1.addr, d.joint2.addr, d.ratio); } - if( def.type == JointType.LineJoint ) - { + if (def.type == JointType.LineJoint) { LineJointDef d = (LineJointDef)def; - return jniCreateLineJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, - d.localAnchorA.x, d.localAnchorA.y, - d.localAnchorB.x, d.localAnchorB.y, - d.localAxisA.x, d.localAxisA.y, - d.enableLimit, - d.lowerTranslation, - d.upperTranslation, - d.enableMotor, - d.maxMotorForce, - d.motorSpeed ); - + return jniCreateLineJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, + d.localAnchorB.x, d.localAnchorB.y, d.localAxisA.x, d.localAxisA.y, d.enableLimit, d.lowerTranslation, + d.upperTranslation, d.enableMotor, d.maxMotorForce, d.motorSpeed); + } - if( def.type == JointType.MouseJoint ) - { + if (def.type == JointType.MouseJoint) { MouseJointDef d = (MouseJointDef)def; - return jniCreateMouseJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, - d.target.x, d.target.y, d.maxForce, d.frequencyHz, d.dampingRatio ); + return jniCreateMouseJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.target.x, d.target.y, d.maxForce, + d.frequencyHz, d.dampingRatio); } - if( def.type == JointType.PrismaticJoint ) - { + if (def.type == JointType.PrismaticJoint) { PrismaticJointDef d = (PrismaticJointDef)def; - return jniCreatePrismaticJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, - d.localAnchorA.x, d.localAnchorA.y, - d.localAnchorB.x, d.localAnchorB.y, - d.localAxis1.x, d.localAxis1.y, - d.referenceAngle, - d.enableLimit, - d.lowerTranslation, - d.upperTranslation, - d.enableMotor, - d.maxMotorForce, - d.motorSpeed ); + return jniCreatePrismaticJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, + d.localAnchorB.x, d.localAnchorB.y, d.localAxis1.x, d.localAxis1.y, d.referenceAngle, d.enableLimit, + d.lowerTranslation, d.upperTranslation, d.enableMotor, d.maxMotorForce, d.motorSpeed); } - if( def.type == JointType.PulleyJoint ) - { + if (def.type == JointType.PulleyJoint) { PulleyJointDef d = (PulleyJointDef)def; - return jniCreatePulleyJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, - d.groundAnchorA.x, d.groundAnchorA.y, - d.groundAnchorB.x, d.groundAnchorB.y, - d.localAnchorA.x, d.localAnchorA.y, - d.localAnchorB.x, d.localAnchorB.y, - d.lengthA, - d.maxLengthA, - d.lengthB, - d.maxLengthB, - d.ratio ); - + return jniCreatePulleyJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.groundAnchorA.x, d.groundAnchorA.y, + d.groundAnchorB.x, d.groundAnchorB.y, d.localAnchorA.x, d.localAnchorA.y, d.localAnchorB.x, d.localAnchorB.y, + d.lengthA, d.maxLengthA, d.lengthB, d.maxLengthB, d.ratio); + } - if( def.type == JointType.RevoluteJoint ) - { + if (def.type == JointType.RevoluteJoint) { RevoluteJointDef d = (RevoluteJointDef)def; - return jniCreateRevoluteJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, - d.localAnchorA.x, d.localAnchorA.y, - d.localAnchorB.x, d.localAnchorB.y, - d.referenceAngle, - d.enableLimit, - d.lowerAngle, - d.upperAngle, - d.enableMotor, - d.motorSpeed, - d.maxMotorTorque ); + return jniCreateRevoluteJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, + d.localAnchorB.x, d.localAnchorB.y, d.referenceAngle, d.enableLimit, d.lowerAngle, d.upperAngle, d.enableMotor, + d.motorSpeed, d.maxMotorTorque); } - if( def.type == JointType.WeldJoint ) - { + if (def.type == JointType.WeldJoint) { WeldJointDef d = (WeldJointDef)def; - return jniCreateWeldJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, - d.localAnchorA.x, d.localAnchorA.y, - d.localAnchorB.x, d.localAnchorB.y, - d.referenceAngle ); + return jniCreateWeldJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, + d.localAnchorB.x, d.localAnchorB.y, d.referenceAngle); } - + return 0; } - - private native long jniCreateDistanceJoint( long addr, long bodyA, long bodyB, boolean collideConnected, - float localAnchorAX, float localAnchorAY, - float localAnchorBX, float localAnchorBY, - float length, - float frequencyHz, - float dampingRatio ); - - private native long jniCreateFrictionJoint( long addr, long bodyA, long bodyB, boolean collideConnected, - float localAnchorAX, float localAnchorAY, - float localAnchorBX, float localAnchorBY, - float maxForce, - float maxTorque); - - private native long jniCreateGearJoint( long addr, long bodyA, long bodyB, boolean collideConnected, - long joint1, - long joint2, - float ratio - ); - - private native long jniCreateLineJoint( long addr, long bodyA, long bodyB, boolean collideConnected, - float localAnchorAX, float localAnchorAY, - float localAnchorBX, float localAnchorBY, - float localAxisAX, float localAxisAY, - boolean enableLimit, - float lowerTranslation, - float upperTranslation, - boolean enableMotor, - float maxMotorForce, - float motorSpeed ); - - private native long jniCreateMouseJoint( long addr, long bodyA, long bodyB, boolean collideConnected, - float targetX, float targetY, - float maxForce, - float frequencyHz, - float dampingRatio); - - private native long jniCreatePrismaticJoint( long addr, long bodyA, long bodyB, boolean collideConnected, - float localAnchorAX, float localAnchorAY, - float localAnchorBX, float localAnchorBY, - float localAxisAX, float localAxisAY, - float referenceAngle, - boolean enableLimit, - float lowerTranslation, - float upperTranslation, - boolean enableMotor, - float maxMotorForce, - float motorSpeed ); - - private native long jniCreatePulleyJoint( long addr, long bodyA, long bodyB, boolean collideConnected, - float groundAnchorAX, float groundAnchorAY, - float groundAnchorBX, float groundAnchorBY, - float localAnchorAX, float localAnchorAY, - float localAnchorBX, float localAnchorBY, - float lengthA, - float maxLengthA, - float lengthB, - float maxLengthB, - float ratio); - - private native long jniCreateRevoluteJoint( long addr, long bodyA, long bodyB, boolean collideConnected, - float localAnchorAX, float localAnchorAY, - float localAnchorBX, float localAnchorBY, - float referenceAngle, - boolean enableLimit, - float lowerAngle, - float upperAngle, - boolean enableMotor, - float motorSpeed, - float maxMotorTorque); - - private native long jniCreateWeldJoint( long addr, long bodyA, long bodyB, boolean collideConnected, - float localAnchorAX, float localAnchorAY, - float localAnchorBX, float localAnchorBY, - float referenceAngle); - + + private native long jniCreateDistanceJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, + float localAnchorAY, float localAnchorBX, float localAnchorBY, float length, float frequencyHz, float dampingRatio); + + private native long jniCreateFrictionJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, + float localAnchorAY, float localAnchorBX, float localAnchorBY, float maxForce, float maxTorque); + + private native long jniCreateGearJoint (long addr, long bodyA, long bodyB, boolean collideConnected, long joint1, long joint2, + float ratio); + + private native long jniCreateLineJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, + float localAnchorAY, float localAnchorBX, float localAnchorBY, float localAxisAX, float localAxisAY, boolean enableLimit, + float lowerTranslation, float upperTranslation, boolean enableMotor, float maxMotorForce, float motorSpeed); + + private native long jniCreateMouseJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float targetX, + float targetY, float maxForce, float frequencyHz, float dampingRatio); + + private native long jniCreatePrismaticJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, + float localAnchorAY, float localAnchorBX, float localAnchorBY, float localAxisAX, float localAxisAY, float referenceAngle, + boolean enableLimit, float lowerTranslation, float upperTranslation, boolean enableMotor, float maxMotorForce, + float motorSpeed); + + private native long jniCreatePulleyJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float groundAnchorAX, + float groundAnchorAY, float groundAnchorBX, float groundAnchorBY, float localAnchorAX, float localAnchorAY, + float localAnchorBX, float localAnchorBY, float lengthA, float maxLengthA, float lengthB, float maxLengthB, float ratio); + + private native long jniCreateRevoluteJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, + float localAnchorAY, float localAnchorBX, float localAnchorBY, float referenceAngle, boolean enableLimit, float lowerAngle, + float upperAngle, boolean enableMotor, float motorSpeed, float maxMotorTorque); + + private native long jniCreateWeldJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, + float localAnchorAY, float localAnchorBX, float localAnchorBY, float referenceAngle); + /** * Destroy a joint. This may cause the connected bodies to begin colliding. * @warning This function is locked during callbacks. */ - public void destroyJoint(Joint joint) - { + public void destroyJoint (Joint joint) { joints.remove(joint.addr); joint.jointEdgeA.other.joints.remove(joint.jointEdgeB); joint.jointEdgeB.other.joints.remove(joint.jointEdgeA); - jniDestroyJoint( addr, joint.addr ); + jniDestroyJoint(addr, joint.addr); } - - private native void jniDestroyJoint( long addr, long jointAddr ); + + private native void jniDestroyJoint (long addr, long jointAddr); /** - * Take a time step. This performs collision detection, integration, - * and constraint solution. + * Take a time step. This performs collision detection, integration, and constraint solution. * @param timeStep the amount of time to simulate, this should not vary. * @param velocityIterations for the velocity constraint solver. * @param positionIterations for the position constraint solver. */ - public void step( float timeStep, - int velocityIterations, - int positionIterations) - { - jniStep( addr, timeStep, velocityIterations, positionIterations ); + public void step (float timeStep, int velocityIterations, int positionIterations) { + jniStep(addr, timeStep, velocityIterations, positionIterations); } - - private native void jniStep( long addr, float timeStep, int velocityIterations, int positionIterations ); + + private native void jniStep (long addr, float timeStep, int velocityIterations, int positionIterations); /** - * Call this after you are done with time steps to clear the forces. You normally - * call this after each call to Step, unless you are performing sub-steps. By default, - * forces will be automatically cleared, so you don't need to call this function. + * Call this after you are done with time steps to clear the forces. You normally call this after each call to Step, unless you + * are performing sub-steps. By default, forces will be automatically cleared, so you don't need to call this function. * @see SetAutoClearForces */ - public void clearForces() - { + public void clearForces () { jniClearForces(addr); } - private native void jniClearForces(long addr); - + private native void jniClearForces (long addr); + /** * Enable/disable warm starting. For testing. */ - public void setWarmStarting(boolean flag) - { + public void setWarmStarting (boolean flag) { jniSetWarmStarting(addr, flag); } - private native void jniSetWarmStarting( long addr, boolean flag ); - + private native void jniSetWarmStarting (long addr, boolean flag); + /** * Enable/disable continuous physics. For testing. */ - public void setContinuousPhysics(boolean flag) - { + public void setContinuousPhysics (boolean flag) { jniSetContiousPhysics(addr, flag); } - - private native void jniSetContiousPhysics( long addr, boolean flag ); + + private native void jniSetContiousPhysics (long addr, boolean flag); /** * Get the number of broad-phase proxies. */ - public int getProxyCount() - { + public int getProxyCount () { return jniGetProxyCount(addr); } - - private native int jniGetProxyCount( long addr ); + + private native int jniGetProxyCount (long addr); /** * Get the number of bodies. */ - public int getBodyCount() - { + public int getBodyCount () { return jniGetBodyCount(addr); } - - private native int jniGetBodyCount( long addr ); + + private native int jniGetBodyCount (long addr); /** * Get the number of joints. */ - public int getJointCount() - { + public int getJointCount () { return jniGetJointcount(addr); } - - private native int jniGetJointcount( long addr ); - + + private native int jniGetJointcount (long addr); + /** * Get the number of contacts (each may have 0 or more contact points). */ - public int getContactCount() - { - return jniGetContactCount( addr ); + public int getContactCount () { + return jniGetContactCount(addr); } - private native int jniGetContactCount( long addr ); - + private native int jniGetContactCount (long addr); + /** * Change the global gravity vector. */ - public void setGravity(Vector2 gravity) - { - jniSetGravity( addr, gravity.x, gravity.y ); + public void setGravity (Vector2 gravity) { + jniSetGravity(addr, gravity.x, gravity.y); } - - private native void jniSetGravity( long addr, float gravityX, float gravityY ); - + + private native void jniSetGravity (long addr, float gravityX, float gravityY); + /** * Get the global gravity vector. */ final float[] tmpGravity = new float[2]; - final Vector2 gravity = new Vector2( ); - public Vector2 getGravity() - { - jniGetGravity( addr, tmpGravity ); - gravity.x = tmpGravity[0]; gravity.y = tmpGravity[1]; + final Vector2 gravity = new Vector2(); + + public Vector2 getGravity () { + jniGetGravity(addr, tmpGravity); + gravity.x = tmpGravity[0]; + gravity.y = tmpGravity[1]; return gravity; } - private native void jniGetGravity( long addr, float[] gravity ); - + private native void jniGetGravity (long addr, float[] gravity); + /** * Is the world locked (in the middle of a time step). - */ - public boolean isLocked() - { - return jniIsLocked( addr ); + */ + public boolean isLocked () { + return jniIsLocked(addr); } - private native boolean jniIsLocked( long addr ); - + private native boolean jniIsLocked (long addr); + /** - * Set flag to control automatic clearing of forces after each time step. + * Set flag to control automatic clearing of forces after each time step. */ - public void setAutoClearForces(boolean flag) - { + public void setAutoClearForces (boolean flag) { jniSetAutoClearForces(addr, flag); } - private native void jniSetAutoClearForces( long addr, boolean flag ); - + private native void jniSetAutoClearForces (long addr, boolean flag); + /** - * Get the flag that controls automatic clearing of forces after each time step. + * Get the flag that controls automatic clearing of forces after each time step. */ - public boolean getAutoClearForces() - { - return jniGetAutoClearForces( addr ); + public boolean getAutoClearForces () { + return jniGetAutoClearForces(addr); } - - private native boolean jniGetAutoClearForces( long addr ); - + + private native boolean jniGetAutoClearForces (long addr); + /** - * Query the world for all fixtures that potentially overlap the - * provided AABB. + * Query the world for all fixtures that potentially overlap the provided AABB. * @param callback a user implemented callback class. * @param aabb the query box. */ - public void QueryAABB(QueryCallback callback, float lowerX, float lowerY, float upperX, float upperY ) - { + public void QueryAABB (QueryCallback callback, float lowerX, float lowerY, float upperX, float upperY) { queryCallback = callback; - jniQueryAABB( addr, lowerX, lowerY, upperX, upperY ); + jniQueryAABB(addr, lowerX, lowerY, upperX, upperY); } - + private QueryCallback queryCallback = null;; - - private native void jniQueryAABB( long addr, float lowX, float lowY, float upX, float upY ); - + + private native void jniQueryAABB (long addr, float lowX, float lowY, float upX, float upY); + // -// /// Ray-cast the world for all fixtures in the path of the ray. Your callback -// /// controls whether you get the closest point, any point, or n-points. -// /// The ray-cast ignores shapes that contain the starting point. -// /// @param callback a user implemented callback class. -// /// @param point1 the ray starting point -// /// @param point2 the ray ending point -// void RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const; +// /// Ray-cast the world for all fixtures in the path of the ray. Your callback +// /// controls whether you get the closest point, any point, or n-points. +// /// The ray-cast ignores shapes that contain the starting point. +// /// @param callback a user implemented callback class. +// /// @param point1 the ray starting point +// /// @param point2 the ray ending point +// void RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const; // -// /// Get the world contact list. With the returned contact, use b2Contact::GetNext to get -// /// the next contact in the world list. A NULL contact indicates the end of the list. -// /// @return the head of the world contact list. -// /// @warning contacts are -// b2Contact* GetContactList(); - - private long[] contactAddrs = new long[200]; - private final ArrayList contacts = new ArrayList( ); - private final ArrayList freeContacts = new ArrayList( ); - - public List getContactList( ) - { +// /// Get the world contact list. With the returned contact, use b2Contact::GetNext to get +// /// the next contact in the world list. A NULL contact indicates the end of the list. +// /// @return the head of the world contact list. +// /// @warning contacts are +// b2Contact* GetContactList(); + + private long[] contactAddrs = new long[200]; + private final ArrayList contacts = new ArrayList(); + private final ArrayList freeContacts = new ArrayList(); + + public List getContactList () { int numContacts = getContactCount(); - if( numContacts > contactAddrs.length ) - contactAddrs = new long[numContacts]; - if( numContacts > freeContacts.size() ) - { + if (numContacts > contactAddrs.length) contactAddrs = new long[numContacts]; + if (numContacts > freeContacts.size()) { int freeConts = freeContacts.size(); - for( int i = 0; i < numContacts - freeConts; i++ ) - freeContacts.add( new Contact( this, 0 ) ); + for (int i = 0; i < numContacts - freeConts; i++) + freeContacts.add(new Contact(this, 0)); } - jniGetContactList( addr, contactAddrs ); - - contacts.clear(); - for( int i = 0; i < numContacts; i++ ) - { + jniGetContactList(addr, contactAddrs); + + contacts.clear(); + for (int i = 0; i < numContacts; i++) { Contact contact = freeContacts.get(i); contact.addr = contactAddrs[i]; - contacts.add( contact ); + contacts.add(contact); } - + return contacts; } - + /** * @return all bodies currently in the simulation */ - public Iterable getBodies( ) - { + public Iterable getBodies () { return bodies.values(); } - + /** * @return all joints currently in the simulation */ - public Iterable getJoints( ) - { + public Iterable getJoints () { return joints.values(); } - - private native void jniGetContactList( long addr, long[] contacts ); - - public void dispose( ) - { - jniDispose( addr ); + + private native void jniGetContactList (long addr, long[] contacts); + + public void dispose () { + jniDispose(addr); } - - private native void jniDispose( long addr ); - + + private native void jniDispose (long addr); + /** * Internal method called from JNI in case a contact happens * @param fixtureA * @param fixtureB * @return */ - @SuppressWarnings("unused") - private boolean contactFilter( long fixtureA, long fixtureB ) - { - if( contactFilter != null ) - return contactFilter.shouldCollide( fixtures.get(fixtureA), fixtures.get(fixtureB)); - else - { + @SuppressWarnings("unused") private boolean contactFilter (long fixtureA, long fixtureB) { + if (contactFilter != null) + return contactFilter.shouldCollide(fixtures.get(fixtureA), fixtures.get(fixtureB)); + else { Filter filterA = fixtures.get(fixtureA).getFilterData(); - Filter filterB = fixtures.get(fixtureB).getFilterData(); + Filter filterB = fixtures.get(fixtureB).getFilterData(); - if (filterA.groupIndex == filterB.groupIndex && filterA.groupIndex != 0) - { + if (filterA.groupIndex == filterB.groupIndex && filterA.groupIndex != 0) { return filterA.groupIndex > 0; } @@ -648,31 +482,23 @@ public class World return collide; } } - - private final Contact contact = new Contact(this, 0 ); - - @SuppressWarnings("unused") - private void beginContact( long contactAddr ) - { - contact.addr = contactAddr; - if( contactListener != null ) - contactListener.beginContact( contact ); + + private final Contact contact = new Contact(this, 0); + + @SuppressWarnings("unused") private void beginContact (long contactAddr) { + contact.addr = contactAddr; + if (contactListener != null) contactListener.beginContact(contact); } - - @SuppressWarnings("unused") - private void endContact( long contactAddr ) - { + + @SuppressWarnings("unused") private void endContact (long contactAddr) { contact.addr = contactAddr; - contact.GetWorldManifold(); - if( contactListener != null ) - contactListener.endContact( contact ); + contact.GetWorldManifold(); + if (contactListener != null) contactListener.endContact(contact); } - - @SuppressWarnings("unused") - private boolean reportFixture( long addr ) - { - if( queryCallback != null ) - return queryCallback.reportFixture( fixtures.get( addr ) ); + + @SuppressWarnings("unused") private boolean reportFixture (long addr) { + if (queryCallback != null) + return queryCallback.reportFixture(fixtures.get(addr)); else return false; } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/WorldManifold.java b/gdx/src/com/badlogic/gdx/physics/box2d/WorldManifold.java index 184f9a5ac..f63b4cbbe 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/WorldManifold.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/WorldManifold.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; import com.badlogic.gdx.math.Vector2; @@ -20,38 +18,33 @@ import com.badlogic.gdx.math.Vector2; /** * This is used to compute the current state of a contact manifold. */ -public class WorldManifold -{ +public class WorldManifold { protected final Vector2 normal = new Vector2(); - protected final Vector2[] points = { new Vector2(), new Vector2() }; + protected final Vector2[] points = {new Vector2(), new Vector2()}; protected int numContactPoints; - - protected WorldManifold( ) - { + + protected WorldManifold () { } - + /** * Returns the normal of this manifold */ - public Vector2 getNormal( ) - { + public Vector2 getNormal () { return normal; - } - + } + /** - * Returns the contact points of this manifold. Use getNumberOfContactPoints - * to determine how many contact points there are (0,1 or 2) + * Returns the contact points of this manifold. Use getNumberOfContactPoints to determine how many contact points there are + * (0,1 or 2) */ - public Vector2[] getPoints( ) - { + public Vector2[] getPoints () { return points; - } - + } + /** * @return the number of contact points */ - public int getNumberOfContactPoints( ) - { + public int getNumberOfContactPoints () { return numContactPoints; - } + } } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/joints/DistanceJoint.java b/gdx/src/com/badlogic/gdx/physics/box2d/joints/DistanceJoint.java index b6f02c72a..1ab495186 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/DistanceJoint.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/DistanceJoint.java @@ -1,94 +1,81 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.World; /** - * A distance joint constrains two points on two bodies - * to remain at a fixed distance from each other. You can view - * this as a massless, rigid rod. + * A distance joint constrains two points on two bodies to remain at a fixed distance from each other. You can view this as a + * massless, rigid rod. */ -public class DistanceJoint extends Joint -{ - public DistanceJoint(World world, long addr) - { - super( world, addr); +public class DistanceJoint extends Joint { + public DistanceJoint (World world, long addr) { + super(world, addr); } /** - * Set/get the natural length. - * Manipulating the length can lead to non-physical behavior when the frequency is zero. + * Set/get the natural length. Manipulating the length can lead to non-physical behavior when the frequency is zero. */ - public void setLength(float length) - { - jniSetLength( addr, length ); + public void setLength (float length) { + jniSetLength(addr, length); } - - private native void jniSetLength( long addr, float length ); - + + private native void jniSetLength (long addr, float length); + /** - * Set/get the natural length. - * Manipulating the length can lead to non-physical behavior when the frequency is zero. + * Set/get the natural length. Manipulating the length can lead to non-physical behavior when the frequency is zero. */ - public float getLength() - { - return jniGetLength( addr ); + public float getLength () { + return jniGetLength(addr); } - - private native float jniGetLength( long addr ); + + private native float jniGetLength (long addr); /** * Set/get frequency in Hz. */ - public void setFrequency(float hz) - { - jniSetFrequency( addr, hz ); + public void setFrequency (float hz) { + jniSetFrequency(addr, hz); } - - private native void jniSetFrequency( long addr, float hz ); - + + private native void jniSetFrequency (long addr, float hz); + /** * Set/get frequency in Hz. */ - public float getFrequency() - { - return jniGetFrequency( addr ); + public float getFrequency () { + return jniGetFrequency(addr); } - - private native float jniGetFrequency( long addr ); + + private native float jniGetFrequency (long addr); /** - * Set/get damping ratio. + * Set/get damping ratio. */ - public void setDampingRatio(float ratio) - { - jniSetDampingRatio( addr, ratio ); + public void setDampingRatio (float ratio) { + jniSetDampingRatio(addr, ratio); } - - private native void jniSetDampingRatio( long addr, float ratio ); - + + private native void jniSetDampingRatio (long addr, float ratio); + /** - * Set/get damping ratio. + * Set/get damping ratio. */ - public float getDampingRatio() - { - return jniGetDampingRatio( addr ); + public float getDampingRatio () { + return jniGetDampingRatio(addr); } - - private native float jniGetDampingRatio( long addr ); + + private native float jniGetDampingRatio (long addr); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/joints/DistanceJointDef.java b/gdx/src/com/badlogic/gdx/physics/box2d/joints/DistanceJointDef.java index d48af06b0..274e5cb50 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/DistanceJointDef.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/DistanceJointDef.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.math.Vector2; @@ -20,53 +18,47 @@ import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.JointDef; /** - * Distance joint definition. This requires defining an - * anchor point on both bodies and the non-zero length of the - * distance joint. The definition uses local anchor points - * so that the initial configuration can violate the constraint - * slightly. This helps when saving and loading a game. + * Distance joint definition. This requires defining an anchor point on both bodies and the non-zero length of the distance joint. + * The definition uses local anchor points so that the initial configuration can violate the constraint slightly. This helps when + * saving and loading a game. * @warning Do not use a zero or short length. */ -public class DistanceJointDef extends JointDef -{ - public DistanceJointDef( ) - { +public class DistanceJointDef extends JointDef { + public DistanceJointDef () { type = JointType.DistanceJoint; } - + /** - * Initialize the bodies, anchors, and length using the world - * anchors. + * Initialize the bodies, anchors, and length using the world anchors. */ - public void initialize( Body bodyA, Body bodyB, Vector2 anchorA, Vector2 anchorB ) - { + public void initialize (Body bodyA, Body bodyB, Vector2 anchorA, Vector2 anchorB) { this.bodyA = bodyA; this.bodyB = bodyB; - this.localAnchorA.set( bodyA.getLocalPoint( anchorA ) ); - this.localAnchorB.set( bodyB.getLocalPoint( anchorB ) ); + this.localAnchorA.set(bodyA.getLocalPoint(anchorA)); + this.localAnchorB.set(bodyB.getLocalPoint(anchorB)); this.length = anchorA.dst(anchorB); } - + /** - * The local anchor point relative to body1's origin. + * The local anchor point relative to body1's origin. */ public final Vector2 localAnchorA = new Vector2(); - + /** - * The local anchor point relative to body2's origin. + * The local anchor point relative to body2's origin. */ public final Vector2 localAnchorB = new Vector2(); - + /** - * The natural length between the anchor points. + * The natural length between the anchor points. */ public float length = 1; - + /** - * The mass-spring-damper frequency in Hertz. + * The mass-spring-damper frequency in Hertz. */ public float frequencyHz = 0; - + /** * The damping ratio. 0 = no damping, 1 = critical damping. */ diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/joints/FrictionJoint.java b/gdx/src/com/badlogic/gdx/physics/box2d/joints/FrictionJoint.java index 75a975f18..caa96a6fc 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/FrictionJoint.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/FrictionJoint.java @@ -1,71 +1,62 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.World; /** - * Friction joint. This is used for top-down friction. - * It provides 2D translational friction and angular friction. + * Friction joint. This is used for top-down friction. It provides 2D translational friction and angular friction. */ -public class FrictionJoint extends Joint -{ - public FrictionJoint( World world, long addr) - { - super(world, addr); +public class FrictionJoint extends Joint { + public FrictionJoint (World world, long addr) { + super(world, addr); } - + /** * Set the maximum friction force in N. */ - public void setMaxForce(float force) - { - jniSetMaxForce( addr, force ); + public void setMaxForce (float force) { + jniSetMaxForce(addr, force); } - - private native void jniSetMaxForce( long ddr, float force ); + + private native void jniSetMaxForce (long ddr, float force); /** - * Get the maximum friction force in N. + * Get the maximum friction force in N. */ - public float getMaxForce() - { - return jniGetMaxForce( addr ); + public float getMaxForce () { + return jniGetMaxForce(addr); } - - private native float jniGetMaxForce( long addr ); + + private native float jniGetMaxForce (long addr); /** * Set the maximum friction torque in N*m. */ - public void setMaxTorque(float torque) - { - jniSetMaxTorque( addr, torque ); + public void setMaxTorque (float torque) { + jniSetMaxTorque(addr, torque); } - - private native void jniSetMaxTorque( long addr, float torque ); + + private native void jniSetMaxTorque (long addr, float torque); /** - * Get the maximum friction torque in N*m. + * Get the maximum friction torque in N*m. */ - public float getMaxTorque() - { - return jniGetMaxTorque( addr ); + public float getMaxTorque () { + return jniGetMaxTorque(addr); } - - private native float jniGetMaxTorque( long addr ); + + private native float jniGetMaxTorque (long addr); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/joints/FrictionJointDef.java b/gdx/src/com/badlogic/gdx/physics/box2d/joints/FrictionJointDef.java index 79dc5db0f..6a26e0497 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/FrictionJointDef.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/FrictionJointDef.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.math.Vector2; @@ -20,44 +18,41 @@ import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.JointDef; /** - * Friction joint definition. + * Friction joint definition. */ -public class FrictionJointDef extends JointDef{ - - public FrictionJointDef( ) - { +public class FrictionJointDef extends JointDef { + + public FrictionJointDef () { type = JointType.FrictionJoint; } - + /** - * Initialize the bodies, anchors, axis, and reference angle using the world - * anchor and world axis. + * Initialize the bodies, anchors, axis, and reference angle using the world anchor and world axis. */ - public void initialize(Body bodyA, Body bodyB, Vector2 anchor) - { + public void initialize (Body bodyA, Body bodyB, Vector2 anchor) { this.bodyA = bodyA; this.bodyB = bodyB; - localAnchorA.set( bodyA.getLocalPoint( anchor ) ); - localAnchorB.set( bodyB.getLocalPoint( anchor ) ); + localAnchorA.set(bodyA.getLocalPoint(anchor)); + localAnchorB.set(bodyB.getLocalPoint(anchor)); } /** - * The local anchor point relative to bodyA's origin. + * The local anchor point relative to bodyA's origin. */ public final Vector2 localAnchorA = new Vector2(); /** - * The local anchor point relative to bodyB's origin. + * The local anchor point relative to bodyB's origin. */ public final Vector2 localAnchorB = new Vector2(); /** - * The maximum friction force in N. + * The maximum friction force in N. */ public float maxForce = 0; /** - * The maximum friction torque in N-m. + * The maximum friction torque in N-m. */ public float maxTorque = 0; } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/joints/GearJoint.java b/gdx/src/com/badlogic/gdx/physics/box2d/joints/GearJoint.java index d60820ead..f25fd2bb5 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/GearJoint.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/GearJoint.java @@ -1,58 +1,48 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.World; /** - * A gear joint is used to connect two joints together. Either joint - * can be a revolute or prismatic joint. You specify a gear ratio - * to bind the motions together: - * coordinate1 + ratio * coordinate2 = constant - * The ratio can be negative or positive. If one joint is a revolute joint - * and the other joint is a prismatic joint, then the ratio will have units - * of length or units of 1/length. - * @warning The revolute and prismatic joints must be attached to - * fixed bodies (which must be body1 on those joints). + * A gear joint is used to connect two joints together. Either joint can be a revolute or prismatic joint. You specify a gear + * ratio to bind the motions together: coordinate1 + ratio * coordinate2 = constant The ratio can be negative or positive. If one + * joint is a revolute joint and the other joint is a prismatic joint, then the ratio will have units of length or units of + * 1/length. + * @warning The revolute and prismatic joints must be attached to fixed bodies (which must be body1 on those joints). */ -public class GearJoint extends Joint -{ - public GearJoint(World world, long addr) - { - super(world, addr); +public class GearJoint extends Joint { + public GearJoint (World world, long addr) { + super(world, addr); } - + /** - * Set/Get the gear ratio. + * Set/Get the gear ratio. */ - public void setRatio(float ratio) - { - jniSetRatio( addr, ratio ); + public void setRatio (float ratio) { + jniSetRatio(addr, ratio); } - - private native void jniSetRatio( long addr, float ratio ); - + + private native void jniSetRatio (long addr, float ratio); + /** - * Set/Get the gear ratio. + * Set/Get the gear ratio. */ - public float getRatio() - { - return jniGetRatio( addr ); + public float getRatio () { + return jniGetRatio(addr); } - - private native float jniGetRatio( long addr ); + + private native float jniGetRatio (long addr); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/joints/GearJointDef.java b/gdx/src/com/badlogic/gdx/physics/box2d/joints/GearJointDef.java index 6a8a5c0bd..11386934e 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/GearJointDef.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/GearJointDef.java @@ -1,47 +1,42 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.JointDef; /** - * Gear joint definition. This definition requires two existing - * revolute or prismatic joints (any combination will work). - * The provided joints must attach a dynamic body to a static body. + * Gear joint definition. This definition requires two existing revolute or prismatic joints (any combination will work). The + * provided joints must attach a dynamic body to a static body. */ -public class GearJointDef extends JointDef -{ - public GearJointDef( ) - { +public class GearJointDef extends JointDef { + public GearJointDef () { type = JointType.GearJoint; } - + /** - * The first revolute/prismatic joint attached to the gear joint. + * The first revolute/prismatic joint attached to the gear joint. */ public Joint joint1 = null; /** - * The second revolute/prismatic joint attached to the gear joint. + * The second revolute/prismatic joint attached to the gear joint. */ public Joint joint2 = null; /** - * The gear ratio. + * The gear ratio. * @see GearJoint for explanation. */ public float ratio = 1; diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/joints/LineJoint.java b/gdx/src/com/badlogic/gdx/physics/box2d/joints/LineJoint.java index e0d03ffd2..e54bc72ba 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/LineJoint.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/LineJoint.java @@ -1,174 +1,153 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.World; /** - * A line joint. This joint provides two degrees of freedom: translation - * along an axis fixed in body1 and rotation in the plane. You can use a - * joint limit to restrict the range of motion and a joint motor to drive - * the motion or to model joint friction. + * A line joint. This joint provides two degrees of freedom: translation along an axis fixed in body1 and rotation in the plane. + * You can use a joint limit to restrict the range of motion and a joint motor to drive the motion or to model joint friction. */ -public class LineJoint extends Joint -{ - public LineJoint(World world, long addr) - { - super(world, addr); +public class LineJoint extends Joint { + public LineJoint (World world, long addr) { + super(world, addr); } - + /** - * Get the current joint translation, usually in meters. + * Get the current joint translation, usually in meters. */ - public float getJointTranslation() - { - return jniGetJointTranslation( addr ); + public float getJointTranslation () { + return jniGetJointTranslation(addr); } - - private native float jniGetJointTranslation( long addr ); + + private native float jniGetJointTranslation (long addr); /** - * Get the current joint translation speed, usually in meters per second. + * Get the current joint translation speed, usually in meters per second. */ - public float getJointSpeed() - { - return jniGetJointSpeed( addr ); + public float getJointSpeed () { + return jniGetJointSpeed(addr); } - - private native float jniGetJointSpeed( long addr ); + + private native float jniGetJointSpeed (long addr); /** * Is the joint limit enabled? */ - public boolean isLimitEnabled() - { - return jniIsLimitEnabled( addr ); + public boolean isLimitEnabled () { + return jniIsLimitEnabled(addr); } - - private native boolean jniIsLimitEnabled( long addr ); + + private native boolean jniIsLimitEnabled (long addr); /** * Enable/disable the joint limit. */ - public void enableLimit(boolean flag) - { - jniEnableLimit( addr, flag ); + public void enableLimit (boolean flag) { + jniEnableLimit(addr, flag); } - private native void jniEnableLimit( long addr, boolean flag ); - + private native void jniEnableLimit (long addr, boolean flag); + /** - * Get the lower joint limit, usually in meters. + * Get the lower joint limit, usually in meters. */ - public float getLowerLimit() - { - return jniGetLowerLimit( addr ); + public float getLowerLimit () { + return jniGetLowerLimit(addr); } - private native float jniGetLowerLimit( long addr ); - + private native float jniGetLowerLimit (long addr); + /** - * Get the upper joint limit, usually in meters. + * Get the upper joint limit, usually in meters. */ - public float getUpperLimit() - { - return jniGetUpperLimit( addr ); + public float getUpperLimit () { + return jniGetUpperLimit(addr); } - - private native float jniGetUpperLimit( long addr ); + + private native float jniGetUpperLimit (long addr); /** - * Set the joint limits, usually in meters. + * Set the joint limits, usually in meters. */ - public void setLimits(float lower, float upper) - { - jniSetLimits( addr, lower, upper ); + public void setLimits (float lower, float upper) { + jniSetLimits(addr, lower, upper); } - private native void jniSetLimits( long addr, float lower, float upper ); - + private native void jniSetLimits (long addr, float lower, float upper); + /** * Is the joint motor enabled? */ - public boolean isMotorEnabled() - { - return jniIsMotorEnabled( addr ); + public boolean isMotorEnabled () { + return jniIsMotorEnabled(addr); } - - private native boolean jniIsMotorEnabled( long addr ); + + private native boolean jniIsMotorEnabled (long addr); /** * Enable/disable the joint motor. */ - public void enableMotor(boolean flag) - { - jniEnableMotor( addr, flag ); + public void enableMotor (boolean flag) { + jniEnableMotor(addr, flag); } - - private native void jniEnableMotor( long addr, boolean flag ); + + private native void jniEnableMotor (long addr, boolean flag); /** - * Set the motor speed, usually in meters per second. + * Set the motor speed, usually in meters per second. */ - public void setMotorSpeed(float speed) - { - jniSetMotorSpeed( addr, speed ); + public void setMotorSpeed (float speed) { + jniSetMotorSpeed(addr, speed); } - - private native void jniSetMotorSpeed( long addr, float speed ); - /** + private native void jniSetMotorSpeed (long addr, float speed); + + /** * Get the motor speed, usually in meters per second. */ - public float getMotorSpeed() - { - return jniGetMotorSpeed( addr ); + public float getMotorSpeed () { + return jniGetMotorSpeed(addr); } - - private native float jniGetMotorSpeed( long addr ); - /** + private native float jniGetMotorSpeed (long addr); + + /** * Set/Get the maximum motor force, usually in N. */ - public void setMaxMotorForce(float force) - { - jniSetMaxMotorForce( addr, force ); + public void setMaxMotorForce (float force) { + jniSetMaxMotorForce(addr, force); } - - private native void jniSetMaxMotorForce( long addr, float force ); - - /** - * Set/Get the maximum motor force, usually in N. - * FIXME returns 0 at the moment due to a linking problem. + + private native void jniSetMaxMotorForce (long addr, float force); + + /** + * Set/Get the maximum motor force, usually in N. FIXME returns 0 at the moment due to a linking problem. */ - public float getMaxMotorForce() - { - return jniGetMaxMotorForce( addr ); + public float getMaxMotorForce () { + return jniGetMaxMotorForce(addr); } - - private native float jniGetMaxMotorForce( long addr ); + + private native float jniGetMaxMotorForce (long addr); /** * Get the current motor force, usually in N. */ - public float getMotorForce() - { - return jniGetMotorForce( addr ); + public float getMotorForce () { + return jniGetMotorForce(addr); } - - private native float jniGetMotorForce( long addr ); + + private native float jniGetMotorForce (long addr); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/joints/LineJointDef.java b/gdx/src/com/badlogic/gdx/physics/box2d/joints/LineJointDef.java index c6e77af5a..15cd8cf4d 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/LineJointDef.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/LineJointDef.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.math.Vector2; @@ -20,75 +18,69 @@ import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.JointDef; /** - * Line joint definition. This requires defining a line of - * motion using an axis and an anchor point. The definition uses local - * anchor points and a local axis so that the initial configuration - * can violate the constraint slightly. The joint translation is zero - * when the local anchor points coincide in world space. Using local - * anchors and a local axis helps when saving and loading a game. + * Line joint definition. This requires defining a line of motion using an axis and an anchor point. The definition uses local + * anchor points and a local axis so that the initial configuration can violate the constraint slightly. The joint translation is + * zero when the local anchor points coincide in world space. Using local anchors and a local axis helps when saving and loading a + * game. */ -public class LineJointDef extends JointDef -{ - public LineJointDef( ) - { +public class LineJointDef extends JointDef { + public LineJointDef () { type = JointType.LineJoint; } - + /** - * Initialize the bodies, anchors, axis, and reference angle using the world - * anchor and world axis. + * Initialize the bodies, anchors, axis, and reference angle using the world anchor and world axis. */ - public void initialize(Body bodyA, Body bodyB, Vector2 anchor, Vector2 axis) - { + public void initialize (Body bodyA, Body bodyB, Vector2 anchor, Vector2 axis) { this.bodyA = bodyA; this.bodyB = bodyB; - localAnchorA.set( bodyA.getLocalPoint( anchor ) ); - localAnchorB.set( bodyB.getLocalPoint( anchor ) ); - localAxisA.set( bodyA.getLocalVector(axis) ); + localAnchorA.set(bodyA.getLocalPoint(anchor)); + localAnchorB.set(bodyB.getLocalPoint(anchor)); + localAxisA.set(bodyA.getLocalVector(axis)); } /** - * The local anchor point relative to body1's origin. + * The local anchor point relative to body1's origin. */ - public final Vector2 localAnchorA = new Vector2( ); + public final Vector2 localAnchorA = new Vector2(); /** - * The local anchor point relative to body2's origin. + * The local anchor point relative to body2's origin. */ - public final Vector2 localAnchorB = new Vector2( ); + public final Vector2 localAnchorB = new Vector2(); /** - * The local translation axis in body1. + * The local translation axis in body1. */ - public final Vector2 localAxisA = new Vector2( 1.0f, 0 ); + public final Vector2 localAxisA = new Vector2(1.0f, 0); /** - * Enable/disable the joint limit. + * Enable/disable the joint limit. */ public boolean enableLimit = false; /** - * The lower translation limit, usually in meters. + * The lower translation limit, usually in meters. */ public float lowerTranslation = 0; /** - * The upper translation limit, usually in meters. + * The upper translation limit, usually in meters. */ public float upperTranslation = 0; /** - * Enable/disable the joint motor. + * Enable/disable the joint motor. */ public boolean enableMotor = false; /** - * The maximum motor torque, usually in N-m. + * The maximum motor torque, usually in N-m. */ public float maxMotorForce = 0; /** - * The desired motor speed in radians per second. + * The desired motor speed in radians per second. */ public float motorSpeed = 0; } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/joints/MouseJoint.java b/gdx/src/com/badlogic/gdx/physics/box2d/joints/MouseJoint.java index 69b94ee82..956e5cac0 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/MouseJoint.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/MouseJoint.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.math.Vector2; @@ -20,102 +18,91 @@ import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.World; /** - * A mouse joint is used to make a point on a body track a - * specified world point. This a soft constraint with a maximum - * force. This allows the constraint to stretch and without - * applying huge forces. - * NOTE: this joint is not documented in the manual because it was - * developed to be used in the testbed. If you want to learn how to - * use the mouse joint, look at the testbed. + * A mouse joint is used to make a point on a body track a specified world point. This a soft constraint with a maximum force. + * This allows the constraint to stretch and without applying huge forces. NOTE: this joint is not documented in the manual + * because it was developed to be used in the testbed. If you want to learn how to use the mouse joint, look at the testbed. */ -public class MouseJoint extends Joint -{ - public MouseJoint(World world, long addr) { +public class MouseJoint extends Joint { + public MouseJoint (World world, long addr) { super(world, addr); // TODO Auto-generated constructor stub } /** - * Use this to update the target point. + * Use this to update the target point. */ - public void setTarget(Vector2 target) - { - jniSetTarget( addr, target.x, target.y ); + public void setTarget (Vector2 target) { + jniSetTarget(addr, target.x, target.y); } - - private native void jniSetTarget( long addr, float x, float y ); - + + private native void jniSetTarget (long addr, float x, float y); + /** - * Use this to update the target point. + * Use this to update the target point. */ final float[] tmp = new float[2]; - private final Vector2 target = new Vector2( ); - public Vector2 getTarget() - { - jniGetTarget( addr, tmp ); - target.x = tmp[0]; target.y = tmp[1]; + private final Vector2 target = new Vector2(); + + public Vector2 getTarget () { + jniGetTarget(addr, tmp); + target.x = tmp[0]; + target.y = tmp[1]; return target; } - - private native void jniGetTarget( long addr, float[] target ); + + private native void jniGetTarget (long addr, float[] target); /** - * Set/get the maximum force in Newtons. + * Set/get the maximum force in Newtons. */ - public void setMaxForce(float force) - { - jniSetMaxForce( addr, force ); + public void setMaxForce (float force) { + jniSetMaxForce(addr, force); } - - private native void jniSetMaxForce( long addr, float force ); - + + private native void jniSetMaxForce (long addr, float force); + /** - * Set/get the maximum force in Newtons. + * Set/get the maximum force in Newtons. */ - public float getMaxForce() - { - return jniGetMaxForce( addr ); + public float getMaxForce () { + return jniGetMaxForce(addr); } - - private native float jniGetMaxForce( long addr ); + + private native float jniGetMaxForce (long addr); /** * Set/get the frequency in Hertz. */ - public void setFrequency(float hz) - { - jniSetFrequency( addr, hz ); + public void setFrequency (float hz) { + jniSetFrequency(addr, hz); } - - private native void jniSetFrequency( long addr, float hz ); - + + private native void jniSetFrequency (long addr, float hz); + /** * Set/get the frequency in Hertz. */ - public float getFrequency() - { - return jniGetFrequency( addr ); + public float getFrequency () { + return jniGetFrequency(addr); } - private native float jniGetFrequency( long addr ); - + private native float jniGetFrequency (long addr); + /** - * Set/get the damping ratio (dimensionless). + * Set/get the damping ratio (dimensionless). */ - public void setDampingRatio(float ratio) - { - jniSetDampingRatio( addr, ratio ); + public void setDampingRatio (float ratio) { + jniSetDampingRatio(addr, ratio); } - - private native void jniSetDampingRatio( long addr, float ratio ); - + + private native void jniSetDampingRatio (long addr, float ratio); + /** - * Set/get the damping ratio (dimensionless). + * Set/get the damping ratio (dimensionless). */ - public float getDampingRatio() - { - return jniGetDampingRatio( addr ); + public float getDampingRatio () { + return jniGetDampingRatio(addr); } - - private native float jniGetDampingRatio( long addr ); + + private native float jniGetDampingRatio (long addr); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/joints/MouseJointDef.java b/gdx/src/com/badlogic/gdx/physics/box2d/joints/MouseJointDef.java index d407b3bbc..e3398e96a 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/MouseJointDef.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/MouseJointDef.java @@ -1,54 +1,47 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.JointDef; /** - * Mouse joint definition. This requires a world target point, - * tuning parameters, and the time step. + * Mouse joint definition. This requires a world target point, tuning parameters, and the time step. */ -public class MouseJointDef extends JointDef -{ - public MouseJointDef( ) - { +public class MouseJointDef extends JointDef { + public MouseJointDef () { type = JointType.MouseJoint; } - + /** - * The initial world target point. This is assumed - * to coincide with the body anchor initially. + * The initial world target point. This is assumed to coincide with the body anchor initially. */ - public final Vector2 target = new Vector2( ); + public final Vector2 target = new Vector2(); /** - * The maximum constraint force that can be exerted - * to move the candidate body. Usually you will express - * as some multiple of the weight (multiplier * mass * gravity). + * The maximum constraint force that can be exerted to move the candidate body. Usually you will express as some multiple of + * the weight (multiplier * mass * gravity). */ public float maxForce = 0; /** - * The response speed. + * The response speed. */ public float frequencyHz = 5.0f; /** - * The damping ratio. 0 = no damping, 1 = critical damping. + * The damping ratio. 0 = no damping, 1 = critical damping. */ public float dampingRatio = 0.7f; } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/joints/PrismaticJoint.java b/gdx/src/com/badlogic/gdx/physics/box2d/joints/PrismaticJoint.java index e9766d573..e30c9a9d4 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/PrismaticJoint.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/PrismaticJoint.java @@ -1,165 +1,146 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.World; /** - * A prismatic joint. This joint provides one degree of freedom: translation - * along an axis fixed in body1. Relative rotation is prevented. You can - * use a joint limit to restrict the range of motion and a joint motor to - * drive the motion or to model joint friction. + * A prismatic joint. This joint provides one degree of freedom: translation along an axis fixed in body1. Relative rotation is + * prevented. You can use a joint limit to restrict the range of motion and a joint motor to drive the motion or to model joint + * friction. */ -public class PrismaticJoint extends Joint -{ - public PrismaticJoint( World world, long addr) - { - super(world, addr); +public class PrismaticJoint extends Joint { + public PrismaticJoint (World world, long addr) { + super(world, addr); } /** * Get the current joint translation, usually in meters. */ - public float getJointTranslation() - { - return jniGetJointTranslation( addr ); + public float getJointTranslation () { + return jniGetJointTranslation(addr); } - - private native float jniGetJointTranslation( long addr ); + + private native float jniGetJointTranslation (long addr); /** - * Get the current joint translation speed, usually in meters per second. + * Get the current joint translation speed, usually in meters per second. */ - public float getJointSpeed() - { - return jniGetJointSpeed( addr ); + public float getJointSpeed () { + return jniGetJointSpeed(addr); } - - private native float jniGetJointSpeed( long addr ); + + private native float jniGetJointSpeed (long addr); /** * Is the joint limit enabled? */ - public boolean isLimitEnabled() - { - return jniIsLimitEnabled( addr ); + public boolean isLimitEnabled () { + return jniIsLimitEnabled(addr); } - - private native boolean jniIsLimitEnabled( long addr ); + + private native boolean jniIsLimitEnabled (long addr); /** - * Enable/disable the joint limit. + * Enable/disable the joint limit. */ - public void enableLimit(boolean flag) - { - jniEnableLimit( addr, flag ); + public void enableLimit (boolean flag) { + jniEnableLimit(addr, flag); } - - private native void jniEnableLimit( long addr, boolean flag ); + + private native void jniEnableLimit (long addr, boolean flag); /** * Get the lower joint limit, usually in meters. */ - public float getLowerLimit() - { - return jniGetLowerLimit( addr ); + public float getLowerLimit () { + return jniGetLowerLimit(addr); } - private native float jniGetLowerLimit( long addr ); - + private native float jniGetLowerLimit (long addr); + /** - * Get the upper joint limit, usually in meters. + * Get the upper joint limit, usually in meters. */ - public float getUpperLimit() - { - return jniGetUpperLimit( addr ); + public float getUpperLimit () { + return jniGetUpperLimit(addr); } - - private native float jniGetUpperLimit( long addr ); + + private native float jniGetUpperLimit (long addr); /** - * Set the joint limits, usually in meters. + * Set the joint limits, usually in meters. */ - public void setLimits(float lower, float upper) - { - jniSetLimits( addr, lower, upper ); + public void setLimits (float lower, float upper) { + jniSetLimits(addr, lower, upper); } - - private native void jniSetLimits( long addr, float lower, float upper ); + + private native void jniSetLimits (long addr, float lower, float upper); /** - * Is the joint motor enabled? + * Is the joint motor enabled? */ - public boolean isMotorEnabled() - { - return jniIsMotorEnabled( addr ); + public boolean isMotorEnabled () { + return jniIsMotorEnabled(addr); } - private native boolean jniIsMotorEnabled( long addr ); - + private native boolean jniIsMotorEnabled (long addr); + /** - * Enable/disable the joint motor. + * Enable/disable the joint motor. */ - public void enableMotor(boolean flag) - { - jniEnableMotor( addr, flag ); + public void enableMotor (boolean flag) { + jniEnableMotor(addr, flag); } - private native void jniEnableMotor( long addr, boolean flag ); - - /** + private native void jniEnableMotor (long addr, boolean flag); + + /** * Set the motor speed, usually in meters per second. */ - public void setMotorSpeed(float speed) - { - jniSetMotorSpeed( addr, speed ); + public void setMotorSpeed (float speed) { + jniSetMotorSpeed(addr, speed); } - private native void jniSetMotorSpeed( long addr, float speed ); - + private native void jniSetMotorSpeed (long addr, float speed); + /** - * Get the motor speed, usually in meters per second. + * Get the motor speed, usually in meters per second. */ - public float getMotorSpeed() - { - return jniGetMotorSpeed( addr ); + public float getMotorSpeed () { + return jniGetMotorSpeed(addr); } - - private native float jniGetMotorSpeed( long addr ); + + private native float jniGetMotorSpeed (long addr); /** - * Set the maximum motor force, usually in N. + * Set the maximum motor force, usually in N. */ - public void setMaxMotorForce(float force) - { - jniSetMaxMotorForce( addr, force ); + public void setMaxMotorForce (float force) { + jniSetMaxMotorForce(addr, force); } - - private native void jniSetMaxMotorForce( long addr, float force ); + + private native void jniSetMaxMotorForce (long addr, float force); /** - * Get the current motor force, usually in N. + * Get the current motor force, usually in N. */ - public float getMotorForce() - { - return jniGetMotorForce( addr ); + public float getMotorForce () { + return jniGetMotorForce(addr); } - - private native float jniGetMotorForce( long addr ); - + private native float jniGetMotorForce (long addr); + } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/joints/PrismaticJointDef.java b/gdx/src/com/badlogic/gdx/physics/box2d/joints/PrismaticJointDef.java index 10fbcd3b1..b56fa6bb6 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/PrismaticJointDef.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/PrismaticJointDef.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.math.Vector2; @@ -20,83 +18,77 @@ import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.JointDef; /** - * Prismatic joint definition. This requires defining a line of - * motion using an axis and an anchor point. The definition uses local - * anchor points and a local axis so that the initial configuration - * can violate the constraint slightly. The joint translation is zero - * when the local anchor points coincide in world space. Using local - * anchors and a local axis helps when saving and loading a game. + * Prismatic joint definition. This requires defining a line of motion using an axis and an anchor point. The definition uses + * local anchor points and a local axis so that the initial configuration can violate the constraint slightly. The joint + * translation is zero when the local anchor points coincide in world space. Using local anchors and a local axis helps when + * saving and loading a game. * @warning at least one body should by dynamic with a non-fixed rotation. */ -public class PrismaticJointDef extends JointDef -{ - public PrismaticJointDef( ) - { +public class PrismaticJointDef extends JointDef { + public PrismaticJointDef () { type = JointType.PrismaticJoint; } - + /** - * Initialize the bodies, anchors, axis, and reference angle using the world - * anchor and world axis. + * Initialize the bodies, anchors, axis, and reference angle using the world anchor and world axis. */ - public void initialize(Body bodyA, Body bodyB, Vector2 anchor, Vector2 axis) - { + public void initialize (Body bodyA, Body bodyB, Vector2 anchor, Vector2 axis) { this.bodyA = bodyA; this.bodyB = bodyB; - localAnchorA.set( bodyA.getLocalPoint( anchor ) ); - localAnchorB.set( bodyB.getLocalPoint( anchor ) ); - localAxis1.set(bodyA.getLocalVector( axis )); + localAnchorA.set(bodyA.getLocalPoint(anchor)); + localAnchorB.set(bodyB.getLocalPoint(anchor)); + localAxis1.set(bodyA.getLocalVector(axis)); referenceAngle = bodyB.getAngle() - bodyA.getAngle(); - + } /** - * The local anchor point relative to body1's origin. + * The local anchor point relative to body1's origin. */ public final Vector2 localAnchorA = new Vector2(); /** - * The local anchor point relative to body2's origin. + * The local anchor point relative to body2's origin. */ - public final Vector2 localAnchorB = new Vector2( ); + public final Vector2 localAnchorB = new Vector2(); /** - * The local translation axis in body1. + * The local translation axis in body1. */ public final Vector2 localAxis1 = new Vector2(1, 0); /** - * The constrained angle between the bodies: body2_angle - body1_angle. + * The constrained angle between the bodies: body2_angle - body1_angle. */ public float referenceAngle = 0; /** - * Enable/disable the joint limit. + * Enable/disable the joint limit. */ public boolean enableLimit = false; /** - * The lower translation limit, usually in meters. + * The lower translation limit, usually in meters. */ public float lowerTranslation = 0; /** - * The upper translation limit, usually in meters. + * The upper translation limit, usually in meters. */ public float upperTranslation = 0; /** - * Enable/disable the joint motor. + * Enable/disable the joint motor. */ public boolean enableMotor = false; /** - * The maximum motor torque, usually in N-m. + * The maximum motor torque, usually in N-m. */ public float maxMotorForce = 0; /** - * The desired motor speed in radians per second. + * The desired motor speed in radians per second. */ public float motorSpeed = 0; } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/joints/PulleyJoint.java b/gdx/src/com/badlogic/gdx/physics/box2d/joints/PulleyJoint.java index de242ab01..e2b6b36db 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/PulleyJoint.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/PulleyJoint.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.math.Vector2; @@ -20,73 +18,66 @@ import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.World; /** - * The pulley joint is connected to two bodies and two fixed ground points. - * The pulley supports a ratio such that: - * length1 + ratio * length2 <= constant - * Yes, the force transmitted is scaled by the ratio. - * The pulley also enforces a maximum length limit on both sides. This is - * useful to prevent one side of the pulley hitting the top. + * The pulley joint is connected to two bodies and two fixed ground points. The pulley supports a ratio such that: length1 + ratio + * * length2 <= constant Yes, the force transmitted is scaled by the ratio. The pulley also enforces a maximum length limit on + * both sides. This is useful to prevent one side of the pulley hitting the top. */ -public class PulleyJoint extends Joint -{ - public PulleyJoint(World world, long addr) - { - super(world, addr); +public class PulleyJoint extends Joint { + public PulleyJoint (World world, long addr) { + super(world, addr); } /** - * Get the first ground anchor. + * Get the first ground anchor. */ private final float[] tmp = new float[2]; - private final Vector2 groundAnchorA = new Vector2( ); - public Vector2 getGroundAnchorA() - { - jniGetGroundAnchorA( addr, tmp ); - groundAnchorA.set( tmp[0], tmp[1] ); + private final Vector2 groundAnchorA = new Vector2(); + + public Vector2 getGroundAnchorA () { + jniGetGroundAnchorA(addr, tmp); + groundAnchorA.set(tmp[0], tmp[1]); return groundAnchorA; } - private native void jniGetGroundAnchorA( long addr, float[] anchor ); - + private native void jniGetGroundAnchorA (long addr, float[] anchor); + /** - * Get the second ground anchor. + * Get the second ground anchor. */ - private final Vector2 groundAnchorB = new Vector2( ); - public Vector2 getGroundAnchorB() - { - jniGetGroundAnchorB( addr, tmp ); - groundAnchorB.set( tmp[0], tmp[1] ); + private final Vector2 groundAnchorB = new Vector2(); + + public Vector2 getGroundAnchorB () { + jniGetGroundAnchorB(addr, tmp); + groundAnchorB.set(tmp[0], tmp[1]); return groundAnchorB; } - private native void jniGetGroundAnchorB( long addr, float[] anchor ); + private native void jniGetGroundAnchorB (long addr, float[] anchor); + /** - * Get the current length of the segment attached to body1. + * Get the current length of the segment attached to body1. */ - public float getLength1() - { + public float getLength1 () { return jniGetLength1(addr); } - private native float jniGetLength1( long addr ); - + private native float jniGetLength1 (long addr); + /** - * Get the current length of the segment attached to body2. + * Get the current length of the segment attached to body2. */ - public float getLength2() - { + public float getLength2 () { return jniGetLength2(addr); } - - private native float jniGetLength2( long addr ); + + private native float jniGetLength2 (long addr); /** - * Get the pulley ratio. + * Get the pulley ratio. */ - public float getRatio() - { - return jniGetRatio( addr ); + public float getRatio () { + return jniGetRatio(addr); } - - private native float jniGetRatio( long addr ); + + private native float jniGetRatio (long addr); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/joints/PulleyJointDef.java b/gdx/src/com/badlogic/gdx/physics/box2d/joints/PulleyJointDef.java index 8600323da..b1315d8d9 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/PulleyJointDef.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/PulleyJointDef.java @@ -1,104 +1,96 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.JointDef; -/** - * Pulley joint definition. This requires two ground anchors, - * two dynamic body anchor points, max lengths for each side, - * and a pulley ratio. +/** + * Pulley joint definition. This requires two ground anchors, two dynamic body anchor points, max lengths for each side, and a + * pulley ratio. */ -public class PulleyJointDef extends JointDef -{ +public class PulleyJointDef extends JointDef { private final static float minPulleyLength = 2.0f; - - public PulleyJointDef( ) - { + + public PulleyJointDef () { type = JointType.PulleyJoint; collideConnected = true; } - + /** - * Initialize the bodies, anchors, lengths, max lengths, and ratio using the world anchors. + * Initialize the bodies, anchors, lengths, max lengths, and ratio using the world anchors. */ - public void initialize(Body bodyA, Body bodyB, - Vector2 groundAnchorA, Vector2 groundAnchorB, - Vector2 anchorA, Vector2 anchorB, - float ratio) - { + public void initialize (Body bodyA, Body bodyB, Vector2 groundAnchorA, Vector2 groundAnchorB, Vector2 anchorA, + Vector2 anchorB, float ratio) { this.bodyA = bodyA; this.bodyB = bodyB; this.groundAnchorA.set(groundAnchorA); this.groundAnchorB.set(groundAnchorB); - this.localAnchorA.set( bodyA.getLocalPoint( anchorA ) ); - this.localAnchorB.set( bodyB.getLocalPoint( anchorB ) ); + this.localAnchorA.set(bodyA.getLocalPoint(anchorA)); + this.localAnchorB.set(bodyB.getLocalPoint(anchorB)); lengthA = anchorA.dst(groundAnchorA); lengthB = anchorB.dst(groundAnchorB); this.ratio = ratio; float C = lengthA + ratio * lengthB; maxLengthA = C - ratio * minPulleyLength; maxLengthB = (C - minPulleyLength) / ratio; - + } /** - * The first ground anchor in world coordinates. This point never moves. + * The first ground anchor in world coordinates. This point never moves. */ - public final Vector2 groundAnchorA = new Vector2( -1, 1 ); + public final Vector2 groundAnchorA = new Vector2(-1, 1); /** - * The second ground anchor in world coordinates. This point never moves. + * The second ground anchor in world coordinates. This point never moves. */ - public final Vector2 groundAnchorB = new Vector2( 1, 1); + public final Vector2 groundAnchorB = new Vector2(1, 1); /** - * The local anchor point relative to bodyA's origin. + * The local anchor point relative to bodyA's origin. */ - public final Vector2 localAnchorA = new Vector2( -1, 0 ); + public final Vector2 localAnchorA = new Vector2(-1, 0); /** - * The local anchor point relative to bodyB's origin. + * The local anchor point relative to bodyB's origin. */ - public final Vector2 localAnchorB = new Vector2( 1, 0 ); + public final Vector2 localAnchorB = new Vector2(1, 0); /** - * The a reference length for the segment attached to bodyA. + * The a reference length for the segment attached to bodyA. */ public float lengthA = 0; /** - * The maximum length of the segment attached to bodyA. + * The maximum length of the segment attached to bodyA. */ public float maxLengthA = 0; /** - * The a reference length for the segment attached to bodyB. + * The a reference length for the segment attached to bodyB. */ public float lengthB = 0; /** - * The maximum length of the segment attached to bodyB. + * The maximum length of the segment attached to bodyB. */ public float maxLengthB = 0; /** - * The pulley ratio, used to simulate a block-and-tackle. + * The pulley ratio, used to simulate a block-and-tackle. */ public float ratio = 1; } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/joints/RevoluteJoint.java b/gdx/src/com/badlogic/gdx/physics/box2d/joints/RevoluteJoint.java index aa066d57e..3d6fa7fea 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/RevoluteJoint.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/RevoluteJoint.java @@ -1,166 +1,147 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.World; /** - * A revolute joint constrains two bodies to share a common point while they - * are free to rotate about the point. The relative rotation about the shared - * point is the joint angle. You can limit the relative rotation with - * a joint limit that specifies a lower and upper angle. You can use a motor - * to drive the relative rotation about the shared point. A maximum motor torque - * is provided so that infinite forces are not generated. + * A revolute joint constrains two bodies to share a common point while they are free to rotate about the point. The relative + * rotation about the shared point is the joint angle. You can limit the relative rotation with a joint limit that specifies a + * lower and upper angle. You can use a motor to drive the relative rotation about the shared point. A maximum motor torque is + * provided so that infinite forces are not generated. */ -public class RevoluteJoint extends Joint -{ - public RevoluteJoint( World world, long addr) - { - super(world,addr); +public class RevoluteJoint extends Joint { + public RevoluteJoint (World world, long addr) { + super(world, addr); } /** - * Get the current joint angle in radians. + * Get the current joint angle in radians. */ - public float getJointAngle() - { - return jniGetJointAngle( addr ); + public float getJointAngle () { + return jniGetJointAngle(addr); } - private native float jniGetJointAngle( long addr ); + private native float jniGetJointAngle (long addr); /** - * Get the current joint angle speed in radians per second. + * Get the current joint angle speed in radians per second. */ - public float getJointSpeed() - { - return jniGetJointSpeed( addr ); + public float getJointSpeed () { + return jniGetJointSpeed(addr); } - - private native float jniGetJointSpeed( long addr ); + + private native float jniGetJointSpeed (long addr); /** - * Is the joint limit enabled? + * Is the joint limit enabled? */ - public boolean isLimitEnabled() - { - return jniIsLimitEnabled( addr ); + public boolean isLimitEnabled () { + return jniIsLimitEnabled(addr); } - - private native boolean jniIsLimitEnabled( long addr ); + + private native boolean jniIsLimitEnabled (long addr); /** * Enable/disable the joint limit. */ - public void enableLimit(boolean flag) - { - jniEnableLimit( addr, flag ); + public void enableLimit (boolean flag) { + jniEnableLimit(addr, flag); } - - private native void jniEnableLimit( long addr, boolean flag ); + + private native void jniEnableLimit (long addr, boolean flag); /** - * Get the lower joint limit in radians. + * Get the lower joint limit in radians. */ - public float getLowerLimit() - { - return jniGetLowerLimit( addr ); + public float getLowerLimit () { + return jniGetLowerLimit(addr); } - private native float jniGetLowerLimit( long addr ); - + private native float jniGetLowerLimit (long addr); + /** * Get the upper joint limit in radians. */ - public float getUpperLimit() - { - return jniGetUpperLimit( addr ); + public float getUpperLimit () { + return jniGetUpperLimit(addr); } - private native float jniGetUpperLimit( long addr ); - + private native float jniGetUpperLimit (long addr); + /** - * Set the joint limits in radians. + * Set the joint limits in radians. * @param upper */ - public void setLimits(float lower, float upper) - { - jniSetLimits( addr, lower, upper ); + public void setLimits (float lower, float upper) { + jniSetLimits(addr, lower, upper); } - private native void jniSetLimits( long addr, float lower, float upper ); - + private native void jniSetLimits (long addr, float lower, float upper); + /** - * Is the joint motor enabled? + * Is the joint motor enabled? */ - public boolean isMotorEnabled() - { - return jniIsMotorEnabled( addr ); + public boolean isMotorEnabled () { + return jniIsMotorEnabled(addr); } - - private native boolean jniIsMotorEnabled( long addr ); + + private native boolean jniIsMotorEnabled (long addr); /** - * Enable/disable the joint motor. + * Enable/disable the joint motor. */ - public void enableMotor(boolean flag) - { - jniEnableMotor( addr, flag ); + public void enableMotor (boolean flag) { + jniEnableMotor(addr, flag); } - - private native void jniEnableMotor( long addr, boolean flag ); + + private native void jniEnableMotor (long addr, boolean flag); /** - * Set the motor speed in radians per second. + * Set the motor speed in radians per second. */ - public void setMotorSpeed(float speed) - { - jniSetMotorSpeed( addr, speed ); + public void setMotorSpeed (float speed) { + jniSetMotorSpeed(addr, speed); } - - private native void jniSetMotorSpeed( long addr, float speed ); + + private native void jniSetMotorSpeed (long addr, float speed); /** - * Get the motor speed in radians per second. + * Get the motor speed in radians per second. */ - public float getMotorSpeed() - { - return jniGetMotorSpeed( addr ); + public float getMotorSpeed () { + return jniGetMotorSpeed(addr); } - - private native float jniGetMotorSpeed(long addr ); + + private native float jniGetMotorSpeed (long addr); /** - * Set the maximum motor torque, usually in N-m. + * Set the maximum motor torque, usually in N-m. */ - public void setMaxMotorTorque(float torque) - { - jniSetMaxMotorTorque( addr, torque ); + public void setMaxMotorTorque (float torque) { + jniSetMaxMotorTorque(addr, torque); } - - private native void jniSetMaxMotorTorque( long addr, float torque ); + + private native void jniSetMaxMotorTorque (long addr, float torque); /** - * Get the current motor torque, usually in N-m. + * Get the current motor torque, usually in N-m. */ - public float getMotorTorque() - { - return jniGetMotorTorque( addr ); + public float getMotorTorque () { + return jniGetMotorTorque(addr); } - - private native float jniGetMotorTorque( long addr ); + + private native float jniGetMotorTorque (long addr); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/joints/RevoluteJointDef.java b/gdx/src/com/badlogic/gdx/physics/box2d/joints/RevoluteJointDef.java index cf5f1821a..1526b9123 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/RevoluteJointDef.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/RevoluteJointDef.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.math.Vector2; @@ -20,81 +18,70 @@ import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.JointDef; /** - * Revolute joint definition. This requires defining an - * anchor point where the bodies are joined. The definition - * uses local anchor points so that the initial configuration - * can violate the constraint slightly. You also need to - * specify the initial relative angle for joint limits. This - * helps when saving and loading a game. - * The local anchor points are measured from the body's origin - * rather than the center of mass because: - * 1. you might not know where the center of mass will be. - * 2. if you add/remove shapes from a body and recompute the mass, - * the joints will be broken. + * Revolute joint definition. This requires defining an anchor point where the bodies are joined. The definition uses local anchor + * points so that the initial configuration can violate the constraint slightly. You also need to specify the initial relative + * angle for joint limits. This helps when saving and loading a game. The local anchor points are measured from the body's origin + * rather than the center of mass because: 1. you might not know where the center of mass will be. 2. if you add/remove shapes + * from a body and recompute the mass, the joints will be broken. */ -public class RevoluteJointDef extends JointDef -{ - public RevoluteJointDef( ) - { +public class RevoluteJointDef extends JointDef { + public RevoluteJointDef () { type = JointType.RevoluteJoint; } - + /** - * Initialize the bodies, anchors, and reference angle using a world - * anchor point. + * Initialize the bodies, anchors, and reference angle using a world anchor point. */ - public void initialize(Body bodyA, Body bodyB, Vector2 anchor) - { + public void initialize (Body bodyA, Body bodyB, Vector2 anchor) { this.bodyA = bodyA; this.bodyB = bodyB; - localAnchorA.set( bodyA.getLocalPoint( anchor ) ); - localAnchorB.set( bodyB.getLocalPoint( anchor ) ); + localAnchorA.set(bodyA.getLocalPoint(anchor)); + localAnchorB.set(bodyB.getLocalPoint(anchor)); referenceAngle = bodyB.getAngle() - bodyA.getAngle(); } /** - * The local anchor point relative to body1's origin. + * The local anchor point relative to body1's origin. */ - public final Vector2 localAnchorA = new Vector2( ); + public final Vector2 localAnchorA = new Vector2(); /** - * The local anchor point relative to body2's origin. + * The local anchor point relative to body2's origin. */ - public final Vector2 localAnchorB = new Vector2( );; + public final Vector2 localAnchorB = new Vector2();; /** - * The body2 angle minus body1 angle in the reference state (radians). + * The body2 angle minus body1 angle in the reference state (radians). */ public float referenceAngle = 0; /** - * A flag to enable joint limits. + * A flag to enable joint limits. */ public boolean enableLimit = false; /** - * The lower angle for the joint limit (radians). + * The lower angle for the joint limit (radians). */ public float lowerAngle = 0; /** - * The upper angle for the joint limit (radians). + * The upper angle for the joint limit (radians). */ public float upperAngle = 0; /** - * A flag to enable the joint motor. + * A flag to enable the joint motor. */ public boolean enableMotor = false; /** - * The desired motor speed. Usually in radians per second. + * The desired motor speed. Usually in radians per second. */ public float motorSpeed = 0; /** - * The maximum motor torque used to achieve the desired motor speed. - * Usually in N-m. + * The maximum motor torque used to achieve the desired motor speed. Usually in N-m. */ public float maxMotorTorque = 0; } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/joints/WeldJoint.java b/gdx/src/com/badlogic/gdx/physics/box2d/joints/WeldJoint.java index e0c936304..03745e3b9 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/WeldJoint.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/WeldJoint.java @@ -1,31 +1,27 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.World; /** - * A weld joint essentially glues two bodies together. A weld joint may - * distort somewhat because the island constraint solver is approximate. + * A weld joint essentially glues two bodies together. A weld joint may distort somewhat because the island constraint solver is + * approximate. */ -public class WeldJoint extends Joint -{ - public WeldJoint(World world, long addr) - { - super(world,addr); +public class WeldJoint extends Joint { + public WeldJoint (World world, long addr) { + super(world, addr); } } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/joints/WeldJointDef.java b/gdx/src/com/badlogic/gdx/physics/box2d/joints/WeldJointDef.java index e25ea7b3d..f5a90b321 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/WeldJointDef.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/WeldJointDef.java @@ -1,48 +1,43 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.JointDef; -public class WeldJointDef extends JointDef -{ - public WeldJointDef( ) - { +public class WeldJointDef extends JointDef { + public WeldJointDef () { type = JointType.WeldJoint; } - - /// Initialize the bodies, anchors, and reference angle using a world - /// anchor point. - public void initialize(Body body1, Body body2, Vector2 anchor) - { + + // / Initialize the bodies, anchors, and reference angle using a world + // / anchor point. + public void initialize (Body body1, Body body2, Vector2 anchor) { this.bodyA = body1; this.bodyB = body2; - this.localAnchorA.set( body1.getLocalPoint( anchor ) ); - this.localAnchorB.set( body2.getLocalPoint( anchor ) ); + this.localAnchorA.set(body1.getLocalPoint(anchor)); + this.localAnchorB.set(body2.getLocalPoint(anchor)); referenceAngle = body2.getAngle() - body1.getAngle(); } - /// The local anchor point relative to body1's origin. + // / The local anchor point relative to body1's origin. public final Vector2 localAnchorA = new Vector2(); - /// The local anchor point relative to body2's origin. + // / The local anchor point relative to body2's origin. public final Vector2 localAnchorB = new Vector2(); - /// The body2 angle minus body1 angle in the reference state (radians). + // / The body2 angle minus body1 angle in the reference state (radians). public float referenceAngle = 0; } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/Action.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/Action.java index 439971376..98923f5c8 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/Action.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/Action.java @@ -1,40 +1,35 @@ + package com.badlogic.gdx.scenes.scene2d; -public interface Action -{ +public interface Action { /** - * Sets the {@link Actor} of this action. Will be called - * when the Action is added to an Actor via {@link Actor.action()} - * before any other call to this interface. + * Sets the {@link Actor} of this action. Will be called when the Action is added to an Actor via {@link Actor.action()} before + * any other call to this interface. * * @param actor the actor. */ - public void setTarget( Actor actor ); - + public void setTarget (Actor actor); + /** * Apply the action. * * @param delta delta time in seconds */ - public void act( float delta ); - + public void act (float delta); + /** * @return whether the action is done or not */ - public boolean isDone( ); - + public boolean isDone (); + /** - * Called by the owner of the action when it can - * release all its resources, e.g. put itself - * back into a pool. + * Called by the owner of the action when it can release all its resources, e.g. put itself back into a pool. */ - public void finish( ); - + public void finish (); + /** - * Creates a copy of this action. The action - * must be in a state independent of the original - * and one must be able to call {@link #setTarget()} - * on it without any side effects. + * Creates a copy of this action. The action must be in a state independent of the original and one must be able to call + * {@link #setTarget()} on it without any side effects. */ - public Action copy( ); + public Action copy (); } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/Actor.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/Actor.java index c6e090c30..575c250ee 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/Actor.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/Actor.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d; import com.badlogic.gdx.graphics.Color; @@ -21,29 +19,32 @@ import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.PooledLinkedList; /** - *

An Actor is part of a Stage or a group within a stage - * it has a position, a rectangular size given as width and height, - * a rotation angle and a scale in x and y and a reference point - * relative to the position which is used for rotation and scaling

+ *

+ * An Actor is part of a Stage or a group within a stage it has a position, a rectangular size given as width and height, a + * rotation angle and a scale in x and y and a reference point relative to the position which is used for rotation and scaling + *

+ * + *

+ * The position of an Actor is coincident with its unrotated, unscaled bottom left corner. + *

+ * + *

+ * An Actor can be a child of a Group or the Stage it belongs to. The object it belongs to is called the Actor's parent. An + * Actor's position is always relative to the bottom left corner of its parent. + *

+ * + *

+ * Every Actor must have a unique name within a Stage + *

* - *

The position of an Actor is coincident with its unrotated, unscaled bottom - * left corner.

- * - *

An Actor can be a child of a Group or the Stage it belongs to. The object it belongs - * to is called the Actor's parent. An Actor's position is always relative to the bottom - * left corner of its parent.

- * - *

Every Actor must have a unique name within a Stage

- * * @author mzechner - * + * */ -public abstract class Actor -{ +public abstract class Actor { public Group parent; public final String name; public boolean touchable = true; - + public float x; public float y; public float width; @@ -53,75 +54,65 @@ public abstract class Actor public float scaleX = 1; public float scaleY = 1; public float rotation; - public final Color color = new Color( 1, 1, 1, 1 ); - - private PooledLinkedList actions = new PooledLinkedList( 10 ); - - public Actor( String name ) - { + public final Color color = new Color(1, 1, 1, 1); + + private PooledLinkedList actions = new PooledLinkedList(10); + + public Actor (String name) { this.name = name; } - + /** - * Renders the Actor. The spriteBatch is configured so that - * the Actor can render in its parents coordinate system. + * Renders the Actor. The spriteBatch is configured so that the Actor can render in its parents coordinate system. * @param stage the stage * @param batch the spritebatch to render with */ - protected abstract void render( SpriteBatch batch ); - - protected abstract boolean touchDown( float x, float y, int pointer ); - - protected abstract boolean touchUp( float x, float y, int pointer ); - - protected abstract boolean touchDragged( float x, float y, int pointer ); - - public abstract Actor hit( float x, float y ); - - public void toLocalCoordinates( Vector2 point ) - { - if( parent == null ) - return; - - parent.toLocalCoordinates( point ); - Group.toChildCoordinates(this, point.x, point.y, point ); + protected abstract void render (SpriteBatch batch); + + protected abstract boolean touchDown (float x, float y, int pointer); + + protected abstract boolean touchUp (float x, float y, int pointer); + + protected abstract boolean touchDragged (float x, float y, int pointer); + + public abstract Actor hit (float x, float y); + + public void toLocalCoordinates (Vector2 point) { + if (parent == null) return; + + parent.toLocalCoordinates(point); + Group.toChildCoordinates(this, point.x, point.y, point); } - - public void remove( ) - { - parent.removeActor( this ); + + public void remove () { + parent.removeActor(this); } - - protected void act( float delta ) - { + + protected void act (float delta) { actions.iter(); Action action; - - while( (action = actions.next() ) != null ) - { - action.act( delta ); - if( action.isDone() ) - { + + while ((action = actions.next()) != null) { + action.act(delta); + if (action.isDone()) { action.finish(); actions.remove(); } } } - - public void action( Action action ) - { - action.setTarget( this ); - actions.add( action ); + + public void action (Action action) { + action.setTarget(this); + actions.add(action); } - - public void clearActions( ) - { - actions.clear( ); + + public void clearActions () { + actions.clear(); } - - public String toString( ) - { - return name + ": [x=" + x + ", y=" + y + ", refX=" + originX + ", refY=" + originY + ", width=" + width + ", height=" + height + "]"; + + public String toString () { + return name + ": [x=" + x + ", y=" + y + ", refX=" + originX + ", refY=" + originY + ", width=" + width + ", height=" + + height + "]"; } - + } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/Group.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/Group.java index e4999ea31..da46e7777 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/Group.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/Group.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d; import java.util.ArrayList; @@ -36,381 +34,313 @@ import com.badlogic.gdx.math.Vector2; * A group is an Actor that contains other Actors (also other Groups which are Actors). * * @author mzechner - * + * */ -public class Group extends Actor -{ +public class Group extends Actor { public static Texture debugTexture; public static boolean debug = false; - - private final Matrix4 tmp4 = new Matrix4( ); - private final Matrix4 oldBatchTransform = new Matrix4( ); + + private final Matrix4 tmp4 = new Matrix4(); + private final Matrix4 oldBatchTransform = new Matrix4(); private final Matrix3 transform; - private final Matrix3 scenetransform = new Matrix3( ); - + private final Matrix3 scenetransform = new Matrix3(); + private final List children; // TODO O(n) delete, baaad. - private final List immutableChildren; + private final List immutableChildren; private final List groups; // TODO O(n) delete, baad. private final List immutableGroups; private final Map namesToActors; - + public Actor lastTouchedChild; public Actor focusedActor = null; - - public Group( String name ) - { - super( name ); - this.transform = new Matrix3( ); - this.children = new ArrayList( ); - this.immutableChildren = Collections.unmodifiableList( this.children ); - this.groups = new ArrayList( ); - this.immutableGroups = Collections.unmodifiableList( this.groups ); - this.namesToActors = new HashMap( ); + + public Group (String name) { + super(name); + this.transform = new Matrix3(); + this.children = new ArrayList(); + this.immutableChildren = Collections.unmodifiableList(this.children); + this.groups = new ArrayList(); + this.immutableGroups = Collections.unmodifiableList(this.groups); + this.namesToActors = new HashMap(); } - - private void updateTransform( ) - { + + private void updateTransform () { transform.idt(); - if( originX != 0 || originY != 0 ) - transform.setToTranslation( originX, originY ); - if( rotation != 0 ) - transform.mul( scenetransform.setToRotation( rotation ) ); - if( scaleX != 1 || scaleY != 1 ) - transform.mul( scenetransform.setToScaling( scaleX, scaleY ) ); - if( originX != 0 || originY != 0 ) - transform.mul( scenetransform.setToTranslation( -originX, -originY ) ); - if( x != 0 || y != 0 ) - { + if (originX != 0 || originY != 0) transform.setToTranslation(originX, originY); + if (rotation != 0) transform.mul(scenetransform.setToRotation(rotation)); + if (scaleX != 1 || scaleY != 1) transform.mul(scenetransform.setToScaling(scaleX, scaleY)); + if (originX != 0 || originY != 0) transform.mul(scenetransform.setToTranslation(-originX, -originY)); + if (x != 0 || y != 0) { transform.getValues()[6] += x; transform.getValues()[7] += y; } - - if( parent != null ) - { + + if (parent != null) { scenetransform.set(parent.scenetransform); - scenetransform.mul( transform ); - } - else - { + scenetransform.mul(transform); + } else { scenetransform.set(transform); } } - - protected void act( float delta ) - { - super.act( delta ); - + + protected void act (float delta) { + super.act(delta); + int len = children.size(); - for( int i = 0; i < len; i++ ) - { + for (int i = 0; i < len; i++) { Actor child = children.get(i); - child.act( delta ); + child.act(delta); } } - - @Override - protected void render( SpriteBatch batch ) - { - updateTransform( ); - tmp4.set( scenetransform ); - - if( debug && debugTexture != null && parent != null ) - batch.draw( debugTexture, x, y, originX, originY, width==0?200:width, height==0?200:height, scaleX, scaleY, rotation, 0, 0, debugTexture.getWidth(), debugTexture.getHeight(), Color.WHITE, false, false ); - - batch.end(); + + @Override protected void render (SpriteBatch batch) { + updateTransform(); + tmp4.set(scenetransform); + + if (debug && debugTexture != null && parent != null) + batch.draw(debugTexture, x, y, originX, originY, width == 0 ? 200 : width, height == 0 ? 200 : height, scaleX, scaleY, + rotation, 0, 0, debugTexture.getWidth(), debugTexture.getHeight(), Color.WHITE, false, false); + + batch.end(); oldBatchTransform.set(batch.getTransformMatrix()); - batch.setTransformMatrix( tmp4 ); - batch.begin( ); + batch.setTransformMatrix(tmp4); + batch.begin(); int len = children.size(); - for( int i = 0; i < len; i++ ) - children.get(i).render( batch ); - + for (int i = 0; i < len; i++) + children.get(i).render(batch); + batch.end(); - batch.setTransformMatrix( oldBatchTransform ); - batch.begin( ); + batch.setTransformMatrix(oldBatchTransform); + batch.begin(); } - final Vector2 point = new Vector2( ); + final Vector2 point = new Vector2(); static final Vector2 xAxis = new Vector2(); static final Vector2 yAxis = new Vector2(); static final Vector2 p = new Vector2(); static final Vector2 ref = new Vector2(); - public static void toChildCoordinates( Actor child, float x, float y, Vector2 out ) - { - if( child.rotation == 0 ) - { - if( child.scaleX == 1 && child.scaleY == 1 ) - { + + public static void toChildCoordinates (Actor child, float x, float y, Vector2 out) { + if (child.rotation == 0) { + if (child.scaleX == 1 && child.scaleY == 1) { out.x = x - child.x; out.y = y - child.y; - } - else - { - if( child.originX == 0 && child.originY == 0 ) - { + } else { + if (child.originX == 0 && child.originY == 0) { out.x = (x - child.x) / child.scaleX; out.y = (y - child.y) / child.scaleY; - } - else - { + } else { out.x = x / child.scaleX - (child.x - child.originX); out.x = x / child.scaleX - (child.x - child.originX); } } - } - else - { - final float cos = (float)Math.cos( (float)Math.toRadians(child.rotation) ); - final float sin = (float)Math.sin( (float)Math.toRadians(child.rotation) ); - - if( child.scaleX == 1 && child.scaleY == 1 ) - { - if( child.originX == 0 && child.originY == 0 ) - { + } else { + final float cos = (float)Math.cos((float)Math.toRadians(child.rotation)); + final float sin = (float)Math.sin((float)Math.toRadians(child.rotation)); + + if (child.scaleX == 1 && child.scaleY == 1) { + if (child.originX == 0 && child.originY == 0) { float tox = x - child.x; float toy = y - child.y; - + out.x = tox * cos + toy * sin; out.y = tox * -sin + toy * cos; - } - else - { + } else { final float worldOriginX = child.x + child.originX; final float worldOriginY = child.y + child.originY; float fx = -child.originX; float fy = -child.originY; - + float x1 = cos * fx - sin * fy; float y1 = sin * fx + cos * fy; - x1 += worldOriginX; y1 += worldOriginY; - + x1 += worldOriginX; + y1 += worldOriginY; + float tox = x - x1; float toy = y - y1; - + out.x = tox * cos + toy * sin; out.y = tox * -sin + toy * cos; } - } - else - { - if( child.originX == 0 && child.originY == 0 ) - { + } else { + if (child.originX == 0 && child.originY == 0) { float tox = x - child.x; float toy = y - child.y; - + out.x = tox * cos + toy * sin; out.y = tox * -sin + toy * cos; - + out.x /= child.scaleX; out.y /= child.scaleY; - } - else - { + } else { float srefX = child.originX * child.scaleX; float srefY = child.originY * child.scaleY; - + final float worldOriginX = child.x + child.originX; final float worldOriginY = child.y + child.originY; float fx = -srefX; float fy = -srefY; - + float x1 = cos * fx - sin * fy; float y1 = sin * fx + cos * fy; - x1 += worldOriginX; y1 += worldOriginY; - + x1 += worldOriginX; + y1 += worldOriginY; + float tox = x - x1; float toy = y - y1; - + out.x = tox * cos + toy * sin; out.y = tox * -sin + toy * cos; - + out.x /= child.scaleX; out.y /= child.scaleY; } } } } - - @Override - protected boolean touchDown(float x, float y, int pointer) - { - if( !touchable ) - return false; - - if( debug ) - Gdx.app.log( "Group", name + ": " + x + ", " + y ); - - if( focusedActor != null ) - { - point.x = x; point.y = y; - focusedActor.toLocalCoordinates( point ); - focusedActor.touchDown( point.x, point.y, pointer ); + + @Override protected boolean touchDown (float x, float y, int pointer) { + if (!touchable) return false; + + if (debug) Gdx.app.log("Group", name + ": " + x + ", " + y); + + if (focusedActor != null) { + point.x = x; + point.y = y; + focusedActor.toLocalCoordinates(point); + focusedActor.touchDown(point.x, point.y, pointer); return true; } - + int len = children.size() - 1; - for( int i = len; i >= 0; i-- ) - { + for (int i = len; i >= 0; i--) { Actor child = children.get(i); - if( !child.touchable ) - continue; - - toChildCoordinates( child, x, y, point ); - - if( child.touchDown( point.x, point.y, pointer ) ) - { - if( child instanceof Group ) + if (!child.touchable) continue; + + toChildCoordinates(child, x, y, point); + + if (child.touchDown(point.x, point.y, pointer)) { + if (child instanceof Group) lastTouchedChild = ((Group)child).lastTouchedChild; else lastTouchedChild = child; return true; } } - + return false; } - - @Override - protected boolean touchUp(float x, float y, int pointer) - { - if( !touchable ) - return false; - - if( focusedActor != null ) - { - point.x = x; point.y = y; - focusedActor.toLocalCoordinates( point ); - focusedActor.touchUp( point.x, point.y, pointer ); + + @Override protected boolean touchUp (float x, float y, int pointer) { + if (!touchable) return false; + + if (focusedActor != null) { + point.x = x; + point.y = y; + focusedActor.toLocalCoordinates(point); + focusedActor.touchUp(point.x, point.y, pointer); return true; } - + int len = children.size() - 1; - for( int i = len; i >= 0; i-- ) - { + for (int i = len; i >= 0; i--) { Actor child = children.get(i); - if( !child.touchable ) - continue; - - toChildCoordinates( child, x, y, point ); - - if( child.touchUp( point.x, point.y, pointer ) ) - return true; + if (!child.touchable) continue; + + toChildCoordinates(child, x, y, point); + + if (child.touchUp(point.x, point.y, pointer)) return true; } return false; } - @Override - protected boolean touchDragged(float x, float y, int pointer) - { - if( !touchable ) - return false; - - if( focusedActor != null ) - { - point.x = x; point.y = y; - focusedActor.toLocalCoordinates( point ); - focusedActor.touchDragged( point.x, point.y, pointer ); + @Override protected boolean touchDragged (float x, float y, int pointer) { + if (!touchable) return false; + + if (focusedActor != null) { + point.x = x; + point.y = y; + focusedActor.toLocalCoordinates(point); + focusedActor.touchDragged(point.x, point.y, pointer); return true; } - + int len = children.size() - 1; - for( int i = len; i >= 0; i-- ) - { + for (int i = len; i >= 0; i--) { Actor child = children.get(i); - if( !child.touchable ) - continue; - - toChildCoordinates( child, x, y, point ); - - if( child.touchDragged( point.x, point.y, pointer ) ) - return true; + if (!child.touchable) continue; + + toChildCoordinates(child, x, y, point); + + if (child.touchDragged(point.x, point.y, pointer)) return true; } return false; } - - public Actor hit( float x, float y ) - { + + public Actor hit (float x, float y) { int len = children.size() - 1; - for( int i = len; i >= 0; i-- ) - { + for (int i = len; i >= 0; i--) { Actor child = children.get(i); - - toChildCoordinates( child, x, y, point ); - - Actor hit = child.hit( point.x, point.y ); - if( hit != null ) - { + + toChildCoordinates(child, x, y, point); + + Actor hit = child.hit(point.x, point.y); + if (hit != null) { return hit; } } - return null; + return null; } - - public void addActor( Actor actor ) - { - children.add( actor ); - if( actor instanceof Group ) - groups.add( (Group)actor ); - namesToActors.put( actor.name, actor ); + + public void addActor (Actor actor) { + children.add(actor); + if (actor instanceof Group) groups.add((Group)actor); + namesToActors.put(actor.name, actor); actor.parent = this; } - - public void removeActor( Actor actor ) - { - children.remove( actor ); - if( actor instanceof Group ) - groups.remove( (Group)actor ); - namesToActors.remove( actor.name ); + + public void removeActor (Actor actor) { + children.remove(actor); + if (actor instanceof Group) groups.remove((Group)actor); + namesToActors.remove(actor.name); } - - public Actor findActor( String name ) - { - Actor actor = namesToActors.get( name ); - if( actor == null ) - { + + public Actor findActor (String name) { + Actor actor = namesToActors.get(name); + if (actor == null) { int len = groups.size(); - for( int i = 0; i < len; i++ ) - { - actor = groups.get(i).findActor( name ); - if( actor != null ) - return actor; + for (int i = 0; i < len; i++) { + actor = groups.get(i).findActor(name); + if (actor != null) return actor; } } - + return actor; } - - public List getActors( ) - { + + public List getActors () { return immutableChildren; } - - public List getGroups( ) - { + + public List getGroups () { return immutableGroups; } - - public void focus( Actor actor ) - { + + public void focus (Actor actor) { focusedActor = actor; - if( parent != null ) - parent.focus( actor ); + if (parent != null) parent.focus(actor); } - - public static void enableDebugging( String debugTextureFile ) - { - debugTexture = Gdx.graphics.newTexture( Gdx.files.getFileHandle( debugTextureFile, FileType.Internal ), - TextureFilter.Linear, TextureFilter.Linear, - TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); + + public static void enableDebugging (String debugTextureFile) { + debugTexture = Gdx.graphics.newTexture(Gdx.files.getFileHandle(debugTextureFile, FileType.Internal), TextureFilter.Linear, + TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); debug = true; } - - public static void disableDebugging( ) - { - if( debugTexture != null ) - debugTexture.dispose(); + + public static void disableDebugging () { + if (debugTexture != null) debugTexture.dispose(); debug = false; } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/Stage.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/Stage.java index db81c8e23..fad13f39d 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/Stage.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/Stage.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d; import java.util.List; @@ -23,289 +21,249 @@ import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector2; /** - *

A Stage is a container for StageObjects and handles - * distributing touch events, animating StageObjects and - * asking them to render themselves.

+ *

+ * A Stage is a container for StageObjects and handles distributing touch events, animating StageObjects and asking them to render + * themselves. + *

* - *

A Stage object fills the whole screen. It has a width and - * height given in device independent pixels. It will create - * a projection matrix that maps this viewport to the given - * real screen resolution. If the stretched attribute is set - * to true then the viewport is enforced no matter the difference - * in aspect ratio between the stage object and the screen dimensions. - * In case stretch is disabled then the viewport is extended in the - * bigger screen dimensions.

+ *

+ * A Stage object fills the whole screen. It has a width and height given in device independent pixels. It will create a + * projection matrix that maps this viewport to the given real screen resolution. If the stretched attribute is set to true then + * the viewport is enforced no matter the difference in aspect ratio between the stage object and the screen dimensions. In case + * stretch is disabled then the viewport is extended in the bigger screen dimensions. + *

* @author mzechner - * + * */ -public class Stage -{ +public class Stage { private float width; private float height; private float centerX; private float centerY; private boolean stretch; - + private final Group root; - + private final SpriteBatch batch; private final Matrix4 projection; private final Matrix4 identity; - + /** - *

Constructs a new Stage object with the given - * dimensions. If the device resolution does not - * equal the Stage objects dimensions the stage - * object will setup a projection matrix to guarantee - * a fixed coordinate system. If stretch is disabled - * then the bigger dimension of the Stage will be increased - * to accomodate the actual device resolution.

+ *

+ * Constructs a new Stage object with the given dimensions. If the device resolution does not equal the Stage objects + * dimensions the stage object will setup a projection matrix to guarantee a fixed coordinate system. If stretch is disabled + * then the bigger dimension of the Stage will be increased to accomodate the actual device resolution. + *

* * @param width the width of the viewport * @param height the height of the viewport * @param stretch whether to stretch the viewport to the real device resolution */ - public Stage( float width, float height, boolean stretch ) - { + public Stage (float width, float height, boolean stretch) { this.width = width; this.height = height; this.stretch = stretch; - this.root = new Group( "root" ); - this.batch = new SpriteBatch( ); - this.projection = new Matrix4( ); - this.identity = new Matrix4( ); - setViewport( width, height, stretch ); + this.root = new Group("root"); + this.batch = new SpriteBatch(); + this.projection = new Matrix4(); + this.identity = new Matrix4(); + setViewport(width, height, stretch); } - + /** - * Sets the viewport dimensions in device independent pixels. If stretch - * is false and the viewport aspect ratio is not equal to the device - * ratio then the bigger dimension of the viewport will be extended (device - * independent pixels stay quardatic instead of getting stretched). + * Sets the viewport dimensions in device independent pixels. If stretch is false and the viewport aspect ratio is not equal to + * the device ratio then the bigger dimension of the viewport will be extended (device independent pixels stay quardatic + * instead of getting stretched). * * @param width thew width of the viewport in device independent pixels * @param height the height of the viewport in device independent pixels * @param strech whether to stretch the viewport or not */ - public void setViewport( float width, float height, boolean strech ) - { + public void setViewport (float width, float height, boolean strech) { // TODO implement stretch, adjust width or height - if( !stretch ) - { - if( width > height ) - { + if (!stretch) { + if (width > height) { float toDeviceSpace = Gdx.graphics.getHeight() / height; float toViewportSpace = height / Gdx.graphics.getHeight(); - + float deviceWidth = width * toDeviceSpace; - this.width = width + (Gdx.graphics.getWidth() - deviceWidth ) * toViewportSpace; + this.width = width + (Gdx.graphics.getWidth() - deviceWidth) * toViewportSpace; this.height = height; - } - else - { + } else { float toDeviceSpace = Gdx.graphics.getWidth() / width; float toViewportSpace = width / Gdx.graphics.getWidth(); - + float deviceHeight = height * toDeviceSpace; - this.height = height + (Gdx.graphics.getHeight() - deviceHeight ) * toViewportSpace; + this.height = height + (Gdx.graphics.getHeight() - deviceHeight) * toViewportSpace; this.width = width; } - } - else - { + } else { this.width = width; this.height = height; } - - + centerX = width / 2; centerY = height / 2; - - projection.setToOrtho2D( 0, 0, this.width, this.height ); + + projection.setToOrtho2D(0, 0, this.width, this.height); } - + /** * @return the width of the stage in dips */ - public float width() - { + public float width () { return width; } - + /** * @return the height of the stage in dips */ - public float height() - { + public float height () { return height; } - + /** * @return the x-coordinate of the left edge of the stage in dips */ - public int left( ) - { + public int left () { return 0; } - + /** * @return the x-coordinate of the right edge of the stage in dips */ - public float right( ) - { + public float right () { return width - 1; } - + /** * @return the y-coordinate of the top edge of the stage in dips */ - public float top( ) - { + public float top () { return height - 1; } - + /** * @return the y-coordinate of the bottom edge of the stage in dips */ - public float bottom( ) - { + public float bottom () { return 0; } - + /** * @return the center x-coordinate of the stage in dips */ - public float centerX( ) - { + public float centerX () { return centerX; } - + /** * @return the center y-coordinate of the stage in dips */ - public float centerY( ) - { + public float centerY () { return centerY; } - + /** * @return whether the stage is stretched */ - public boolean isStretched( ) - { + public boolean isStretched () { return stretch; } - - public Actor findActor( String name ) - { - return root.findActor( name ); + + public Actor findActor (String name) { + return root.findActor(name); } - - public List getActors( ) - { + + public List getActors () { return root.getActors(); } - - public List getGroups( ) - { + + public List getGroups () { return root.getGroups(); } - - final Vector2 point = new Vector2( ); - final Vector2 coords = new Vector2( ); - public boolean touchDown(int x, int y, int pointer) - { - toStageCoordinates(x, y, coords ); - Group.toChildCoordinates( root, coords.x, coords.y, point ); + + final Vector2 point = new Vector2(); + final Vector2 coords = new Vector2(); + + public boolean touchDown (int x, int y, int pointer) { + toStageCoordinates(x, y, coords); + Group.toChildCoordinates(root, coords.x, coords.y, point); return root.touchDown(point.x, point.y, pointer); } - public boolean touchUp(int x, int y, int pointer) - { - toStageCoordinates(x, y, coords ); - Group.toChildCoordinates( root, coords.x, coords.y, point ); - return root.touchUp( point.x, point.y, pointer ); + public boolean touchUp (int x, int y, int pointer) { + toStageCoordinates(x, y, coords); + Group.toChildCoordinates(root, coords.x, coords.y, point); + return root.touchUp(point.x, point.y, pointer); } - public boolean touchDragged(int x, int y, int pointer) - { - toStageCoordinates(x, y, coords ); - Group.toChildCoordinates( root, coords.x, coords.y, point ); - return root.touchDragged( point.x, point.y, pointer ); + public boolean touchDragged (int x, int y, int pointer) { + toStageCoordinates(x, y, coords); + Group.toChildCoordinates(root, coords.x, coords.y, point); + return root.touchDragged(point.x, point.y, pointer); } - - public void act( float delta ) - { - root.act( delta ); + + public void act (float delta) { + root.act(delta); } - - public void render( ) - { - batch.setProjectionMatrix( projection ); - batch.setTransformMatrix( identity ); - batch.begin( ); - root.render( batch ); - batch.end( ); + + public void render () { + batch.setProjectionMatrix(projection); + batch.setTransformMatrix(identity); + batch.begin(); + root.render(batch); + batch.end(); } - - public void dispose( ) - { + + public void dispose () { batch.dispose(); } - public void addActor(Actor actor) - { - root.addActor( actor ); + public void addActor (Actor actor) { + root.addActor(actor); } - - public String graphToString( ) - { - StringBuilder buffer = new StringBuilder( ); - graphToString( buffer, root, 0 ); + + public String graphToString () { + StringBuilder buffer = new StringBuilder(); + graphToString(buffer, root, 0); return buffer.toString(); } - - private void graphToString( StringBuilder buffer, Actor actor, int level ) - { - for( int i = 0; i < level; i++ ) - buffer.append( ' ' ); - - buffer.append( actor ); - buffer.append( "\n" ); - - if( actor instanceof Group ) - { + + private void graphToString (StringBuilder buffer, Actor actor, int level) { + for (int i = 0; i < level; i++) + buffer.append(' '); + + buffer.append(actor); + buffer.append("\n"); + + if (actor instanceof Group) { Group group = (Group)actor; - for( int i = 0; i < group.getActors().size(); i++ ) - graphToString( buffer, group.getActors().get(i), level + 1 ); + for (int i = 0; i < group.getActors().size(); i++) + graphToString(buffer, group.getActors().get(i), level + 1); } } - public Group getRoot() - { + public Group getRoot () { return root; } - public SpriteBatch getSpriteBatch( ) - { + public SpriteBatch getSpriteBatch () { return batch; } - - public Actor getLastTouchedChild( ) - { + + public Actor getLastTouchedChild () { return root.lastTouchedChild; } - - public Actor hit(float x, float y) - { - Group.toChildCoordinates( root, x, y, point ); - return root.hit( point.x, point.y ); + + public Actor hit (float x, float y) { + Group.toChildCoordinates(root, x, y, point); + return root.hit(point.x, point.y); } - - public void toStageCoordinates( int x, int y, Vector2 out ) - { + + public void toStageCoordinates (int x, int y, Vector2 out) { out.y = (Gdx.graphics.getHeight() - 1) - y; - out.x = (float)x / Gdx.graphics.getWidth() * width; - out.y = out.y / Gdx.graphics.getHeight() * height; + out.x = (float)x / Gdx.graphics.getWidth() * width; + out.y = out.y / Gdx.graphics.getHeight() * height; } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Delay.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Delay.java index 534ebc97f..510d46402 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Delay.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Delay.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; @@ -5,59 +6,43 @@ import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Pool; import com.badlogic.gdx.utils.Pool.PoolObjectFactory; -public class Delay implements Action -{ - static final Pool pool = new Pool( new PoolObjectFactory() { - @Override - public Delay createObject() - { - return new Delay( ); +public class Delay implements Action { + static final Pool pool = new Pool(new PoolObjectFactory() { + @Override public Delay createObject () { + return new Delay(); } - }, 100 ); - - + }, 100); + float taken; float duration; Action action; - - public static Delay $( Action action, float duration ) - { + + public static Delay $ (Action action, float duration) { Delay delay = pool.newObject(); delay.duration = duration; delay.action = action; return delay; } - - @Override - public void setTarget(Actor actor) - { - action.setTarget( actor ); + + @Override public void setTarget (Actor actor) { + action.setTarget(actor); this.taken = 0; } - @Override - public void act(float delta) - { + @Override public void act (float delta) { taken += delta; - if( taken > duration ) - action.act( delta ); + if (taken > duration) action.act(delta); } - @Override - public boolean isDone() - { + @Override public boolean isDone () { return taken > duration && action.isDone(); } - @Override - public void finish() - { - pool.free( this ); + @Override public void finish () { + pool.free(this); } - @Override - public Action copy() - { - return $( action.copy(), duration ); + @Override public Action copy () { + return $(action.copy(), duration); } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/FadeIn.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/FadeIn.java index b3b880b49..f990c4b0f 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/FadeIn.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/FadeIn.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; @@ -5,16 +6,13 @@ import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Pool; import com.badlogic.gdx.utils.Pool.PoolObjectFactory; -public class FadeIn implements Action -{ - static final Pool pool = new Pool( new PoolObjectFactory() { - @Override - public FadeIn createObject() - { - return new FadeIn( ); +public class FadeIn implements Action { + static final Pool pool = new Pool(new PoolObjectFactory() { + @Override public FadeIn createObject () { + return new FadeIn(); } - }, 100 ); - + }, 100); + float startAlpha = 0; float deltaAlpha = 0; private float duration; @@ -22,18 +20,15 @@ public class FadeIn implements Action private float taken = 0; private Actor target; private boolean done; - - public static FadeIn $( float duration ) - { + + public static FadeIn $ (float duration) { FadeIn action = pool.newObject(); action.duration = duration; action.invDuration = 1 / duration; return action; } - @Override - public void setTarget(Actor actor) - { + @Override public void setTarget (Actor actor) { this.target = actor; this.target.color.a = 0; this.startAlpha = 0; @@ -42,34 +37,26 @@ public class FadeIn implements Action this.done = false; } - @Override - public void act(float delta) - { + @Override public void act (float delta) { taken += delta; - if( taken >= duration ) - { + if (taken >= duration) { taken = duration; done = true; } - + float alpha = taken * invDuration; target.color.a = startAlpha + deltaAlpha * alpha; } - @Override - public boolean isDone() - { + @Override public boolean isDone () { return done; } - @Override - public void finish() - { - pool.free( this ); + @Override public void finish () { + pool.free(this); } - @Override - public Action copy() { - return $( duration ); + @Override public Action copy () { + return $(duration); } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/FadeOut.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/FadeOut.java index 3ac6d99b1..8da9152f6 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/FadeOut.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/FadeOut.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; @@ -5,16 +6,13 @@ import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Pool; import com.badlogic.gdx.utils.Pool.PoolObjectFactory; -public class FadeOut implements Action -{ - static final Pool pool = new Pool( new PoolObjectFactory() { - @Override - public FadeOut createObject() - { - return new FadeOut( ); +public class FadeOut implements Action { + static final Pool pool = new Pool(new PoolObjectFactory() { + @Override public FadeOut createObject () { + return new FadeOut(); } - }, 100 ); - + }, 100); + float startAlpha = 0; float deltaAlpha = 0; private float duration; @@ -22,18 +20,15 @@ public class FadeOut implements Action private float taken = 0; private Actor target; private boolean done; - - public static FadeOut $( float duration ) - { + + public static FadeOut $ (float duration) { FadeOut action = pool.newObject(); action.duration = duration; action.invDuration = 1 / duration; return action; } - @Override - public void setTarget(Actor actor) - { + @Override public void setTarget (Actor actor) { this.target = actor; this.target.color.a = 1; this.startAlpha = 1; @@ -42,34 +37,26 @@ public class FadeOut implements Action this.done = false; } - @Override - public void act(float delta) - { + @Override public void act (float delta) { taken += delta; - if( taken >= duration ) - { + if (taken >= duration) { taken = duration; done = true; } - + float alpha = taken * invDuration; target.color.a = startAlpha + deltaAlpha * alpha; } - @Override - public boolean isDone() - { + @Override public boolean isDone () { return done; } - @Override - public void finish() - { - pool.free( this ); + @Override public void finish () { + pool.free(this); } - @Override - public Action copy() { - return $( duration ); + @Override public Action copy () { + return $(duration); } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/FadeTo.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/FadeTo.java index 8e073d2d3..39c4ce57f 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/FadeTo.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/FadeTo.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; @@ -5,16 +6,13 @@ import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Pool; import com.badlogic.gdx.utils.Pool.PoolObjectFactory; -public class FadeTo implements Action -{ - static final Pool pool = new Pool( new PoolObjectFactory() { - @Override - public FadeTo createObject() - { - return new FadeTo( ); +public class FadeTo implements Action { + static final Pool pool = new Pool(new PoolObjectFactory() { + @Override public FadeTo createObject () { + return new FadeTo(); } - }, 100 ); - + }, 100); + float toAlpha = 0; float startAlpha; float deltaAlpha = 0; @@ -23,21 +21,18 @@ public class FadeTo implements Action private float taken = 0; private Actor target; private boolean done; - - public static FadeTo $( float alpha, float duration ) - { + + public static FadeTo $ (float alpha, float duration) { FadeTo action = pool.newObject(); - if( alpha < 0 ) alpha = 0; - if( alpha > 1 ) alpha = 1; + if (alpha < 0) alpha = 0; + if (alpha > 1) alpha = 1; action.toAlpha = alpha; action.duration = duration; action.invDuration = 1 / duration; return action; } - @Override - public void setTarget(Actor actor) - { + @Override public void setTarget (Actor actor) { this.target = actor; this.startAlpha = this.target.color.a; this.deltaAlpha = toAlpha - this.target.color.a; @@ -45,35 +40,26 @@ public class FadeTo implements Action this.done = false; } - @Override - public void act(float delta) - { + @Override public void act (float delta) { taken += delta; - if( taken >= duration ) - { + if (taken >= duration) { taken = duration; done = true; } - + float alpha = taken * invDuration; target.color.a = startAlpha + deltaAlpha * alpha; } - @Override - public boolean isDone() - { + @Override public boolean isDone () { return done; } - @Override - public void finish() - { - pool.free( this ); + @Override public void finish () { + pool.free(this); } - @Override - public Action copy() - { - return $( toAlpha, duration ); + @Override public Action copy () { + return $(toAlpha, duration); } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Forever.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Forever.java index 912c6782a..89a4abe77 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Forever.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Forever.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; @@ -5,63 +6,48 @@ import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Pool; import com.badlogic.gdx.utils.Pool.PoolObjectFactory; -public class Forever implements Action -{ - static final Pool pool = new Pool( new PoolObjectFactory() { - @Override - public Forever createObject() - { - return new Forever( ); +public class Forever implements Action { + static final Pool pool = new Pool(new PoolObjectFactory() { + @Override public Forever createObject () { + return new Forever(); } - }, 100 ); - + }, 100); + private Action action; private Actor target; - - public static Forever $( Action action ) - { + + public static Forever $ (Action action) { Forever forever = pool.newObject(); forever.action = action; return forever; } - - - @Override - public void setTarget(Actor actor) { - action.setTarget( actor ); + + @Override public void setTarget (Actor actor) { + action.setTarget(actor); target = actor; } - @Override - public void act(float delta) - { - action.act( delta ); - if( action.isDone() ) - { + @Override public void act (float delta) { + action.act(delta); + if (action.isDone()) { Action oldAction = action; action = action.copy(); oldAction.finish(); - action.setTarget( target ); + action.setTarget(target); } } - @Override - public boolean isDone() - { + @Override public boolean isDone () { return false; } - @Override - public void finish() - { - pool.free( this ); + @Override public void finish () { + pool.free(this); action.finish(); } - @Override - public Action copy() - { - return $( action.copy() ); + @Override public Action copy () { + return $(action.copy()); } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/MoveBy.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/MoveBy.java index 47599dc3c..c20d980dd 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/MoveBy.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/MoveBy.java @@ -1,21 +1,18 @@ + package com.badlogic.gdx.scenes.scene2d.actions; -import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.Action; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Pool; import com.badlogic.gdx.utils.Pool.PoolObjectFactory; -public class MoveBy implements Action -{ - static final Pool pool = new Pool( new PoolObjectFactory() { - @Override - public MoveBy createObject() - { - return new MoveBy( ); +public class MoveBy implements Action { + static final Pool pool = new Pool(new PoolObjectFactory() { + @Override public MoveBy createObject () { + return new MoveBy(); } - }, 100 ); - + }, 100); + private float x; private float y; private float startX; @@ -27,9 +24,8 @@ public class MoveBy implements Action private float taken = 0; private Actor target; private boolean done; - - public static MoveBy $( float x, float y, float duration ) - { + + public static MoveBy $ (float x, float y, float duration) { MoveBy action = pool.newObject(); action.x = x; action.y = y; @@ -37,10 +33,8 @@ public class MoveBy implements Action action.invDuration = 1 / duration; return action; } - - @Override - public void setTarget(Actor actor) - { + + @Override public void setTarget (Actor actor) { this.target = actor; this.startX = target.x; this.startY = target.y; @@ -50,37 +44,27 @@ public class MoveBy implements Action this.done = false; } - @Override - public void act(float delta) - { + @Override public void act (float delta) { taken += delta; - if( taken >= duration ) - { + if (taken >= duration) { taken = duration; done = true; } - + float alpha = taken * invDuration; target.x = startX + deltaX * alpha; target.y = startY + deltaY * alpha; } - @Override - public boolean isDone() - { + @Override public boolean isDone () { return done; } - @Override - public void finish() - { - pool.free( this ); + @Override public void finish () { + pool.free(this); } - @Override - public Action copy() - { - return $( x, y, duration ); + @Override public Action copy () { + return $(x, y, duration); } } - diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/MoveTo.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/MoveTo.java index e12d6445c..be3915f67 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/MoveTo.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/MoveTo.java @@ -1,21 +1,18 @@ + package com.badlogic.gdx.scenes.scene2d.actions; -import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.Action; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Pool; import com.badlogic.gdx.utils.Pool.PoolObjectFactory; -public class MoveTo implements Action -{ - static final Pool pool = new Pool( new PoolObjectFactory() { - @Override - public MoveTo createObject() - { - return new MoveTo( ); +public class MoveTo implements Action { + static final Pool pool = new Pool(new PoolObjectFactory() { + @Override public MoveTo createObject () { + return new MoveTo(); } - }, 100 ); - + }, 100); + private float x; private float y; private float startX; @@ -27,8 +24,8 @@ public class MoveTo implements Action private float taken = 0; private Actor target; private boolean done; - public static MoveTo $( float x, float y, float duration ) - { + + public static MoveTo $ (float x, float y, float duration) { MoveTo action = pool.newObject(); action.x = x; action.y = y; @@ -36,10 +33,8 @@ public class MoveTo implements Action action.invDuration = 1 / duration; return action; } - - @Override - public void setTarget(Actor actor) - { + + @Override public void setTarget (Actor actor) { this.target = actor; this.startX = target.x; this.startY = target.y; @@ -49,36 +44,27 @@ public class MoveTo implements Action this.done = false; } - @Override - public void act(float delta) - { + @Override public void act (float delta) { taken += delta; - if( taken >= duration ) - { + if (taken >= duration) { taken = duration; done = true; } - + float alpha = taken * invDuration; target.x = startX + deltaX * alpha; target.y = startY + deltaY * alpha; } - @Override - public boolean isDone() - { + @Override public boolean isDone () { return done; } - @Override - public void finish() - { - pool.free( this ); + @Override public void finish () { + pool.free(this); } - @Override - public Action copy() - { - return $( x, y, duration ); + @Override public Action copy () { + return $(x, y, duration); } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Parallel.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Parallel.java index efd5fa488..e94709165 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Parallel.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Parallel.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.scenes.scene2d.actions; import java.util.ArrayList; @@ -8,69 +9,56 @@ import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Pool; import com.badlogic.gdx.utils.Pool.PoolObjectFactory; -public class Parallel implements Action -{ - static final Pool pool = new Pool( new PoolObjectFactory() { - @Override - public Parallel createObject() - { - return new Parallel( ); +public class Parallel implements Action { + static final Pool pool = new Pool(new PoolObjectFactory() { + @Override public Parallel createObject () { + return new Parallel(); } - }, 100 ); - - public static Parallel $( Action ... actions ) - { + }, 100); + + public static Parallel $ (Action... actions) { Parallel action = pool.newObject(); action.actions.clear(); int len = actions.length; - for( int i = 0; i < len; i++ ) - action.actions.add( actions[i] ); + for (int i = 0; i < len; i++) + action.actions.add(actions[i]); return action; } - - private final List actions = new ArrayList( ); - @Override - public void setTarget(Actor actor) - { + private final List actions = new ArrayList(); + + @Override public void setTarget (Actor actor) { int len = actions.size(); - for( int i = 0; i < len; i++ ) - actions.get(i).setTarget( actor ); + for (int i = 0; i < len; i++) + actions.get(i).setTarget(actor); } - @Override - public void act(float delta) - { + @Override public void act (float delta) { int len = actions.size(); - for( int i = 0; i < len; i++ ) - actions.get(i).act( delta ); + for (int i = 0; i < len; i++) + actions.get(i).act(delta); } - @Override - public boolean isDone() { + @Override public boolean isDone () { int len = actions.size(); - for( int i = 0; i < len; i++ ) - if( actions.get(i).isDone() == false ) - return false; + for (int i = 0; i < len; i++) + if (actions.get(i).isDone() == false) return false; return true; } - - @Override - public void finish() - { - pool.free( this ); + + @Override public void finish () { + pool.free(this); int len = 0; - for( int i = 0; i < len; i++ ) + for (int i = 0; i < len; i++) actions.get(i).finish(); } - @Override - public Action copy() { + @Override public Action copy () { Parallel action = pool.newObject(); action.actions.clear(); int len = actions.size(); - for( int i = 0; i < len; i++ ) - action.actions.add( actions.get(i).copy() ); + for (int i = 0; i < len; i++) + action.actions.add(actions.get(i).copy()); return action; } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Repeat.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Repeat.java index 3428234fa..e7b955566 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Repeat.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Repeat.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; @@ -5,71 +6,55 @@ import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Pool; import com.badlogic.gdx.utils.Pool.PoolObjectFactory; -public class Repeat implements Action -{ - static final Pool pool = new Pool( new PoolObjectFactory() { - @Override - public Repeat createObject() - { - return new Repeat( ); +public class Repeat implements Action { + static final Pool pool = new Pool(new PoolObjectFactory() { + @Override public Repeat createObject () { + return new Repeat(); } - }, 100 ); - + }, 100); + private Action action; private Actor target; private int times; private int finishedTimes; - - public static Repeat $( Action action, int times ) - { + + public static Repeat $ (Action action, int times) { Repeat repeat = pool.newObject(); repeat.action = action; repeat.times = times; repeat.finishedTimes = 0; return repeat; } - - - @Override - public void setTarget(Actor actor) { - action.setTarget( actor ); + + @Override public void setTarget (Actor actor) { + action.setTarget(actor); target = actor; } - @Override - public void act(float delta) - { - action.act( delta ); - if( action.isDone() ) - { + @Override public void act (float delta) { + action.act(delta); + if (action.isDone()) { finishedTimes++; - if( finishedTimes < times ) - { + if (finishedTimes < times) { Action oldAction = action; action = action.copy(); oldAction.finish(); - action.setTarget( target ); + action.setTarget(target); } } } - @Override - public boolean isDone() - { - return finishedTimes >= times ; + @Override public boolean isDone () { + return finishedTimes >= times; } - @Override - public void finish() - { - pool.free( this ); + @Override public void finish () { + pool.free(this); action.finish(); } - @Override - public Action copy() - { - return $( action.copy(), times ); + @Override public Action copy () { + return $(action.copy(), times); } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/RotateBy.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/RotateBy.java index e6f86db90..56b647325 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/RotateBy.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/RotateBy.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; @@ -5,16 +6,13 @@ import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Pool; import com.badlogic.gdx.utils.Pool.PoolObjectFactory; -public class RotateBy implements Action -{ - static final Pool pool = new Pool( new PoolObjectFactory() { - @Override - public RotateBy createObject() - { - return new RotateBy( ); +public class RotateBy implements Action { + static final Pool pool = new Pool(new PoolObjectFactory() { + @Override public RotateBy createObject () { + return new RotateBy(); } - }, 100 ); - + }, 100); + private float rotation; private float startRotation;; private float deltaRotation; @@ -23,19 +21,16 @@ public class RotateBy implements Action private float taken = 0; private Actor target; private boolean done; - - public static RotateBy $( float rotation, float duration ) - { + + public static RotateBy $ (float rotation, float duration) { RotateBy action = pool.newObject(); action.rotation = rotation; action.duration = duration; action.invDuration = 1 / duration; return action; } - - @Override - public void setTarget(Actor actor) - { + + @Override public void setTarget (Actor actor) { this.target = actor; this.startRotation = target.rotation; this.deltaRotation = rotation; @@ -43,37 +38,27 @@ public class RotateBy implements Action this.done = false; } - @Override - public void act(float delta) - { + @Override public void act (float delta) { taken += delta; - if( taken >= duration ) - { + if (taken >= duration) { taken = duration; done = true; return; } - + float alpha = taken * invDuration; target.rotation = startRotation + deltaRotation * alpha; } - @Override - public boolean isDone() - { + @Override public boolean isDone () { return done; } - - @Override - public void finish() - { - pool.free( this ); + + @Override public void finish () { + pool.free(this); } - @Override - public Action copy() - { - return $( rotation, duration ); + @Override public Action copy () { + return $(rotation, duration); } } - diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/RotateTo.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/RotateTo.java index dc90016ce..94633b2c5 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/RotateTo.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/RotateTo.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; @@ -5,16 +6,13 @@ import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Pool; import com.badlogic.gdx.utils.Pool.PoolObjectFactory; -public class RotateTo implements Action -{ - static final Pool pool = new Pool( new PoolObjectFactory() { - @Override - public RotateTo createObject() - { - return new RotateTo( ); +public class RotateTo implements Action { + static final Pool pool = new Pool(new PoolObjectFactory() { + @Override public RotateTo createObject () { + return new RotateTo(); } - }, 100 ); - + }, 100); + private float rotation; private float startRotation;; private float deltaRotation; @@ -23,19 +21,16 @@ public class RotateTo implements Action private float taken = 0; private Actor target; private boolean done; - - public static RotateTo $( float rotation, float duration ) - { + + public static RotateTo $ (float rotation, float duration) { RotateTo action = pool.newObject(); action.rotation = rotation; action.duration = duration; action.invDuration = 1 / duration; return action; } - - @Override - public void setTarget(Actor actor) - { + + @Override public void setTarget (Actor actor) { this.target = actor; this.startRotation = target.rotation; this.deltaRotation = rotation - target.rotation; @@ -43,37 +38,28 @@ public class RotateTo implements Action this.done = false; } - @Override - public void act(float delta) - { + @Override public void act (float delta) { taken += delta; - if( taken >= duration ) - { + if (taken >= duration) { taken = duration; target.rotation = rotation; done = true; return; } - + float alpha = taken * invDuration; target.rotation = startRotation + deltaRotation * alpha; } - @Override - public boolean isDone() - { + @Override public boolean isDone () { return done; } - - @Override - public void finish() - { - pool.free( this ); + + @Override public void finish () { + pool.free(this); } - @Override - public Action copy() { + @Override public Action copy () { return $(rotation, duration); } } - diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/ScaleTo.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/ScaleTo.java index 02c968acf..7de20e5eb 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/ScaleTo.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/ScaleTo.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; @@ -5,16 +6,13 @@ import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Pool; import com.badlogic.gdx.utils.Pool.PoolObjectFactory; -public class ScaleTo implements Action -{ - static final Pool pool = new Pool( new PoolObjectFactory() { - @Override - public ScaleTo createObject() - { - return new ScaleTo( ); +public class ScaleTo implements Action { + static final Pool pool = new Pool(new PoolObjectFactory() { + @Override public ScaleTo createObject () { + return new ScaleTo(); } - }, 100 ); - + }, 100); + private float scaleX; private float scaleY; private float startScaleX; @@ -26,9 +24,8 @@ public class ScaleTo implements Action private float taken = 0; private Actor target; private boolean done; - - public static ScaleTo $( float scaleX, float scaleY, float duration ) - { + + public static ScaleTo $ (float scaleX, float scaleY, float duration) { ScaleTo action = pool.newObject(); action.scaleX = scaleX; action.scaleY = scaleY; @@ -36,53 +33,41 @@ public class ScaleTo implements Action action.invDuration = 1 / duration; return action; } - - @Override - public void setTarget(Actor actor) - { + + @Override public void setTarget (Actor actor) { this.target = actor; this.startScaleX = target.scaleX; - this.deltaScaleX= scaleX - target.scaleX; + this.deltaScaleX = scaleX - target.scaleX; this.startScaleY = target.scaleY; - this.deltaScaleY= scaleY - target.scaleY; + this.deltaScaleY = scaleY - target.scaleY; this.taken = 0; this.done = false; } - @Override - public void act(float delta) - { + @Override public void act (float delta) { taken += delta; - if( taken >= duration ) - { + if (taken >= duration) { taken = duration; target.scaleX = scaleX; target.scaleY = scaleY; done = true; return; } - + float alpha = taken * invDuration; target.scaleX = startScaleX + deltaScaleX * alpha; target.scaleY = startScaleY + deltaScaleY * alpha; } - @Override - public boolean isDone() - { + @Override public boolean isDone () { return done; } - - @Override - public void finish() - { - pool.free( this ); + + @Override public void finish () { + pool.free(this); } - @Override - public Action copy() - { - return $( scaleX, scaleY, duration ); + @Override public Action copy () { + return $(scaleX, scaleY, duration); } } - diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Sequence.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Sequence.java index 2652a3430..41b688e71 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Sequence.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Sequence.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.scenes.scene2d.actions; import java.util.ArrayList; @@ -8,79 +9,62 @@ import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Pool; import com.badlogic.gdx.utils.Pool.PoolObjectFactory; -public class Sequence implements Action -{ - static final Pool pool = new Pool( new PoolObjectFactory() { - @Override - public Sequence createObject() - { - return new Sequence( ); +public class Sequence implements Action { + static final Pool pool = new Pool(new PoolObjectFactory() { + @Override public Sequence createObject () { + return new Sequence(); } - }, 100 ); - - private final List actions = new ArrayList( ); + }, 100); + + private final List actions = new ArrayList(); private Actor target; private int currAction = 0; - - public static Sequence $( Action ... actions ) - { + + public static Sequence $ (Action... actions) { Sequence action = pool.newObject(); action.actions.clear(); int len = actions.length; - for( int i = 0; i < len; i++ ) - action.actions.add( actions[i] ); + for (int i = 0; i < len; i++) + action.actions.add(actions[i]); return action; } - - @Override - public void setTarget(Actor actor) - { + + @Override public void setTarget (Actor actor) { this.target = actor; - if( actions.size() > 0 ) - actions.get(0).setTarget( target ); + if (actions.size() > 0) actions.get(0).setTarget(target); this.currAction = 0; } - @Override - public void act(float delta) - { - if( actions.size() == 0 ) - { + @Override public void act (float delta) { + if (actions.size() == 0) { currAction = 1; return; } - - actions.get(currAction).act( delta ); - if( actions.get(currAction).isDone() ) - { + + actions.get(currAction).act(delta); + if (actions.get(currAction).isDone()) { currAction++; - if( currAction < actions.size() ) - actions.get(currAction).setTarget( target ); + if (currAction < actions.size()) actions.get(currAction).setTarget(target); } } - @Override - public boolean isDone() - { + @Override public boolean isDone () { return currAction == actions.size(); } - - @Override - public void finish() - { - pool.free( this ); + + @Override public void finish () { + pool.free(this); int len = 0; - for( int i = 0; i < len; i++ ) + for (int i = 0; i < len; i++) actions.get(i).finish(); } - - @Override - public Action copy() { + + @Override public Action copy () { Sequence action = pool.newObject(); action.actions.clear(); int len = actions.size(); - for( int i = 0; i < len; i++ ) - action.actions.add( actions.get(i).copy() ); + for (int i = 0; i < len; i++) + action.actions.add(actions.get(i).copy()); return action; } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/BoundGroup.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/BoundGroup.java index eb86d240c..96a356d93 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/BoundGroup.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/BoundGroup.java @@ -1,69 +1,51 @@ + package com.badlogic.gdx.scenes.scene2d.actors; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Group; /** - * This is a group that respects its width and height. Useful for implementing - * layouts. + * This is a group that respects its width and height. Useful for implementing layouts. * @author mzechner - * + * */ -public class BoundGroup extends Group -{ - public BoundGroup(String name, float width, float height ) - { - super(name); +public class BoundGroup extends Group { + public BoundGroup (String name, float width, float height) { + super(name); this.width = width; this.height = height; this.originX = width / 2; this.originY = height / 2; } - - protected boolean touchDown( float x, float y, int pointer ) - { - if( focusedActor != null ) - { + + protected boolean touchDown (float x, float y, int pointer) { + if (focusedActor != null) { + return super.touchDown(x, y, pointer); + } else { + if (!(x > 0 && y > 0 && x < width && y < height)) return false; return super.touchDown(x, y, pointer); } - else - { - if( !(x > 0 && y > 0 && x < width && y < height) ) - return false; - return super.touchDown( x, y, pointer ); - } } - - protected boolean touchUp( float x, float y, int pointer ) - { - if( focusedActor != null ) - { + + protected boolean touchUp (float x, float y, int pointer) { + if (focusedActor != null) { return super.touchUp(x, y, pointer); - } - else - { - if( !(x > 0 && y > 0 && x < width && y < height) ) - return false; + } else { + if (!(x > 0 && y > 0 && x < width && y < height)) return false; return super.touchUp(x, y, pointer); - } + } } - - protected boolean touchDragged( float x, float y, int pointer ) - { - if( focusedActor != null ) - { + + protected boolean touchDragged (float x, float y, int pointer) { + if (focusedActor != null) { return super.touchDragged(x, y, pointer); - } - else - { - if( !(x > 0 && y > 0 && x < width && y < height) ) - return false; + } else { + if (!(x > 0 && y > 0 && x < width && y < height)) return false; return super.touchDragged(x, y, pointer); - } + } } - - public Actor hit( float x, float y ) - { - return x > 0 && y > 0 && x < width && y < height? this: null; + + public Actor hit (float x, float y) { + return x > 0 && y > 0 && x < width && y < height ? this : null; } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/Button.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/Button.java index b9b34dc47..2583f8f9b 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/Button.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/Button.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.scenes.scene2d.actors; import com.badlogic.gdx.graphics.SpriteBatch; @@ -5,98 +6,83 @@ import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.TextureRegion; import com.badlogic.gdx.scenes.scene2d.Actor; -public class Button extends Actor -{ - public interface ClickListener - { - public void clicked( Button button ); +public class Button extends Actor { + public interface ClickListener { + public void clicked (Button button); } - + public final TextureRegion pressedRegion; public final TextureRegion unpressedRegion; public ClickListener clickListener; private boolean pressed = false; - - public Button( String name ) - { - super( name ); - this.pressedRegion = new TextureRegion( null, 0, 0, 0, 0 ); - this.unpressedRegion = new TextureRegion( null, 0, 0, 0, 0 ); + + public Button (String name) { + super(name); + this.pressedRegion = new TextureRegion(null, 0, 0, 0, 0); + this.unpressedRegion = new TextureRegion(null, 0, 0, 0, 0); } - - public Button( String name, Texture texture ) - { - super( name ); + + public Button (String name, Texture texture) { + super(name); this.originX = texture.getWidth() / 2.0f; this.originY = texture.getHeight() / 2.0f; this.width = texture.getWidth(); this.height = texture.getHeight(); - this.pressedRegion = new TextureRegion( texture, 0, 0, texture.getWidth(), texture.getHeight() ); - this.unpressedRegion = new TextureRegion( texture, 0, 0, texture.getWidth(), texture.getHeight() ); + this.pressedRegion = new TextureRegion(texture, 0, 0, texture.getWidth(), texture.getHeight()); + this.unpressedRegion = new TextureRegion(texture, 0, 0, texture.getWidth(), texture.getHeight()); } - - public Button( String name, TextureRegion region ) - { - this( name, region, region ); + + public Button (String name, TextureRegion region) { + this(name, region, region); } - - public Button( String name, TextureRegion unpressedRegion, TextureRegion pressedRegion ) - { - super( name ); + + public Button (String name, TextureRegion unpressedRegion, TextureRegion pressedRegion) { + super(name); this.originX = unpressedRegion.width / 2.0f; this.originY = unpressedRegion.height / 2.0f; this.width = unpressedRegion.width; this.height = unpressedRegion.height; - this.unpressedRegion = new TextureRegion( unpressedRegion.texture, unpressedRegion.x, unpressedRegion.y, unpressedRegion.width, unpressedRegion.height ); - this.pressedRegion = new TextureRegion( pressedRegion.texture, pressedRegion.x, pressedRegion.y, pressedRegion.width, pressedRegion.height ); + this.unpressedRegion = new TextureRegion(unpressedRegion.texture, unpressedRegion.x, unpressedRegion.y, + unpressedRegion.width, unpressedRegion.height); + this.pressedRegion = new TextureRegion(pressedRegion.texture, pressedRegion.x, pressedRegion.y, pressedRegion.width, + pressedRegion.height); } - - @Override - protected void render(SpriteBatch batch) - { - TextureRegion region = pressed?pressedRegion:unpressedRegion; - - if( region.texture != null ) - { - if( scaleX == 0 && scaleY == 0 && rotation == 0 ) - batch.draw( region.texture, x, y, width, height, region.x, region.y, region.width, region.height, color, false, false ); + + @Override protected void render (SpriteBatch batch) { + TextureRegion region = pressed ? pressedRegion : unpressedRegion; + + if (region.texture != null) { + if (scaleX == 0 && scaleY == 0 && rotation == 0) + batch.draw(region.texture, x, y, width, height, region.x, region.y, region.width, region.height, color, false, false); else - batch.draw( region.texture, x, y, originX, originY, width, height, scaleX, scaleY, rotation, region.x, region.y, region.width, region.height, color, false, false ); + batch.draw(region.texture, x, y, originX, originY, width, height, scaleX, scaleY, rotation, region.x, region.y, + region.width, region.height, color, false, false); } } - @Override - protected boolean touchDown(float x, float y, int pointer) { + @Override protected boolean touchDown (float x, float y, int pointer) { boolean result = x > 0 && y > 0 && x < width && y < height; pressed = result; - if( pressed ) - parent.focus( this ); + if (pressed) parent.focus(this); return result; } - @Override - protected boolean touchUp(float x, float y, int pointer) - { - if( !pressed ) - return false; - - parent.focus( null ); + @Override protected boolean touchUp (float x, float y, int pointer) { + if (!pressed) return false; + + parent.focus(null); pressed = false; - if( clickListener != null ) - clickListener.clicked( this ); + if (clickListener != null) clickListener.clicked(this); return true; } - @Override - protected boolean touchDragged(float x, float y, int pointer) - { + @Override protected boolean touchDragged (float x, float y, int pointer) { return true; } - public Actor hit( float x, float y ) - { - return x > 0 && y > 0 && x < width && y < height? this: null; + public Actor hit (float x, float y) { + return x > 0 && y > 0 && x < width && y < height ? this : null; } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/Image.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/Image.java index 629f442c9..e1ab9c5b4 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/Image.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/Image.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.actors; import com.badlogic.gdx.graphics.SpriteBatch; @@ -20,71 +18,59 @@ import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.TextureRegion; import com.badlogic.gdx.scenes.scene2d.Actor; -public class Image extends Actor -{ +public class Image extends Actor { public final TextureRegion region; - - public Image( String name ) - { - super( name ); - this.region = new TextureRegion( null, 0, 0, 0, 0 ); + + public Image (String name) { + super(name); + this.region = new TextureRegion(null, 0, 0, 0, 0); } - - public Image( String name, Texture texture ) - { - super( name ); + + public Image (String name, Texture texture) { + super(name); this.originX = texture.getWidth() / 2.0f; this.originY = texture.getHeight() / 2.0f; this.width = texture.getWidth(); this.height = texture.getHeight(); - this.region = new TextureRegion( texture, 0, 0, texture.getWidth(), texture.getHeight() ); + this.region = new TextureRegion(texture, 0, 0, texture.getWidth(), texture.getHeight()); } - - public Image( String name, TextureRegion region ) - { - super( name ); + + public Image (String name, TextureRegion region) { + super(name); this.originX = region.width / 2.0f; this.originY = region.height / 2.0f; this.width = region.width; this.height = region.height; - this.region = new TextureRegion( region.texture, region.x, region.y, region.width, region.height ); + this.region = new TextureRegion(region.texture, region.x, region.y, region.width, region.height); } - - @Override - protected void render(SpriteBatch batch) - { - if( region.texture != null ) - { - if( scaleX == 0 && scaleY == 0 && rotation == 0 ) - batch.draw( region.texture, x, y, width, height, region.x, region.y, region.width, region.height, color, false, false ); + + @Override protected void render (SpriteBatch batch) { + if (region.texture != null) { + if (scaleX == 0 && scaleY == 0 && rotation == 0) + batch.draw(region.texture, x, y, width, height, region.x, region.y, region.width, region.height, color, false, false); else - batch.draw( region.texture, x, y, originX, originY, width, height, scaleX, scaleY, rotation, region.x, region.y, region.width, region.height, color, false, false ); + batch.draw(region.texture, x, y, originX, originY, width, height, scaleX, scaleY, rotation, region.x, region.y, + region.width, region.height, color, false, false); } } - @Override - protected boolean touchDown(float x, float y, int pointer) { + @Override protected boolean touchDown (float x, float y, int pointer) { return x > 0 && y > 0 && x < width && y < height; } - @Override - protected boolean touchUp(float x, float y, int pointer) { + @Override protected boolean touchUp (float x, float y, int pointer) { // TODO Auto-generated method stub return false; } - @Override - protected boolean touchDragged(float x, float y, int pointer) { + @Override protected boolean touchDragged (float x, float y, int pointer) { // TODO Auto-generated method stub return false; } - public Actor hit( float x, float y ) - { - if( x > 0 && x < width ) - if( y > 0 && y < height ) - return this; - + public Actor hit (float x, float y) { + if (x > 0 && x < width) if (y > 0 && y < height) return this; + return null; } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/Label.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/Label.java index e378239d9..1f8f10722 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/Label.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/Label.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.scenes.scene2d.actors; import com.badlogic.gdx.graphics.Color; @@ -5,49 +6,37 @@ import com.badlogic.gdx.graphics.Font; import com.badlogic.gdx.graphics.SpriteBatch; import com.badlogic.gdx.scenes.scene2d.Actor; -public class Label extends Actor -{ +public class Label extends Actor { public Font font; public String text; - public final Color color = new Color( 1, 1, 1, 1 ); - - public Label( String name, Font font, String text ) - { + public final Color color = new Color(1, 1, 1, 1); + + public Label (String name, Font font, String text) { super(name); this.font = font; this.text = text; - this.width = font.getStringWidth( text ); + this.width = font.getStringWidth(text); this.height = font.getLineHeight(); } - - @Override - protected void render(SpriteBatch batch) - { - batch.drawText( font, text, x, y, color ); + + @Override protected void render (SpriteBatch batch) { + batch.drawText(font, text, x, y, color); } - @Override - protected boolean touchDown(float x, float y, int pointer) - { - return x > 0 && y > 0 && x < font.getStringWidth( text ) && x < font.getLineHeight() ; + @Override protected boolean touchDown (float x, float y, int pointer) { + return x > 0 && y > 0 && x < font.getStringWidth(text) && x < font.getLineHeight(); } - @Override - protected boolean touchUp(float x, float y, int pointer) - { - return x > 0 && y > 0 && x < font.getStringWidth( text ) && x < font.getLineHeight() ; + @Override protected boolean touchUp (float x, float y, int pointer) { + return x > 0 && y > 0 && x < font.getStringWidth(text) && x < font.getLineHeight(); } - @Override - protected boolean touchDragged(float x, float y, int pointer) - { - return x > 0 && y > 0 && x < font.getStringWidth( text ) && x < font.getLineHeight() ; + @Override protected boolean touchDragged (float x, float y, int pointer) { + return x > 0 && y > 0 && x < font.getStringWidth(text) && x < font.getLineHeight(); } - @Override - public Actor hit(float x, float y) - { - return x > 0 && y > 0 && x < font.getStringWidth( text ) && x < font.getLineHeight()?this:null ; + @Override public Actor hit (float x, float y) { + return x > 0 && y > 0 && x < font.getStringWidth(text) && x < font.getLineHeight() ? this : null; } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/LinearGroup.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/LinearGroup.java index 00445bb9d..b3c1a3fb6 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/LinearGroup.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/LinearGroup.java @@ -1,50 +1,44 @@ + package com.badlogic.gdx.scenes.scene2d.actors; import com.badlogic.gdx.GdxRuntimeException; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Group; -public class LinearGroup extends BoundGroup -{ - public static enum LinearGroupLayout - { - Vertical, - Horizontal +public class LinearGroup extends BoundGroup { + public static enum LinearGroupLayout { + Vertical, Horizontal } - + private final LinearGroupLayout layout; - - public LinearGroup(String name, int width, int height, LinearGroupLayout layout ) - { - super(name, width, height); + + public LinearGroup (String name, int width, int height, LinearGroupLayout layout) { + super(name, width, height); this.layout = layout; } - - public void addActor( Actor actor ) - { - if( actor instanceof Group && !(actor instanceof BoundGroup) ) - throw new GdxRuntimeException( "Can only add Actors and BoundGroup subclasses" ); - - super.addActor( actor ); - layout( ); + + public void addActor (Actor actor) { + if (actor instanceof Group && !(actor instanceof BoundGroup)) + throw new GdxRuntimeException("Can only add Actors and BoundGroup subclasses"); + + super.addActor(actor); + layout(); } - - public void removeActor( Actor actor ) - { - super.removeActor( actor ); + + public void removeActor (Actor actor) { + super.removeActor(actor); layout(); } - - protected void layout( ) - { + + protected void layout () { int len = getActors().size(); float x = 0; float y = 0; - for( int i = 0; i < len; i++ ) - { + for (int i = 0; i < len; i++) { Actor actor = getActors().get(i); - actor.x = x; actor.y = y; - if( layout == LinearGroupLayout.Horizontal ) + actor.x = x; + actor.y = y; + if (layout == LinearGroupLayout.Horizontal) x += actor.width; else y += actor.height; diff --git a/gdx/src/com/badlogic/gdx/utils/BufferUtils.java b/gdx/src/com/badlogic/gdx/utils/BufferUtils.java index 74d154ffb..9da18ef5f 100644 --- a/gdx/src/com/badlogic/gdx/utils/BufferUtils.java +++ b/gdx/src/com/badlogic/gdx/utils/BufferUtils.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.utils; import java.nio.Buffer; @@ -8,76 +9,64 @@ import java.nio.IntBuffer; import java.nio.ShortBuffer; /** - * Class with static helper methods to increase the speed of - * array/direct buffer and direct buffer/direct buffer transfers + * Class with static helper methods to increase the speed of array/direct buffer and direct buffer/direct buffer transfers * * @author mzechner - * + * */ -public class BufferUtils -{ +public class BufferUtils { /** - * Copies numFloats floats from src starting at offset to dst. Dst is - * assumed to be a direct {@link Buffer}. The method will crash if that - * is not the case. The position and limit of the buffer are ignored, the copy - * is placed at position 0 in the buffer. After the copying process the position - * of the buffer is set to 0 and its limit is set to numFloats * 4 if it is a - * ByteBuffer and numFloats if it is a FloatBuffer. In case the Buffer is neither - * a ByteBuffer nor a FloatBuffer the limit is not set. This is an expert method, - * use at your own risk. + * Copies numFloats floats from src starting at offset to dst. Dst is assumed to be a direct {@link Buffer}. The method will + * crash if that is not the case. The position and limit of the buffer are ignored, the copy is placed at position 0 in the + * buffer. After the copying process the position of the buffer is set to 0 and its limit is set to numFloats * 4 if it is a + * ByteBuffer and numFloats if it is a FloatBuffer. In case the Buffer is neither a ByteBuffer nor a FloatBuffer the limit is + * not set. This is an expert method, use at your own risk. * * @param src the source array * @param dst the destination buffer, has to be a direct Buffer * @param numFloats the number of floats to copy * @param offset the offset in src to start copying from */ - public static void copy( float[] src, Buffer dst, int numFloats, int offset ) - { - copyJni( src, dst, numFloats, offset ); - dst.position(0); - - if( dst instanceof ByteBuffer ) + public static void copy (float[] src, Buffer dst, int numFloats, int offset) { + copyJni(src, dst, numFloats, offset); + dst.position(0); + + if (dst instanceof ByteBuffer) dst.limit(numFloats << 2); - else - if( dst instanceof FloatBuffer ) - dst.limit(numFloats); + else if (dst instanceof FloatBuffer) dst.limit(numFloats); } - - private native static void copyJni( float[] src, Buffer dst, int numFloats, int offset ); - -// private native static void copyJni( Buffer src, Buffer dst, int numBytes ); - - public static native float int2float( int value ); - - public static native int float2int( float value ); - - public static native boolean bitEqual( int value1, float value2 ); - - public static FloatBuffer newFloatBuffer( int numFloats ) - { - ByteBuffer buffer = ByteBuffer.allocateDirect( numFloats * Float.SIZE / 8 ); - buffer.order( ByteOrder.nativeOrder() ); + + private native static void copyJni (float[] src, Buffer dst, int numFloats, int offset); + +// private native static void copyJni( Buffer src, Buffer dst, int numBytes ); + + public static native float int2float (int value); + + public static native int float2int (float value); + + public static native boolean bitEqual (int value1, float value2); + + public static FloatBuffer newFloatBuffer (int numFloats) { + ByteBuffer buffer = ByteBuffer.allocateDirect(numFloats * Float.SIZE / 8); + buffer.order(ByteOrder.nativeOrder()); return buffer.asFloatBuffer(); } - - public static ShortBuffer newShortBuffer( int numShorts ) - { - ByteBuffer buffer = ByteBuffer.allocateDirect( numShorts * Short.SIZE / 8 ); - buffer.order( ByteOrder.nativeOrder() ); + + public static ShortBuffer newShortBuffer (int numShorts) { + ByteBuffer buffer = ByteBuffer.allocateDirect(numShorts * Short.SIZE / 8); + buffer.order(ByteOrder.nativeOrder()); return buffer.asShortBuffer(); } - - public static IntBuffer newIntBuffer( int numInts ) - { - ByteBuffer buffer = ByteBuffer.allocateDirect( numInts * Integer.SIZE / 8 ); - buffer.order( ByteOrder.nativeOrder() ); + + public static IntBuffer newIntBuffer (int numInts) { + ByteBuffer buffer = ByteBuffer.allocateDirect(numInts * Integer.SIZE / 8); + buffer.order(ByteOrder.nativeOrder()); return buffer.asIntBuffer(); } - - public static ByteBuffer newByteBuffer( int numBytes ) - { - ByteBuffer buffer = ByteBuffer.allocateDirect( numBytes * Byte.SIZE / 8 ); - buffer.order( ByteOrder.nativeOrder() ); + + public static ByteBuffer newByteBuffer (int numBytes) { + ByteBuffer buffer = ByteBuffer.allocateDirect(numBytes * Byte.SIZE / 8); + buffer.order(ByteOrder.nativeOrder()); return buffer; } } diff --git a/gdx/src/com/badlogic/gdx/utils/IntHashMap.java b/gdx/src/com/badlogic/gdx/utils/IntHashMap.java index 5b936b1c3..9dab36908 100644 --- a/gdx/src/com/badlogic/gdx/utils/IntHashMap.java +++ b/gdx/src/com/badlogic/gdx/utils/IntHashMap.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.utils; import java.util.Iterator; @@ -6,220 +7,194 @@ import java.util.Iterator; * An int to object hashmap, taken from Amarena2D (thanks Christoph :p). * * @author christop widulle - * + * * @param */ public class IntHashMap { - - private Entry[] table; - private float loadFactor; - private int size, mask, capacity, threshold; - - public IntHashMap () { - this(16, 0.75f); - } - - public IntHashMap (int initialCapacity) { - this(initialCapacity, 0.75f); - } - - public IntHashMap (int initialCapacity, float loadFactor) { - if (initialCapacity > 1 << 30) throw new IllegalArgumentException("initialCapacity is too large."); - if (initialCapacity < 0) throw new IllegalArgumentException("initialCapacity must be greater than zero."); - if (loadFactor <= 0) throw new IllegalArgumentException("initialCapacity must be greater than zero."); - capacity = 1; - while (capacity < initialCapacity) { - capacity <<= 1; - } - this.loadFactor = loadFactor; - this.threshold = (int)(capacity * loadFactor); - this.table = new Entry[capacity]; - this.mask = capacity - 1; - } - - public boolean containsValue (Object value) { - Entry[] table = this.table; - for (int i = table.length; i-- > 0;) - for (Entry e = table[i]; e != null; e = e.next) - if (e.value.equals(value)) return true; - return false; - } - - public boolean containsKey (long key) { - int index = ((int)key) & mask; - for (Entry e = table[index]; e != null; e = e.next) - if (e.key == key) return true; - return false; - } - - @SuppressWarnings("unchecked") - public T get (int key) { - int index = key & mask; - for (Entry e = table[index]; e != null; e = e.next) - if (e.key == key) return (T)e.value; - return null; - } - - @SuppressWarnings("unchecked") - public T put (int key, T value) { - int index = key & mask; - // Check if key already exists. - for (Entry e = table[index]; e != null; e = e.next) { - if (e.key != key) continue; - Object oldValue = e.value; - e.value = value; - return (T)oldValue; - } - table[index] = new Entry(key, value, table[index]); - if (size++ >= threshold) { - // Rehash. - int newCapacity = 2 * capacity; - Entry[] newTable = new Entry[newCapacity]; - Entry[] src = table; - int bucketmask = newCapacity - 1; - for (int j = 0; j < src.length; j++) { - Entry e = src[j]; - if (e != null) { - src[j] = null; - do { - Entry next = e.next; - index = e.key & bucketmask; - e.next = newTable[index]; - newTable[index] = e; - e = next; - } while (e != null); - } - } - table = newTable; - capacity = newCapacity; - threshold = (int)(newCapacity * loadFactor); - mask = capacity - 1; - } - return null; - } - - @SuppressWarnings("unchecked") - public T remove (int key) { - int index = key & mask; - Entry prev = table[index]; - Entry e = prev; - while (e != null) { - Entry next = e.next; - if (e.key == key) { - size--; - if (prev == e) { - table[index] = next; - } else { - prev.next = next; - } - return (T)e.value; - } - prev = e; - e = next; - } - return null; - } - - public int size () { - return size; - } - - public void clear () { - Entry[] table = this.table; - for (int index = table.length; --index >= 0;) - table[index] = null; - size = 0; - } - - static class Entry { - final int key; - Object value; - Entry next; - - Entry (int k, Object v, Entry n) { - key = k; - value = v; - next = n; - } - } - - EntryIterable iterable = new EntryIterable( ); - - public Iterable values() - { - iterable.reset( ); + + private Entry[] table; + private float loadFactor; + private int size, mask, capacity, threshold; + + public IntHashMap () { + this(16, 0.75f); + } + + public IntHashMap (int initialCapacity) { + this(initialCapacity, 0.75f); + } + + public IntHashMap (int initialCapacity, float loadFactor) { + if (initialCapacity > 1 << 30) throw new IllegalArgumentException("initialCapacity is too large."); + if (initialCapacity < 0) throw new IllegalArgumentException("initialCapacity must be greater than zero."); + if (loadFactor <= 0) throw new IllegalArgumentException("initialCapacity must be greater than zero."); + capacity = 1; + while (capacity < initialCapacity) { + capacity <<= 1; + } + this.loadFactor = loadFactor; + this.threshold = (int)(capacity * loadFactor); + this.table = new Entry[capacity]; + this.mask = capacity - 1; + } + + public boolean containsValue (Object value) { + Entry[] table = this.table; + for (int i = table.length; i-- > 0;) + for (Entry e = table[i]; e != null; e = e.next) + if (e.value.equals(value)) return true; + return false; + } + + public boolean containsKey (long key) { + int index = ((int)key) & mask; + for (Entry e = table[index]; e != null; e = e.next) + if (e.key == key) return true; + return false; + } + + @SuppressWarnings("unchecked") public T get (int key) { + int index = key & mask; + for (Entry e = table[index]; e != null; e = e.next) + if (e.key == key) return (T)e.value; + return null; + } + + @SuppressWarnings("unchecked") public T put (int key, T value) { + int index = key & mask; + // Check if key already exists. + for (Entry e = table[index]; e != null; e = e.next) { + if (e.key != key) continue; + Object oldValue = e.value; + e.value = value; + return (T)oldValue; + } + table[index] = new Entry(key, value, table[index]); + if (size++ >= threshold) { + // Rehash. + int newCapacity = 2 * capacity; + Entry[] newTable = new Entry[newCapacity]; + Entry[] src = table; + int bucketmask = newCapacity - 1; + for (int j = 0; j < src.length; j++) { + Entry e = src[j]; + if (e != null) { + src[j] = null; + do { + Entry next = e.next; + index = e.key & bucketmask; + e.next = newTable[index]; + newTable[index] = e; + e = next; + } while (e != null); + } + } + table = newTable; + capacity = newCapacity; + threshold = (int)(newCapacity * loadFactor); + mask = capacity - 1; + } + return null; + } + + @SuppressWarnings("unchecked") public T remove (int key) { + int index = key & mask; + Entry prev = table[index]; + Entry e = prev; + while (e != null) { + Entry next = e.next; + if (e.key == key) { + size--; + if (prev == e) { + table[index] = next; + } else { + prev.next = next; + } + return (T)e.value; + } + prev = e; + e = next; + } + return null; + } + + public int size () { + return size; + } + + public void clear () { + Entry[] table = this.table; + for (int index = table.length; --index >= 0;) + table[index] = null; + size = 0; + } + + static class Entry { + final int key; + Object value; + Entry next; + + Entry (int k, Object v, Entry n) { + key = k; + value = v; + next = n; + } + } + + EntryIterable iterable = new EntryIterable(); + + public Iterable values () { + iterable.reset(); return iterable; } - - class EntryIterable implements Iterable - { + + class EntryIterable implements Iterable { int currIndex = -1; Entry currEntry = null; - - Iterator iter = new Iterator( ) - { - @Override - public boolean hasNext() - { - if( currEntry == null ) - { - if( !loadNextEntry() ) - return false; - } - else - { - if( currEntry.next == null && loadNextEntry() == false ) - return false; + + Iterator iter = new Iterator() { + @Override public boolean hasNext () { + if (currEntry == null) { + if (!loadNextEntry()) return false; + } else { + if (currEntry.next == null && loadNextEntry() == false) return false; } - + return true; } - - private boolean loadNextEntry( ) - { - while( true ) - { + + private boolean loadNextEntry () { + while (true) { currIndex++; - if( currIndex >= table.length ) - return false; - - if( table[currIndex] == null ) + if (currIndex >= table.length) return false; + + if (table[currIndex] == null) continue; - else - { + else { currEntry = table[currIndex]; return true; } - } + } } - @SuppressWarnings("unchecked") - @Override - public T next() - { + @SuppressWarnings("unchecked") @Override public T next () { return (T)currEntry.value; } - @Override - public void remove() - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void remove () { + throw new UnsupportedOperationException("not implemented"); } - + }; - - public void reset( ) - { + + public void reset () { currIndex = -1; currEntry = null; } - - @Override - public Iterator iterator() - { + + @Override public Iterator iterator () { return iter; } - + } } - diff --git a/gdx/src/com/badlogic/gdx/utils/LittleEndianInputStream.java b/gdx/src/com/badlogic/gdx/utils/LittleEndianInputStream.java index 1c7183986..ad5ce77e0 100644 --- a/gdx/src/com/badlogic/gdx/utils/LittleEndianInputStream.java +++ b/gdx/src/com/badlogic/gdx/utils/LittleEndianInputStream.java @@ -1,172 +1,162 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.utils; -import java.io.*; +import java.io.EOFException; +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UTFDataFormatException; /** * Taken from http://www.javafaq.nu/java-example-code-1079.html * @author mzechner - * + * */ public class LittleEndianInputStream extends FilterInputStream { - public LittleEndianInputStream(InputStream in) { - super(in); - } - - public boolean readBoolean() throws IOException { - int bool = in.read(); - if (bool == -1) throw new EOFException(); - return (bool != 0); - } - - public byte readByte(int b) throws IOException { - int temp = in.read(); - if (temp == -1) throw new EOFException(); - return (byte) temp; - } - - public int readUnsignedByte() throws IOException { - int temp = in.read(); - if (temp == -1) throw new EOFException(); - return temp; - } - - public short readShort() throws IOException { - int byte1 = in.read(); - int byte2 = in.read(); - // only need to test last byte read - // if byte1 is -1 so is byte2 - if (byte2 == -1) throw new EOFException(); - return (short) (((byte2 << 24) >>> 16) + (byte1 << 24) >>> 24); - } - - public int readUnsignedShort() throws IOException { - int byte1 = in.read(); - int byte2 = in.read(); - if (byte2 == -1) throw new EOFException(); - return ((byte2 << 24) >> 16) + ((byte1 << 24) >> 24); - } - - public char readChar() throws IOException { - int byte1 = in.read(); - int byte2 = in.read(); - if (byte2 == -1) throw new EOFException(); - return (char) (((byte2 << 24) >>> 16) + ((byte1 << 24) >>> 24)); - } - - public int readInt() throws IOException { - - int byte1 = in.read(); - int byte2 = in.read(); - int byte3 = in.read(); - int byte4 = in.read(); - if (byte4 == -1) { - throw new EOFException(); - } - return (byte4 << 24) - + ((byte3 << 24) >>> 8) - + ((byte2 << 24) >>> 16) - + ((byte1 << 24) >>> 24); - - } - - public long readLong() throws IOException { - - long byte1 = in.read(); - long byte2 = in.read(); - long byte3 = in.read(); - long byte4 = in.read(); - long byte5 = in.read(); - long byte6 = in.read(); - long byte7 = in.read(); - long byte8 = in.read(); - if (byte8 == -1) { - throw new EOFException(); - } - return (byte8 << 56) - + ((byte7 << 56) >>> 8) - + ((byte6 << 56) >>> 16) - + ((byte5 << 56) >>> 24) - + ((byte4 << 56) >>> 32) - + ((byte3 << 56) >>> 40) - + ((byte2 << 56) >>> 48) - + ((byte1 << 56) >>> 56); - - } - - public String readUTF() throws IOException { - - int byte1 = in.read(); - int byte2 = in.read(); - if (byte2 == -1) throw new EOFException(); - int numbytes = (byte1 << 8) + byte2; - char result[] = new char[numbytes]; - int numread = 0; - int numchars = 0; - - while (numread < numbytes) { - - int c1 = readUnsignedByte(); - - // The first 4 bits of c1 determine how many bytes are in this char - int test = c1 >> 4; - if (test < 8) { // one byte - numread++; - result[numchars++] = (char) c1; - } - else if (test == 12 || test == 13) { // 2 bytes - numread += 2; - if (numread > numbytes) throw new UTFDataFormatException(); - int c2 = readUnsignedByte(); - if ((c2 & 0xC0) != 0x80) throw new UTFDataFormatException(); - result[numchars++] = (char) (((c1 & 0x1F) << 6) | (c2 & 0x3F)); - } - else if (test == 14) { // three bytes - numread += 3; - if (numread > numbytes) throw new UTFDataFormatException(); - int c2 = readUnsignedByte(); - int c3 = readUnsignedByte(); - if (((c2 & 0xC0) != 0x80) || ((c3 & 0xC0) != 0x80)) { - throw new UTFDataFormatException(); - } - result[numchars++] = (char) - (((c1 & 0x0F) << 12) | ((c2 & 0x3F) << 6) | (c3 & 0x3F)); - } - else { // malformed - throw new UTFDataFormatException(); - } - - } // end while - - return new String(result, 0, numchars); - - } - - public final double readDouble() throws IOException { - return Double.longBitsToDouble(this.readLong()); - } - - public final float readFloat() throws IOException { - return Float.intBitsToFloat(this.readInt()); - } - - public final int skipBytes(int n) throws IOException { - for (int i = 0; i < n; i += (int) skip(n - i)); - return n; - } + public LittleEndianInputStream (InputStream in) { + super(in); + } + + public boolean readBoolean () throws IOException { + int bool = in.read(); + if (bool == -1) throw new EOFException(); + return (bool != 0); + } + + public byte readByte (int b) throws IOException { + int temp = in.read(); + if (temp == -1) throw new EOFException(); + return (byte)temp; + } + + public int readUnsignedByte () throws IOException { + int temp = in.read(); + if (temp == -1) throw new EOFException(); + return temp; + } + + public short readShort () throws IOException { + int byte1 = in.read(); + int byte2 = in.read(); + // only need to test last byte read + // if byte1 is -1 so is byte2 + if (byte2 == -1) throw new EOFException(); + return (short)(((byte2 << 24) >>> 16) + (byte1 << 24) >>> 24); + } + + public int readUnsignedShort () throws IOException { + int byte1 = in.read(); + int byte2 = in.read(); + if (byte2 == -1) throw new EOFException(); + return ((byte2 << 24) >> 16) + ((byte1 << 24) >> 24); + } + + public char readChar () throws IOException { + int byte1 = in.read(); + int byte2 = in.read(); + if (byte2 == -1) throw new EOFException(); + return (char)(((byte2 << 24) >>> 16) + ((byte1 << 24) >>> 24)); + } + + public int readInt () throws IOException { + + int byte1 = in.read(); + int byte2 = in.read(); + int byte3 = in.read(); + int byte4 = in.read(); + if (byte4 == -1) { + throw new EOFException(); + } + return (byte4 << 24) + ((byte3 << 24) >>> 8) + ((byte2 << 24) >>> 16) + ((byte1 << 24) >>> 24); + + } + + public long readLong () throws IOException { + + long byte1 = in.read(); + long byte2 = in.read(); + long byte3 = in.read(); + long byte4 = in.read(); + long byte5 = in.read(); + long byte6 = in.read(); + long byte7 = in.read(); + long byte8 = in.read(); + if (byte8 == -1) { + throw new EOFException(); + } + return (byte8 << 56) + ((byte7 << 56) >>> 8) + ((byte6 << 56) >>> 16) + ((byte5 << 56) >>> 24) + ((byte4 << 56) >>> 32) + + ((byte3 << 56) >>> 40) + ((byte2 << 56) >>> 48) + ((byte1 << 56) >>> 56); + + } + + public String readUTF () throws IOException { + + int byte1 = in.read(); + int byte2 = in.read(); + if (byte2 == -1) throw new EOFException(); + int numbytes = (byte1 << 8) + byte2; + char result[] = new char[numbytes]; + int numread = 0; + int numchars = 0; + + while (numread < numbytes) { + + int c1 = readUnsignedByte(); + + // The first 4 bits of c1 determine how many bytes are in this char + int test = c1 >> 4; + if (test < 8) { // one byte + numread++; + result[numchars++] = (char)c1; + } else if (test == 12 || test == 13) { // 2 bytes + numread += 2; + if (numread > numbytes) throw new UTFDataFormatException(); + int c2 = readUnsignedByte(); + if ((c2 & 0xC0) != 0x80) throw new UTFDataFormatException(); + result[numchars++] = (char)(((c1 & 0x1F) << 6) | (c2 & 0x3F)); + } else if (test == 14) { // three bytes + numread += 3; + if (numread > numbytes) throw new UTFDataFormatException(); + int c2 = readUnsignedByte(); + int c3 = readUnsignedByte(); + if (((c2 & 0xC0) != 0x80) || ((c3 & 0xC0) != 0x80)) { + throw new UTFDataFormatException(); + } + result[numchars++] = (char)(((c1 & 0x0F) << 12) | ((c2 & 0x3F) << 6) | (c3 & 0x3F)); + } else { // malformed + throw new UTFDataFormatException(); + } + + } // end while + + return new String(result, 0, numchars); + + } + + public final double readDouble () throws IOException { + return Double.longBitsToDouble(this.readLong()); + } + + public final float readFloat () throws IOException { + return Float.intBitsToFloat(this.readInt()); + } + + public final int skipBytes (int n) throws IOException { + for (int i = 0; i < n; i += (int)skip(n - i)) + ; + return n; + } } diff --git a/gdx/src/com/badlogic/gdx/utils/LongHashMap.java b/gdx/src/com/badlogic/gdx/utils/LongHashMap.java index 52fe4ad61..1f583e089 100644 --- a/gdx/src/com/badlogic/gdx/utils/LongHashMap.java +++ b/gdx/src/com/badlogic/gdx/utils/LongHashMap.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.utils; import java.util.Iterator; @@ -6,225 +7,197 @@ import java.util.Iterator; * An long to object hashmap, taken from Amarena2D (thanks Christoph :p). * * @author christop widulle - * + * * @param */ public class LongHashMap { - - private Entry[] table; - private float loadFactor; - private int size, mask, capacity, threshold; - - public LongHashMap () { - this(16, 0.75f); - } - - public LongHashMap (int initialCapacity) { - this(initialCapacity, 0.75f); - } - - public LongHashMap (int initialCapacity, float loadFactor) { - if (initialCapacity > 1 << 30) throw new IllegalArgumentException("initialCapacity is too large."); - if (initialCapacity < 0) throw new IllegalArgumentException("initialCapacity must be greater than zero."); - if (loadFactor <= 0) throw new IllegalArgumentException("initialCapacity must be greater than zero."); - capacity = 1; - while (capacity < initialCapacity) { - capacity <<= 1; - } - this.loadFactor = loadFactor; - this.threshold = (int)(capacity * loadFactor); - this.table = new Entry[capacity]; - this.mask = capacity - 1; - } - - public boolean containsValue (Object value) { - Entry[] table = this.table; - for (int i = table.length; i-- > 0;) - for (Entry e = table[i]; e != null; e = e.next) - if (e.value.equals(value)) return true; - return false; - } - - public boolean containsKey (long key) { - int index = ((int)key) & mask; - for (Entry e = table[index]; e != null; e = e.next) - if (e.key == key) return true; - return false; - } - - @SuppressWarnings("unchecked") - public T get (long key) { - int index = (int)(key & mask); - for (Entry e = table[index]; e != null; e = e.next) - if (e.key == key) return (T)e.value; - return null; - } - - @SuppressWarnings("unchecked") - public T put (long key, T value) { - int index = (int)(key & mask); - // Check if key already exists. - for (Entry e = table[index]; e != null; e = e.next) { - if (e.key != key) continue; - Object oldValue = e.value; - e.value = value; - return (T)oldValue; - } - table[index] = new Entry(key, value, table[index]); - if (size++ >= threshold) { - // Rehash. - int newCapacity = 2 * capacity; - Entry[] newTable = new Entry[newCapacity]; - Entry[] src = table; - int bucketmask = newCapacity - 1; - for (int j = 0; j < src.length; j++) { - Entry e = src[j]; - if (e != null) { - src[j] = null; - do { - Entry next = e.next; - index = (int)(e.key & bucketmask); - e.next = newTable[index]; - newTable[index] = e; - e = next; - } while (e != null); - } - } - table = newTable; - capacity = newCapacity; - threshold = (int)(newCapacity * loadFactor); - mask = capacity - 1; - } - return null; - } - - @SuppressWarnings("unchecked") - public T remove (long key) { - int index = (int)(key & mask); - Entry prev = table[index]; - Entry e = prev; - while (e != null) { - Entry next = e.next; - if (e.key == key) { - size--; - if (prev == e) { - table[index] = next; - } else { - prev.next = next; - } - return (T)e.value; - } - prev = e; - e = next; - } - return null; - } - - public int size () { - return size; - } - - public void clear () { - Entry[] table = this.table; - for (int index = table.length; --index >= 0;) - table[index] = null; - size = 0; - } - - static class Entry { - final long key; - Object value; - Entry next; - - Entry (long k, Object v, Entry n) { - key = k; - value = v; - next = n; - } - } - - EntryIterable iterable = new EntryIterable( ); - - public Iterable values() - { - iterable.reset( ); + + private Entry[] table; + private float loadFactor; + private int size, mask, capacity, threshold; + + public LongHashMap () { + this(16, 0.75f); + } + + public LongHashMap (int initialCapacity) { + this(initialCapacity, 0.75f); + } + + public LongHashMap (int initialCapacity, float loadFactor) { + if (initialCapacity > 1 << 30) throw new IllegalArgumentException("initialCapacity is too large."); + if (initialCapacity < 0) throw new IllegalArgumentException("initialCapacity must be greater than zero."); + if (loadFactor <= 0) throw new IllegalArgumentException("initialCapacity must be greater than zero."); + capacity = 1; + while (capacity < initialCapacity) { + capacity <<= 1; + } + this.loadFactor = loadFactor; + this.threshold = (int)(capacity * loadFactor); + this.table = new Entry[capacity]; + this.mask = capacity - 1; + } + + public boolean containsValue (Object value) { + Entry[] table = this.table; + for (int i = table.length; i-- > 0;) + for (Entry e = table[i]; e != null; e = e.next) + if (e.value.equals(value)) return true; + return false; + } + + public boolean containsKey (long key) { + int index = ((int)key) & mask; + for (Entry e = table[index]; e != null; e = e.next) + if (e.key == key) return true; + return false; + } + + @SuppressWarnings("unchecked") public T get (long key) { + int index = (int)(key & mask); + for (Entry e = table[index]; e != null; e = e.next) + if (e.key == key) return (T)e.value; + return null; + } + + @SuppressWarnings("unchecked") public T put (long key, T value) { + int index = (int)(key & mask); + // Check if key already exists. + for (Entry e = table[index]; e != null; e = e.next) { + if (e.key != key) continue; + Object oldValue = e.value; + e.value = value; + return (T)oldValue; + } + table[index] = new Entry(key, value, table[index]); + if (size++ >= threshold) { + // Rehash. + int newCapacity = 2 * capacity; + Entry[] newTable = new Entry[newCapacity]; + Entry[] src = table; + int bucketmask = newCapacity - 1; + for (int j = 0; j < src.length; j++) { + Entry e = src[j]; + if (e != null) { + src[j] = null; + do { + Entry next = e.next; + index = (int)(e.key & bucketmask); + e.next = newTable[index]; + newTable[index] = e; + e = next; + } while (e != null); + } + } + table = newTable; + capacity = newCapacity; + threshold = (int)(newCapacity * loadFactor); + mask = capacity - 1; + } + return null; + } + + @SuppressWarnings("unchecked") public T remove (long key) { + int index = (int)(key & mask); + Entry prev = table[index]; + Entry e = prev; + while (e != null) { + Entry next = e.next; + if (e.key == key) { + size--; + if (prev == e) { + table[index] = next; + } else { + prev.next = next; + } + return (T)e.value; + } + prev = e; + e = next; + } + return null; + } + + public int size () { + return size; + } + + public void clear () { + Entry[] table = this.table; + for (int index = table.length; --index >= 0;) + table[index] = null; + size = 0; + } + + static class Entry { + final long key; + Object value; + Entry next; + + Entry (long k, Object v, Entry n) { + key = k; + value = v; + next = n; + } + } + + EntryIterable iterable = new EntryIterable(); + + public Iterable values () { + iterable.reset(); return iterable; } - - class EntryIterable implements Iterable - { + + class EntryIterable implements Iterable { int currIndex = -1; Entry currEntry = null; - - Iterator iter = new Iterator( ) - { - @Override - public boolean hasNext() - { - if( currEntry == null ) - { - if( !loadNextEntry() ) - return false; - } - else - { - if( currEntry.next == null ) - { - if( loadNextEntry() == false ) - return false; - } - else + + Iterator iter = new Iterator() { + @Override public boolean hasNext () { + if (currEntry == null) { + if (!loadNextEntry()) return false; + } else { + if (currEntry.next == null) { + if (loadNextEntry() == false) return false; + } else currEntry = currEntry.next; } - + return true; } - - private boolean loadNextEntry( ) - { - while( true ) - { + + private boolean loadNextEntry () { + while (true) { currIndex++; - if( currIndex >= table.length ) - return false; - - if( table[currIndex] == null ) + if (currIndex >= table.length) return false; + + if (table[currIndex] == null) continue; - else - { + else { currEntry = table[currIndex]; return true; } - } + } } - @SuppressWarnings("unchecked") - @Override - public T next() - { + @SuppressWarnings("unchecked") @Override public T next () { return (T)currEntry.value; } - @Override - public void remove() - { - throw new UnsupportedOperationException( "not implemented" ); + @Override public void remove () { + throw new UnsupportedOperationException("not implemented"); } - + }; - - public void reset( ) - { + + public void reset () { currIndex = -1; currEntry = null; } - - @Override - public Iterator iterator() - { + + @Override public Iterator iterator () { return iter; } - + } } - diff --git a/gdx/src/com/badlogic/gdx/utils/PauseableThread.java b/gdx/src/com/badlogic/gdx/utils/PauseableThread.java index 2aee18235..6e648cc08 100644 --- a/gdx/src/com/badlogic/gdx/utils/PauseableThread.java +++ b/gdx/src/com/badlogic/gdx/utils/PauseableThread.java @@ -1,87 +1,73 @@ + package com.badlogic.gdx.utils; /** - * A pausable thread. The runnable must not execute - * an inifite loop but should return control to the - * thread as often as possible so that the thread can - * actually pause. + * A pausable thread. The runnable must not execute an inifite loop but should return control to the thread as often as possible + * so that the thread can actually pause. * * @author mzechner - * + * */ -public class PauseableThread extends Thread -{ +public class PauseableThread extends Thread { final Runnable runnable; boolean paused = false; boolean exit = false; - + /** - * Constructs a new thread setting the runnable - * which will be called repeatadly in a loop. + * Constructs a new thread setting the runnable which will be called repeatadly in a loop. * * @param runnable the runnable. */ - public PauseableThread( Runnable runnable ) - { + public PauseableThread (Runnable runnable) { this.runnable = runnable; } - - public void run( ) - { - while( true ) - { - synchronized( this ) - { + + public void run () { + while (true) { + synchronized (this) { try { - while( paused ) + while (paused) wait(); } catch (InterruptedException e) { e.printStackTrace(); } - } - - if( exit ) - return; - + } + + if (exit) return; + runnable.run(); } } - + /** * Pauses the thread. This call is non-blocking */ - public void onPause( ) - { + public void onPause () { paused = true; } - + /** * Resumes the thread. This call is non-blocking */ - public void onResume( ) - { - synchronized( this ) - { + public void onResume () { + synchronized (this) { paused = false; - this.notifyAll(); + this.notifyAll(); } } - + /** * @return whether this thread is paused or not */ - public boolean isPaused( ) - { + public boolean isPaused () { return paused; } - + /** * Stops this thread */ - public void stopThread( ) - { + public void stopThread () { exit = true; - if( paused ) - onResume( ); + if (paused) onResume(); } } diff --git a/gdx/src/com/badlogic/gdx/utils/Pool.java b/gdx/src/com/badlogic/gdx/utils/Pool.java index 927b0caa6..957935314 100644 --- a/gdx/src/com/badlogic/gdx/utils/Pool.java +++ b/gdx/src/com/badlogic/gdx/utils/Pool.java @@ -1,72 +1,59 @@ + package com.badlogic.gdx.utils; import java.util.ArrayList; import java.util.List; /** - * A pool implementation used for object instances - * that should get reused instead of being collected - * by the garbage collector. To increase the speed of - * this class no method is provided to free individual - * object instances. Note that you should not hold on - * to the references of objects from this Pool once - * they've been marked as free by calling Pool.freeAll(). + * A pool implementation used for object instances that should get reused instead of being collected by the garbage collector. To + * increase the speed of this class no method is provided to free individual object instances. Note that you should not hold on to + * the references of objects from this Pool once they've been marked as free by calling Pool.freeAll(). * * @author mzechner - * + * * @param the type */ -@SuppressWarnings("unchecked") -public class Pool -{ +@SuppressWarnings("unchecked") public class Pool { /** - * Interface for an Object Factory to be used - * with this Pool + * Interface for an Object Factory to be used with this Pool * * @author mzechner - * + * * @param the type */ - public interface PoolObjectFactory - { - public T createObject( ); + public interface PoolObjectFactory { + public T createObject (); } - + /** the list of free objects **/ - private final List freeObjects = new ArrayList( ); + private final List freeObjects = new ArrayList(); /** the factory **/ private final PoolObjectFactory factory; /** maximum size of pool **/ private final int maxSize; - - - public Pool( PoolObjectFactory factory, int maxSize ) - { + + public Pool (PoolObjectFactory factory, int maxSize) { this.factory = factory; this.maxSize = maxSize; } - + /** - * Creates a new object either by taking it from the - * free object pool or by creating a new one if there - * are no free objects yet. + * Creates a new object either by taking it from the free object pool or by creating a new one if there are no free objects + * yet. * @return the object */ - public T newObject( ) - { + public T newObject () { T object = null; - - if( freeObjects.size() == 0 ) - object = factory.createObject( ); + + if (freeObjects.size() == 0) + object = factory.createObject(); else - object = freeObjects.remove( freeObjects.size() - 1 ); - - return object; + object = freeObjects.remove(freeObjects.size() - 1); + + return object; } - - public void free( T object ) - { - if( freeObjects.size() < maxSize ) - freeObjects.add( object ); + + public void free (T object) { + if (freeObjects.size() < maxSize) freeObjects.add(object); } } diff --git a/gdx/src/com/badlogic/gdx/utils/PooledLinkedList.java b/gdx/src/com/badlogic/gdx/utils/PooledLinkedList.java index 7d95da48e..7de163d09 100644 --- a/gdx/src/com/badlogic/gdx/utils/PooledLinkedList.java +++ b/gdx/src/com/badlogic/gdx/utils/PooledLinkedList.java @@ -1,139 +1,122 @@ + package com.badlogic.gdx.utils; import com.badlogic.gdx.utils.Pool.PoolObjectFactory; - /** - * A simple linked list that pools its nodes. This is a highly - * specialized class used in a couple of 2D scene graph classes. - * I wouldn't use it if i was you :) + * A simple linked list that pools its nodes. This is a highly specialized class used in a couple of 2D scene graph classes. I + * wouldn't use it if i was you :) * * @author mzechner - * + * */ -public class PooledLinkedList -{ - static final class Item - { +public class PooledLinkedList { + static final class Item { public T payload; public Item next; public Item prev; } - + private Item head; private Item tail; private Item iter; private Item curr; private int size = 0; - + private final Pool> pool; - - public PooledLinkedList( int maxPoolSize ) - { - this.pool = new Pool>( new PoolObjectFactory>() { - - @Override - public PooledLinkedList.Item createObject() { - return new Item( ); + + public PooledLinkedList (int maxPoolSize) { + this.pool = new Pool>(new PoolObjectFactory>() { + + @Override public PooledLinkedList.Item createObject () { + return new Item(); } - } , maxPoolSize ); + }, maxPoolSize); } - - public void add( T object ) - { + + public void add (T object) { Item item = pool.newObject(); item.payload = object; item.next = null; item.prev = null; - - if( head == null ) - { + + if (head == null) { head = item; tail = item; size++; return; } - + item.prev = tail; tail.next = item; tail = item; size++; } - + /** * Starts iterating over the lists items */ - public void iter( ) - { + public void iter () { iter = head; } - + /** * Gets the next item in the list * * @return the next item in the list or null if there are no more items */ - public T next( ) - { - if( iter == null ) - return null; - + public T next () { + if (iter == null) return null; + T payload = iter.payload; curr = iter; iter = iter.next; return payload; } - + /** - * Removs the current list item based on the - * iterator position. + * Removs the current list item based on the iterator position. */ - public void remove( ) - { - if( curr == null ) - return; - + public void remove () { + if (curr == null) return; + size--; - pool.free( curr ); - + pool.free(curr); + Item c = curr; Item n = curr.next; Item p = curr.prev; curr = null; - - if( size == 0 ) - { + + if (size == 0) { head = null; tail = null; return; } - - if( c == head ) - { + + if (c == head) { n.prev = null; head = n; return; } - - if( c == tail ) - { + + if (c == tail) { p.next = null; tail = p; return; } - + p.next = n; n.prev = p; } - - public static void main( String[] argv ) - { - PooledLinkedList list = new PooledLinkedList( 10 ); - - list.add( 1 ); - list.add( 2 ); - list.add( 3 ); - list.add( 4 ); + + public static void main (String[] argv) { + PooledLinkedList list = new PooledLinkedList(10); + + list.add(1); + list.add(2); + list.add(3); + list.add(4); list.iter(); list.next(); list.next(); @@ -141,29 +124,27 @@ public class PooledLinkedList list.next(); list.next(); list.remove(); - + list.iter(); Integer v = null; - while( ( v = list.next() ) != null ) - System.out.println( v ); - + while ((v = list.next()) != null) + System.out.println(v); + list.iter(); list.next(); list.next(); list.remove(); - + list.iter(); list.next(); list.remove(); } - public void clear() - { + public void clear () { iter(); - @SuppressWarnings("unused") - T v = null; - while( ( v = next() ) != null ) + @SuppressWarnings("unused") T v = null; + while ((v = next()) != null) remove(); - + } } diff --git a/gdx/src/com/badlogic/gdx/utils/json/JSONArray.java b/gdx/src/com/badlogic/gdx/utils/json/JSONArray.java index dca0e0161..13eeade6c 100644 --- a/gdx/src/com/badlogic/gdx/utils/json/JSONArray.java +++ b/gdx/src/com/badlogic/gdx/utils/json/JSONArray.java @@ -1,28 +1,23 @@ + package com.badlogic.gdx.utils.json; /* -Copyright (c) 2002 JSON.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -The Software shall be used for Good, not Evil. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ + * Copyright (c) 2002 JSON.org + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, + * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software + * is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * The Software shall be used for Good, not Evil. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR + * IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ import java.io.IOException; import java.io.Writer; @@ -33,896 +28,754 @@ import java.util.Iterator; import java.util.Map; /** - * A JSONArray is an ordered sequence of values. Its external text form is a - * string wrapped in square brackets with commas separating the values. The - * internal form is an object having get and opt - * methods for accessing the values by index, and put methods for - * adding or replacing values. The values can be any of these types: - * Boolean, JSONArray, JSONObject, - * Number, String, or the + * A JSONArray is an ordered sequence of values. Its external text form is a string wrapped in square brackets with commas + * separating the values. The internal form is an object having get and opt methods for accessing the + * values by index, and put methods for adding or replacing values. The values can be any of these types: + * Boolean, JSONArray, JSONObject, Number, String, or the * JSONObject.NULL object. *

- * The constructor can convert a JSON text into a Java object. The - * toString method converts to JSON text. + * The constructor can convert a JSON text into a Java object. The toString method converts to JSON text. *

- * A get method returns a value if one can be found, and throws an - * exception if one cannot be found. An opt method returns a - * default value instead of throwing an exception, and so is useful for - * obtaining optional values. + * A get method returns a value if one can be found, and throws an exception if one cannot be found. An + * opt method returns a default value instead of throwing an exception, and so is useful for obtaining optional + * values. *

- * The generic get() and opt() methods return an - * object which you can cast or query for type. There are also typed - * get and opt methods that do type checking and type - * coercion for you. + * The generic get() and opt() methods return an object which you can cast or query for type. There are + * also typed get and opt methods that do type checking and type coercion for you. *

- * The texts produced by the toString methods strictly conform to - * JSON syntax rules. The constructors are more forgiving in the texts they will - * accept: + * The texts produced by the toString methods strictly conform to JSON syntax rules. The constructors are more + * forgiving in the texts they will accept: *

    - *
  • An extra , (comma) may appear just - * before the closing bracket.
  • - *
  • The null value will be inserted when there - * is , (comma) elision.
  • - *
  • Strings may be quoted with ' (single - * quote).
  • - *
  • Strings do not need to be quoted at all if they do not begin with a quote - * or single quote, and if they do not contain leading or trailing spaces, - * and if they do not contain any of these characters: - * { } [ ] / \ : , = ; # and if they do not look like numbers - * and if they are not the reserved words true, - * false, or null.
  • - *
  • Values can be separated by ; (semicolon) as - * well as by , (comma).
  • - *
  • Numbers may have the - * 0x- (hex) prefix.
  • + *
  • An extra , (comma) may appear just before the closing bracket.
  • + *
  • The null value will be inserted when there is , (comma) elision.
  • + *
  • Strings may be quoted with ' (single quote).
  • + *
  • Strings do not need to be quoted at all if they do not begin with a quote or single quote, and if they do not contain + * leading or trailing spaces, and if they do not contain any of these characters: { } [ ] / \ : , = ; # and if they + * do not look like numbers and if they are not the reserved words true, false, or null.
  • + *
  • Values can be separated by ; (semicolon) as well as by , (comma).
  • + *
  • Numbers may have the 0x- (hex) prefix.
  • *
- + * * @author JSON.org * @version 2009-04-14 */ public class JSONArray { + /** + * The arrayList where the JSONArray's properties are kept. + */ + @SuppressWarnings("unchecked") private ArrayList myArrayList; - /** - * The arrayList where the JSONArray's properties are kept. - */ - @SuppressWarnings("unchecked") - private ArrayList myArrayList; - - - /** - * Construct an empty JSONArray. - */ - @SuppressWarnings("unchecked") - public JSONArray() { - this.myArrayList = new ArrayList(); - } - - /** - * Construct a JSONArray from a JSONTokener. - * @param x A JSONTokener - * @throws JSONException If there is a syntax error. - */ - @SuppressWarnings("unchecked") - public JSONArray(JSONTokener x) throws JSONException { - this(); - char c = x.nextClean(); - char q; - if (c == '[') { - q = ']'; - } else if (c == '(') { - q = ')'; - } else { - throw x.syntaxError("A JSONArray text must start with '['"); - } - if (x.nextClean() == ']') { - return; - } - x.back(); - for (;;) { - if (x.nextClean() == ',') { - x.back(); - this.myArrayList.add(null); - } else { - x.back(); - this.myArrayList.add(x.nextValue()); - } - c = x.nextClean(); - switch (c) { - case ';': - case ',': - if (x.nextClean() == ']') { - return; - } - x.back(); - break; - case ']': - case ')': - if (q != c) { - throw x.syntaxError("Expected a '" + new Character(q) + "'"); - } - return; - default: - throw x.syntaxError("Expected a ',' or ']'"); - } - } - } - - - /** - * Construct a JSONArray from a source JSON text. - * @param source A string that begins with - * [ (left bracket) - * and ends with ] (right bracket). - * @throws JSONException If there is a syntax error. - */ - public JSONArray(String source) throws JSONException { - this(new JSONTokener(source)); - } - - - /** - * Construct a JSONArray from a Collection. - * @param collection A Collection. - */ - @SuppressWarnings("unchecked") - public JSONArray(Collection collection) { + /** + * Construct an empty JSONArray. + */ + @SuppressWarnings("unchecked") public JSONArray () { + this.myArrayList = new ArrayList(); + } + + /** + * Construct a JSONArray from a JSONTokener. + * @param x A JSONTokener + * @throws JSONException If there is a syntax error. + */ + @SuppressWarnings("unchecked") public JSONArray (JSONTokener x) throws JSONException { + this(); + char c = x.nextClean(); + char q; + if (c == '[') { + q = ']'; + } else if (c == '(') { + q = ')'; + } else { + throw x.syntaxError("A JSONArray text must start with '['"); + } + if (x.nextClean() == ']') { + return; + } + x.back(); + for (;;) { + if (x.nextClean() == ',') { + x.back(); + this.myArrayList.add(null); + } else { + x.back(); + this.myArrayList.add(x.nextValue()); + } + c = x.nextClean(); + switch (c) { + case ';': + case ',': + if (x.nextClean() == ']') { + return; + } + x.back(); + break; + case ']': + case ')': + if (q != c) { + throw x.syntaxError("Expected a '" + new Character(q) + "'"); + } + return; + default: + throw x.syntaxError("Expected a ',' or ']'"); + } + } + } + + /** + * Construct a JSONArray from a source JSON text. + * @param source A string that begins with [ (left bracket) and ends with ] + *  (right bracket). + * @throws JSONException If there is a syntax error. + */ + public JSONArray (String source) throws JSONException { + this(new JSONTokener(source)); + } + + /** + * Construct a JSONArray from a Collection. + * @param collection A Collection. + */ + @SuppressWarnings("unchecked") public JSONArray (Collection collection) { this.myArrayList = new ArrayList(); if (collection != null) { Iterator iter = collection.iterator(); while (iter.hasNext()) { - Object o = iter.next(); - this.myArrayList.add(JSONObject.wrap(o)); + Object o = iter.next(); + this.myArrayList.add(JSONObject.wrap(o)); + } + } + } + + /** + * Construct a JSONArray from an array + * @throws JSONException If not an array. + */ + public JSONArray (Object array) throws JSONException { + this(); + if (array.getClass().isArray()) { + int length = Array.getLength(array); + for (int i = 0; i < length; i += 1) { + this.put(JSONObject.wrap(Array.get(array, i))); + } + } else { + throw new JSONException("JSONArray initial value should be a string or collection or array."); + } + } + + /** + * Get the object value associated with an index. + * @param index The index must be between 0 and length() - 1. + * @return An object value. + * @throws JSONException If there is no value for the index. + */ + public Object get (int index) throws JSONException { + Object o = opt(index); + if (o == null) { + throw new JSONException("JSONArray[" + index + "] not found."); + } + return o; + } + + /** + * Get the boolean value associated with an index. The string values "true" and "false" are converted to boolean. + * + * @param index The index must be between 0 and length() - 1. + * @return The truth. + * @throws JSONException If there is no value for the index or if the value is not convertable to boolean. + */ + public boolean getBoolean (int index) throws JSONException { + Object o = get(index); + if (o.equals(Boolean.FALSE) || (o instanceof String && ((String)o).equalsIgnoreCase("false"))) { + return false; + } else if (o.equals(Boolean.TRUE) || (o instanceof String && ((String)o).equalsIgnoreCase("true"))) { + return true; + } + throw new JSONException("JSONArray[" + index + "] is not a Boolean."); + } + + /** + * Get the double value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + * @throws JSONException If the key is not found or if the value cannot be converted to a number. + */ + public double getDouble (int index) throws JSONException { + Object o = get(index); + try { + return o instanceof Number ? ((Number)o).doubleValue() : Double.valueOf((String)o).doubleValue(); + } catch (Exception e) { + throw new JSONException("JSONArray[" + index + "] is not a number."); + } + } + + /** + * Get the int value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + * @throws JSONException If the key is not found or if the value cannot be converted to a number. if the value cannot be + * converted to a number. + */ + public int getInt (int index) throws JSONException { + Object o = get(index); + return o instanceof Number ? ((Number)o).intValue() : (int)getDouble(index); + } + + /** + * Get the JSONArray associated with an index. + * @param index The index must be between 0 and length() - 1. + * @return A JSONArray value. + * @throws JSONException If there is no value for the index. or if the value is not a JSONArray + */ + public JSONArray getJSONArray (int index) throws JSONException { + Object o = get(index); + if (o instanceof JSONArray) { + return (JSONArray)o; + } + throw new JSONException("JSONArray[" + index + "] is not a JSONArray."); + } + + /** + * Get the JSONObject associated with an index. + * @param index subscript + * @return A JSONObject value. + * @throws JSONException If there is no value for the index or if the value is not a JSONObject + */ + public JSONObject getJSONObject (int index) throws JSONException { + Object o = get(index); + if (o instanceof JSONObject) { + return (JSONObject)o; + } + throw new JSONException("JSONArray[" + index + "] is not a JSONObject."); + } + + /** + * Get the long value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + * @throws JSONException If the key is not found or if the value cannot be converted to a number. + */ + public long getLong (int index) throws JSONException { + Object o = get(index); + return o instanceof Number ? ((Number)o).longValue() : (long)getDouble(index); + } + + /** + * Get the string associated with an index. + * @param index The index must be between 0 and length() - 1. + * @return A string value. + * @throws JSONException If there is no value for the index. + */ + public String getString (int index) throws JSONException { + return get(index).toString(); + } + + /** + * Determine if the value is null. + * @param index The index must be between 0 and length() - 1. + * @return true if the value at the index is null, or if there is no value. + */ + public boolean isNull (int index) { + return JSONObject.NULL.equals(opt(index)); + } + + /** + * Make a string from the contents of this JSONArray. The separator string is inserted between each element. + * Warning: This method assumes that the data structure is acyclical. + * @param separator A string that will be inserted between the elements. + * @return a string. + * @throws JSONException If the array contains an invalid number. + */ + public String join (String separator) throws JSONException { + int len = length(); + StringBuffer sb = new StringBuffer(); + + for (int i = 0; i < len; i += 1) { + if (i > 0) { + sb.append(separator); + } + sb.append(JSONObject.valueToString(this.myArrayList.get(i))); + } + return sb.toString(); + } + + /** + * Get the number of elements in the JSONArray, included nulls. + * + * @return The length (or size). + */ + public int length () { + return this.myArrayList.size(); + } + + /** + * Get the optional object value associated with an index. + * @param index The index must be between 0 and length() - 1. + * @return An object value, or null if there is no object at that index. + */ + public Object opt (int index) { + return (index < 0 || index >= length()) ? null : this.myArrayList.get(index); + } + + /** + * Get the optional boolean value associated with an index. It returns false if there is no value at that index, or if the + * value is not Boolean.TRUE or the String "true". + * + * @param index The index must be between 0 and length() - 1. + * @return The truth. + */ + public boolean optBoolean (int index) { + return optBoolean(index, false); + } + + /** + * Get the optional boolean value associated with an index. It returns the defaultValue if there is no value at that index or + * if it is not a Boolean or the String "true" or "false" (case insensitive). + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue A boolean default. + * @return The truth. + */ + public boolean optBoolean (int index, boolean defaultValue) { + try { + return getBoolean(index); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Get the optional double value associated with an index. NaN is returned if there is no value for the index, or if the value + * is not a number and cannot be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + */ + public double optDouble (int index) { + return optDouble(index, Double.NaN); + } + + /** + * Get the optional double value associated with an index. The defaultValue is returned if there is no value for the index, or + * if the value is not a number and cannot be converted to a number. + * + * @param index subscript + * @param defaultValue The default value. + * @return The value. + */ + public double optDouble (int index, double defaultValue) { + try { + return getDouble(index); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Get the optional int value associated with an index. Zero is returned if there is no value for the index, or if the value is + * not a number and cannot be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + */ + public int optInt (int index) { + return optInt(index, 0); + } + + /** + * Get the optional int value associated with an index. The defaultValue is returned if there is no value for the index, or if + * the value is not a number and cannot be converted to a number. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. + * @return The value. + */ + public int optInt (int index, int defaultValue) { + try { + return getInt(index); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Get the optional JSONArray associated with an index. + * @param index subscript + * @return A JSONArray value, or null if the index has no value, or if the value is not a JSONArray. + */ + public JSONArray optJSONArray (int index) { + Object o = opt(index); + return o instanceof JSONArray ? (JSONArray)o : null; + } + + /** + * Get the optional JSONObject associated with an index. Null is returned if the key is not found, or null if the index has no + * value, or if the value is not a JSONObject. + * + * @param index The index must be between 0 and length() - 1. + * @return A JSONObject value. + */ + public JSONObject optJSONObject (int index) { + Object o = opt(index); + return o instanceof JSONObject ? (JSONObject)o : null; + } + + /** + * Get the optional long value associated with an index. Zero is returned if there is no value for the index, or if the value + * is not a number and cannot be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + */ + public long optLong (int index) { + return optLong(index, 0); + } + + /** + * Get the optional long value associated with an index. The defaultValue is returned if there is no value for the index, or if + * the value is not a number and cannot be converted to a number. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. + * @return The value. + */ + public long optLong (int index, long defaultValue) { + try { + return getLong(index); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Get the optional string value associated with an index. It returns an empty string if there is no value at that index. If + * the value is not a string and is not null, then it is coverted to a string. + * + * @param index The index must be between 0 and length() - 1. + * @return A String value. + */ + public String optString (int index) { + return optString(index, ""); + } + + /** + * Get the optional string associated with an index. The defaultValue is returned if the key is not found. + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. + * @return A String value. + */ + public String optString (int index, String defaultValue) { + Object o = opt(index); + return o != null ? o.toString() : defaultValue; + } + + /** + * Append a boolean value. This increases the array's length by one. + * + * @param value A boolean value. + * @return this. + */ + public JSONArray put (boolean value) { + put(value ? Boolean.TRUE : Boolean.FALSE); + return this; + } + + /** + * Put a value in the JSONArray, where the value will be a JSONArray which is produced from a Collection. + * @param value A Collection value. + * @return this. + */ + @SuppressWarnings("unchecked") public JSONArray put (Collection value) { + put(new JSONArray(value)); + return this; + } + + /** + * Append a double value. This increases the array's length by one. + * + * @param value A double value. + * @throws JSONException if the value is not finite. + * @return this. + */ + public JSONArray put (double value) throws JSONException { + Double d = new Double(value); + JSONObject.testValidity(d); + put(d); + return this; + } + + /** + * Append an int value. This increases the array's length by one. + * + * @param value An int value. + * @return this. + */ + public JSONArray put (int value) { + put(new Integer(value)); + return this; + } + + /** + * Append an long value. This increases the array's length by one. + * + * @param value A long value. + * @return this. + */ + public JSONArray put (long value) { + put(new Long(value)); + return this; + } + + /** + * Put a value in the JSONArray, where the value will be a JSONObject which is produced from a Map. + * @param value A Map value. + * @return this. + */ + @SuppressWarnings("unchecked") public JSONArray put (Map value) { + put(new JSONObject(value)); + return this; + } + + /** + * Append an object value. This increases the array's length by one. + * @param value An object value. The value should be a Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the + * JSONObject.NULL object. + * @return this. + */ + @SuppressWarnings("unchecked") public JSONArray put (Object value) { + this.myArrayList.add(value); + return this; + } + + /** + * Put or replace a boolean value in the JSONArray. If the index is greater than the length of the JSONArray, then null + * elements will be added as necessary to pad it out. + * @param index The subscript. + * @param value A boolean value. + * @return this. + * @throws JSONException If the index is negative. + */ + public JSONArray put (int index, boolean value) throws JSONException { + put(index, value ? Boolean.TRUE : Boolean.FALSE); + return this; + } + + /** + * Put a value in the JSONArray, where the value will be a JSONArray which is produced from a Collection. + * @param index The subscript. + * @param value A Collection value. + * @return this. + * @throws JSONException If the index is negative or if the value is not finite. + */ + @SuppressWarnings("unchecked") public JSONArray put (int index, Collection value) throws JSONException { + put(index, new JSONArray(value)); + return this; + } + + /** + * Put or replace a double value. If the index is greater than the length of the JSONArray, then null elements will be added as + * necessary to pad it out. + * @param index The subscript. + * @param value A double value. + * @return this. + * @throws JSONException If the index is negative or if the value is not finite. + */ + public JSONArray put (int index, double value) throws JSONException { + put(index, new Double(value)); + return this; + } + + /** + * Put or replace an int value. If the index is greater than the length of the JSONArray, then null elements will be added as + * necessary to pad it out. + * @param index The subscript. + * @param value An int value. + * @return this. + * @throws JSONException If the index is negative. + */ + public JSONArray put (int index, int value) throws JSONException { + put(index, new Integer(value)); + return this; + } + + /** + * Put or replace a long value. If the index is greater than the length of the JSONArray, then null elements will be added as + * necessary to pad it out. + * @param index The subscript. + * @param value A long value. + * @return this. + * @throws JSONException If the index is negative. + */ + public JSONArray put (int index, long value) throws JSONException { + put(index, new Long(value)); + return this; + } + + /** + * Put a value in the JSONArray, where the value will be a JSONObject which is produced from a Map. + * @param index The subscript. + * @param value The Map value. + * @return this. + * @throws JSONException If the index is negative or if the the value is an invalid number. + */ + @SuppressWarnings("unchecked") public JSONArray put (int index, Map value) throws JSONException { + put(index, new JSONObject(value)); + return this; + } + + /** + * Put or replace an object value in the JSONArray. If the index is greater than the length of the JSONArray, then null + * elements will be added as necessary to pad it out. + * @param index The subscript. + * @param value The value to put into the array. The value should be a Boolean, Double, Integer, JSONArray, JSONObject, Long, + * or String, or the JSONObject.NULL object. + * @return this. + * @throws JSONException If the index is negative or if the the value is an invalid number. + */ + @SuppressWarnings("unchecked") public JSONArray put (int index, Object value) throws JSONException { + JSONObject.testValidity(value); + if (index < 0) { + throw new JSONException("JSONArray[" + index + "] not found."); + } + if (index < length()) { + this.myArrayList.set(index, value); + } else { + while (index != length()) { + put(JSONObject.NULL); + } + put(value); + } + return this; + } + + /** + * Remove an index and close the hole. + * @param index The index of the element to be removed. + * @return The value that was associated with the index, or null if there was no value. + */ + public Object remove (int index) { + Object o = opt(index); + this.myArrayList.remove(index); + return o; + } + + /** + * Produce a JSONObject by combining a JSONArray of names with the values of this JSONArray. + * @param names A JSONArray containing a list of key strings. These will be paired with the values. + * @return A JSONObject, or null if there are no names or if this JSONArray has no values. + * @throws JSONException If any of the names are null. + */ + public JSONObject toJSONObject (JSONArray names) throws JSONException { + if (names == null || names.length() == 0 || length() == 0) { + return null; + } + JSONObject jo = new JSONObject(); + for (int i = 0; i < names.length(); i += 1) { + jo.put(names.getString(i), this.opt(i)); + } + return jo; + } + + /** + * Make a JSON text of this JSONArray. For compactness, no unnecessary whitespace is added. If it is not possible to produce a + * syntactically correct JSON text then null will be returned instead. This could occur if the array contains an invalid + * number. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @return a printable, displayable, transmittable representation of the array. + */ + public String toString () { + try { + return '[' + join(",") + ']'; + } catch (Exception e) { + return null; + } + } + + /** + * Make a prettyprinted JSON text of this JSONArray. Warning: This method assumes that the data structure is acyclical. + * @param indentFactor The number of spaces to add to each level of indentation. + * @return a printable, displayable, transmittable representation of the object, beginning with [ + *  (left bracket) and ending with ] (right bracket). + * @throws JSONException + */ + public String toString (int indentFactor) throws JSONException { + return toString(indentFactor, 0); + } + + /** + * Make a prettyprinted JSON text of this JSONArray. Warning: This method assumes that the data structure is acyclical. + * @param indentFactor The number of spaces to add to each level of indentation. + * @param indent The indention of the top level. + * @return a printable, displayable, transmittable representation of the array. + * @throws JSONException + */ + String toString (int indentFactor, int indent) throws JSONException { + int len = length(); + if (len == 0) { + return "[]"; + } + int i; + StringBuffer sb = new StringBuffer("["); + if (len == 1) { + sb.append(JSONObject.valueToString(this.myArrayList.get(0), indentFactor, indent)); + } else { + int newindent = indent + indentFactor; + sb.append('\n'); + for (i = 0; i < len; i += 1) { + if (i > 0) { + sb.append(",\n"); + } + for (int j = 0; j < newindent; j += 1) { + sb.append(' '); + } + sb.append(JSONObject.valueToString(this.myArrayList.get(i), indentFactor, newindent)); + } + sb.append('\n'); + for (i = 0; i < indent; i += 1) { + sb.append(' '); + } + } + sb.append(']'); + return sb.toString(); + } + + /** + * Write the contents of the JSONArray as JSON text to a writer. For compactness, no whitespace is added. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @return The writer. + * @throws JSONException + */ + public Writer write (Writer writer) throws JSONException { + try { + boolean b = false; + int len = length(); + + writer.write('['); + + for (int i = 0; i < len; i += 1) { + if (b) { + writer.write(','); + } + Object v = this.myArrayList.get(i); + if (v instanceof JSONObject) { + ((JSONObject)v).write(writer); + } else if (v instanceof JSONArray) { + ((JSONArray)v).write(writer); + } else { + writer.write(JSONObject.valueToString(v)); + } + b = true; } + writer.write(']'); + return writer; + } catch (IOException e) { + throw new JSONException(e); } - } - - - /** - * Construct a JSONArray from an array - * @throws JSONException If not an array. - */ - public JSONArray(Object array) throws JSONException { - this(); - if (array.getClass().isArray()) { - int length = Array.getLength(array); - for (int i = 0; i < length; i += 1) { - this.put(JSONObject.wrap(Array.get(array, i))); - } - } else { - throw new JSONException( -"JSONArray initial value should be a string or collection or array."); - } - } - - - /** - * Get the object value associated with an index. - * @param index - * The index must be between 0 and length() - 1. - * @return An object value. - * @throws JSONException If there is no value for the index. - */ - public Object get(int index) throws JSONException { - Object o = opt(index); - if (o == null) { - throw new JSONException("JSONArray[" + index + "] not found."); - } - return o; - } - - - /** - * Get the boolean value associated with an index. - * The string values "true" and "false" are converted to boolean. - * - * @param index The index must be between 0 and length() - 1. - * @return The truth. - * @throws JSONException If there is no value for the index or if the - * value is not convertable to boolean. - */ - public boolean getBoolean(int index) throws JSONException { - Object o = get(index); - if (o.equals(Boolean.FALSE) || - (o instanceof String && - ((String)o).equalsIgnoreCase("false"))) { - return false; - } else if (o.equals(Boolean.TRUE) || - (o instanceof String && - ((String)o).equalsIgnoreCase("true"))) { - return true; - } - throw new JSONException("JSONArray[" + index + "] is not a Boolean."); - } - - - /** - * Get the double value associated with an index. - * - * @param index The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException If the key is not found or if the value cannot - * be converted to a number. - */ - public double getDouble(int index) throws JSONException { - Object o = get(index); - try { - return o instanceof Number ? - ((Number)o).doubleValue() : - Double.valueOf((String)o).doubleValue(); - } catch (Exception e) { - throw new JSONException("JSONArray[" + index + - "] is not a number."); - } - } - - - /** - * Get the int value associated with an index. - * - * @param index The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException If the key is not found or if the value cannot - * be converted to a number. - * if the value cannot be converted to a number. - */ - public int getInt(int index) throws JSONException { - Object o = get(index); - return o instanceof Number ? - ((Number)o).intValue() : (int)getDouble(index); - } - - - /** - * Get the JSONArray associated with an index. - * @param index The index must be between 0 and length() - 1. - * @return A JSONArray value. - * @throws JSONException If there is no value for the index. or if the - * value is not a JSONArray - */ - public JSONArray getJSONArray(int index) throws JSONException { - Object o = get(index); - if (o instanceof JSONArray) { - return (JSONArray)o; - } - throw new JSONException("JSONArray[" + index + - "] is not a JSONArray."); - } - - - /** - * Get the JSONObject associated with an index. - * @param index subscript - * @return A JSONObject value. - * @throws JSONException If there is no value for the index or if the - * value is not a JSONObject - */ - public JSONObject getJSONObject(int index) throws JSONException { - Object o = get(index); - if (o instanceof JSONObject) { - return (JSONObject)o; - } - throw new JSONException("JSONArray[" + index + - "] is not a JSONObject."); - } - - - /** - * Get the long value associated with an index. - * - * @param index The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException If the key is not found or if the value cannot - * be converted to a number. - */ - public long getLong(int index) throws JSONException { - Object o = get(index); - return o instanceof Number ? - ((Number)o).longValue() : (long)getDouble(index); - } - - - /** - * Get the string associated with an index. - * @param index The index must be between 0 and length() - 1. - * @return A string value. - * @throws JSONException If there is no value for the index. - */ - public String getString(int index) throws JSONException { - return get(index).toString(); - } - - - /** - * Determine if the value is null. - * @param index The index must be between 0 and length() - 1. - * @return true if the value at the index is null, or if there is no value. - */ - public boolean isNull(int index) { - return JSONObject.NULL.equals(opt(index)); - } - - - /** - * Make a string from the contents of this JSONArray. The - * separator string is inserted between each element. - * Warning: This method assumes that the data structure is acyclical. - * @param separator A string that will be inserted between the elements. - * @return a string. - * @throws JSONException If the array contains an invalid number. - */ - public String join(String separator) throws JSONException { - int len = length(); - StringBuffer sb = new StringBuffer(); - - for (int i = 0; i < len; i += 1) { - if (i > 0) { - sb.append(separator); - } - sb.append(JSONObject.valueToString(this.myArrayList.get(i))); - } - return sb.toString(); - } - - - /** - * Get the number of elements in the JSONArray, included nulls. - * - * @return The length (or size). - */ - public int length() { - return this.myArrayList.size(); - } - - - /** - * Get the optional object value associated with an index. - * @param index The index must be between 0 and length() - 1. - * @return An object value, or null if there is no - * object at that index. - */ - public Object opt(int index) { - return (index < 0 || index >= length()) ? - null : this.myArrayList.get(index); - } - - - /** - * Get the optional boolean value associated with an index. - * It returns false if there is no value at that index, - * or if the value is not Boolean.TRUE or the String "true". - * - * @param index The index must be between 0 and length() - 1. - * @return The truth. - */ - public boolean optBoolean(int index) { - return optBoolean(index, false); - } - - - /** - * Get the optional boolean value associated with an index. - * It returns the defaultValue if there is no value at that index or if - * it is not a Boolean or the String "true" or "false" (case insensitive). - * - * @param index The index must be between 0 and length() - 1. - * @param defaultValue A boolean default. - * @return The truth. - */ - public boolean optBoolean(int index, boolean defaultValue) { - try { - return getBoolean(index); - } catch (Exception e) { - return defaultValue; - } - } - - - /** - * Get the optional double value associated with an index. - * NaN is returned if there is no value for the index, - * or if the value is not a number and cannot be converted to a number. - * - * @param index The index must be between 0 and length() - 1. - * @return The value. - */ - public double optDouble(int index) { - return optDouble(index, Double.NaN); - } - - - /** - * Get the optional double value associated with an index. - * The defaultValue is returned if there is no value for the index, - * or if the value is not a number and cannot be converted to a number. - * - * @param index subscript - * @param defaultValue The default value. - * @return The value. - */ - public double optDouble(int index, double defaultValue) { - try { - return getDouble(index); - } catch (Exception e) { - return defaultValue; - } - } - - - /** - * Get the optional int value associated with an index. - * Zero is returned if there is no value for the index, - * or if the value is not a number and cannot be converted to a number. - * - * @param index The index must be between 0 and length() - 1. - * @return The value. - */ - public int optInt(int index) { - return optInt(index, 0); - } - - - /** - * Get the optional int value associated with an index. - * The defaultValue is returned if there is no value for the index, - * or if the value is not a number and cannot be converted to a number. - * @param index The index must be between 0 and length() - 1. - * @param defaultValue The default value. - * @return The value. - */ - public int optInt(int index, int defaultValue) { - try { - return getInt(index); - } catch (Exception e) { - return defaultValue; - } - } - - - /** - * Get the optional JSONArray associated with an index. - * @param index subscript - * @return A JSONArray value, or null if the index has no value, - * or if the value is not a JSONArray. - */ - public JSONArray optJSONArray(int index) { - Object o = opt(index); - return o instanceof JSONArray ? (JSONArray)o : null; - } - - - /** - * Get the optional JSONObject associated with an index. - * Null is returned if the key is not found, or null if the index has - * no value, or if the value is not a JSONObject. - * - * @param index The index must be between 0 and length() - 1. - * @return A JSONObject value. - */ - public JSONObject optJSONObject(int index) { - Object o = opt(index); - return o instanceof JSONObject ? (JSONObject)o : null; - } - - - /** - * Get the optional long value associated with an index. - * Zero is returned if there is no value for the index, - * or if the value is not a number and cannot be converted to a number. - * - * @param index The index must be between 0 and length() - 1. - * @return The value. - */ - public long optLong(int index) { - return optLong(index, 0); - } - - - /** - * Get the optional long value associated with an index. - * The defaultValue is returned if there is no value for the index, - * or if the value is not a number and cannot be converted to a number. - * @param index The index must be between 0 and length() - 1. - * @param defaultValue The default value. - * @return The value. - */ - public long optLong(int index, long defaultValue) { - try { - return getLong(index); - } catch (Exception e) { - return defaultValue; - } - } - - - /** - * Get the optional string value associated with an index. It returns an - * empty string if there is no value at that index. If the value - * is not a string and is not null, then it is coverted to a string. - * - * @param index The index must be between 0 and length() - 1. - * @return A String value. - */ - public String optString(int index) { - return optString(index, ""); - } - - - /** - * Get the optional string associated with an index. - * The defaultValue is returned if the key is not found. - * - * @param index The index must be between 0 and length() - 1. - * @param defaultValue The default value. - * @return A String value. - */ - public String optString(int index, String defaultValue) { - Object o = opt(index); - return o != null ? o.toString() : defaultValue; - } - - - /** - * Append a boolean value. This increases the array's length by one. - * - * @param value A boolean value. - * @return this. - */ - public JSONArray put(boolean value) { - put(value ? Boolean.TRUE : Boolean.FALSE); - return this; - } - - - /** - * Put a value in the JSONArray, where the value will be a - * JSONArray which is produced from a Collection. - * @param value A Collection value. - * @return this. - */ - @SuppressWarnings("unchecked") - public JSONArray put(Collection value) { - put(new JSONArray(value)); - return this; - } - - - /** - * Append a double value. This increases the array's length by one. - * - * @param value A double value. - * @throws JSONException if the value is not finite. - * @return this. - */ - public JSONArray put(double value) throws JSONException { - Double d = new Double(value); - JSONObject.testValidity(d); - put(d); - return this; - } - - - /** - * Append an int value. This increases the array's length by one. - * - * @param value An int value. - * @return this. - */ - public JSONArray put(int value) { - put(new Integer(value)); - return this; - } - - - /** - * Append an long value. This increases the array's length by one. - * - * @param value A long value. - * @return this. - */ - public JSONArray put(long value) { - put(new Long(value)); - return this; - } - - - /** - * Put a value in the JSONArray, where the value will be a - * JSONObject which is produced from a Map. - * @param value A Map value. - * @return this. - */ - @SuppressWarnings("unchecked") - public JSONArray put(Map value) { - put(new JSONObject(value)); - return this; - } - - - /** - * Append an object value. This increases the array's length by one. - * @param value An object value. The value should be a - * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the - * JSONObject.NULL object. - * @return this. - */ - @SuppressWarnings("unchecked") - public JSONArray put(Object value) { - this.myArrayList.add(value); - return this; - } - - - /** - * Put or replace a boolean value in the JSONArray. If the index is greater - * than the length of the JSONArray, then null elements will be added as - * necessary to pad it out. - * @param index The subscript. - * @param value A boolean value. - * @return this. - * @throws JSONException If the index is negative. - */ - public JSONArray put(int index, boolean value) throws JSONException { - put(index, value ? Boolean.TRUE : Boolean.FALSE); - return this; - } - - - /** - * Put a value in the JSONArray, where the value will be a - * JSONArray which is produced from a Collection. - * @param index The subscript. - * @param value A Collection value. - * @return this. - * @throws JSONException If the index is negative or if the value is - * not finite. - */ - @SuppressWarnings("unchecked") - public JSONArray put(int index, Collection value) throws JSONException { - put(index, new JSONArray(value)); - return this; - } - - - /** - * Put or replace a double value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad - * it out. - * @param index The subscript. - * @param value A double value. - * @return this. - * @throws JSONException If the index is negative or if the value is - * not finite. - */ - public JSONArray put(int index, double value) throws JSONException { - put(index, new Double(value)); - return this; - } - - - /** - * Put or replace an int value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad - * it out. - * @param index The subscript. - * @param value An int value. - * @return this. - * @throws JSONException If the index is negative. - */ - public JSONArray put(int index, int value) throws JSONException { - put(index, new Integer(value)); - return this; - } - - - /** - * Put or replace a long value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad - * it out. - * @param index The subscript. - * @param value A long value. - * @return this. - * @throws JSONException If the index is negative. - */ - public JSONArray put(int index, long value) throws JSONException { - put(index, new Long(value)); - return this; - } - - - /** - * Put a value in the JSONArray, where the value will be a - * JSONObject which is produced from a Map. - * @param index The subscript. - * @param value The Map value. - * @return this. - * @throws JSONException If the index is negative or if the the value is - * an invalid number. - */ - @SuppressWarnings("unchecked") - public JSONArray put(int index, Map value) throws JSONException { - put(index, new JSONObject(value)); - return this; - } - - - /** - * Put or replace an object value in the JSONArray. If the index is greater - * than the length of the JSONArray, then null elements will be added as - * necessary to pad it out. - * @param index The subscript. - * @param value The value to put into the array. The value should be a - * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the - * JSONObject.NULL object. - * @return this. - * @throws JSONException If the index is negative or if the the value is - * an invalid number. - */ - @SuppressWarnings("unchecked") - public JSONArray put(int index, Object value) throws JSONException { - JSONObject.testValidity(value); - if (index < 0) { - throw new JSONException("JSONArray[" + index + "] not found."); - } - if (index < length()) { - this.myArrayList.set(index, value); - } else { - while (index != length()) { - put(JSONObject.NULL); - } - put(value); - } - return this; - } - - - /** - * Remove an index and close the hole. - * @param index The index of the element to be removed. - * @return The value that was associated with the index, - * or null if there was no value. - */ - public Object remove(int index) { - Object o = opt(index); - this.myArrayList.remove(index); - return o; - } - - - /** - * Produce a JSONObject by combining a JSONArray of names with the values - * of this JSONArray. - * @param names A JSONArray containing a list of key strings. These will be - * paired with the values. - * @return A JSONObject, or null if there are no names or if this JSONArray - * has no values. - * @throws JSONException If any of the names are null. - */ - public JSONObject toJSONObject(JSONArray names) throws JSONException { - if (names == null || names.length() == 0 || length() == 0) { - return null; - } - JSONObject jo = new JSONObject(); - for (int i = 0; i < names.length(); i += 1) { - jo.put(names.getString(i), this.opt(i)); - } - return jo; - } - - - /** - * Make a JSON text of this JSONArray. For compactness, no - * unnecessary whitespace is added. If it is not possible to produce a - * syntactically correct JSON text then null will be returned instead. This - * could occur if the array contains an invalid number. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return a printable, displayable, transmittable - * representation of the array. - */ - public String toString() { - try { - return '[' + join(",") + ']'; - } catch (Exception e) { - return null; - } - } - - - /** - * Make a prettyprinted JSON text of this JSONArray. - * Warning: This method assumes that the data structure is acyclical. - * @param indentFactor The number of spaces to add to each level of - * indentation. - * @return a printable, displayable, transmittable - * representation of the object, beginning - * with [ (left bracket) and ending - * with ] (right bracket). - * @throws JSONException - */ - public String toString(int indentFactor) throws JSONException { - return toString(indentFactor, 0); - } - - - /** - * Make a prettyprinted JSON text of this JSONArray. - * Warning: This method assumes that the data structure is acyclical. - * @param indentFactor The number of spaces to add to each level of - * indentation. - * @param indent The indention of the top level. - * @return a printable, displayable, transmittable - * representation of the array. - * @throws JSONException - */ - String toString(int indentFactor, int indent) throws JSONException { - int len = length(); - if (len == 0) { - return "[]"; - } - int i; - StringBuffer sb = new StringBuffer("["); - if (len == 1) { - sb.append(JSONObject.valueToString(this.myArrayList.get(0), - indentFactor, indent)); - } else { - int newindent = indent + indentFactor; - sb.append('\n'); - for (i = 0; i < len; i += 1) { - if (i > 0) { - sb.append(",\n"); - } - for (int j = 0; j < newindent; j += 1) { - sb.append(' '); - } - sb.append(JSONObject.valueToString(this.myArrayList.get(i), - indentFactor, newindent)); - } - sb.append('\n'); - for (i = 0; i < indent; i += 1) { - sb.append(' '); - } - } - sb.append(']'); - return sb.toString(); - } - - - /** - * Write the contents of the JSONArray as JSON text to a writer. - * For compactness, no whitespace is added. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return The writer. - * @throws JSONException - */ - public Writer write(Writer writer) throws JSONException { - try { - boolean b = false; - int len = length(); - - writer.write('['); - - for (int i = 0; i < len; i += 1) { - if (b) { - writer.write(','); - } - Object v = this.myArrayList.get(i); - if (v instanceof JSONObject) { - ((JSONObject)v).write(writer); - } else if (v instanceof JSONArray) { - ((JSONArray)v).write(writer); - } else { - writer.write(JSONObject.valueToString(v)); - } - b = true; - } - writer.write(']'); - return writer; - } catch (IOException e) { - throw new JSONException(e); - } - } -} \ No newline at end of file + } +} diff --git a/gdx/src/com/badlogic/gdx/utils/json/JSONException.java b/gdx/src/com/badlogic/gdx/utils/json/JSONException.java index f5f0229a2..0570ade20 100644 --- a/gdx/src/com/badlogic/gdx/utils/json/JSONException.java +++ b/gdx/src/com/badlogic/gdx/utils/json/JSONException.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.utils.json; /** @@ -6,26 +7,26 @@ package com.badlogic.gdx.utils.json; * @version 2008-09-18 */ public class JSONException extends Exception { - /** + /** * */ private static final long serialVersionUID = 0; private Throwable cause; - /** - * Constructs a JSONException with an explanatory message. - * @param message Detail about the reason for the exception. - */ - public JSONException(String message) { - super(message); - } + /** + * Constructs a JSONException with an explanatory message. + * @param message Detail about the reason for the exception. + */ + public JSONException (String message) { + super(message); + } - public JSONException(Throwable t) { - super(t.getMessage()); - this.cause = t; - } + public JSONException (Throwable t) { + super(t.getMessage()); + this.cause = t; + } - public Throwable getCause() { - return this.cause; - } + public Throwable getCause () { + return this.cause; + } } diff --git a/gdx/src/com/badlogic/gdx/utils/json/JSONObject.java b/gdx/src/com/badlogic/gdx/utils/json/JSONObject.java index 93b4b38f3..5ed6e85af 100644 --- a/gdx/src/com/badlogic/gdx/utils/json/JSONObject.java +++ b/gdx/src/com/badlogic/gdx/utils/json/JSONObject.java @@ -1,34 +1,29 @@ + package com.badlogic.gdx.utils.json; /* -Copyright (c) 2002 JSON.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -The Software shall be used for Good, not Evil. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ + * Copyright (c) 2002 JSON.org + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, + * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software + * is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * The Software shall be used for Good, not Evil. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR + * IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ import java.io.IOException; import java.io.Writer; import java.lang.reflect.Field; -import java.lang.reflect.Modifier; import java.lang.reflect.Method; +import java.lang.reflect.Modifier; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; @@ -36,1550 +31,1341 @@ import java.util.Map; import java.util.TreeSet; /** - * A JSONObject is an unordered collection of name/value pairs. Its - * external form is a string wrapped in curly braces with colons between the - * names and values, and commas between the values and names. The internal form - * is an object having get and opt methods for - * accessing the values by name, and put methods for adding or - * replacing values by name. The values can be any of these types: - * Boolean, JSONArray, JSONObject, - * Number, String, or the JSONObject.NULL - * object. A JSONObject constructor can be used to convert an external form - * JSON text into an internal form whose values can be retrieved with the - * get and opt methods, or to convert values into a - * JSON text using the put and toString methods. - * A get method returns a value if one can be found, and throws an - * exception if one cannot be found. An opt method returns a - * default value instead of throwing an exception, and so is useful for - * obtaining optional values. + * A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons + * between the names and values, and commas between the values and names. The internal form is an object having get + * and opt methods for accessing the values by name, and put methods for adding or replacing values by + * name. The values can be any of these types: Boolean, JSONArray, JSONObject, + * Number, String, or the JSONObject.NULL object. A JSONObject constructor can be used to + * convert an external form JSON text into an internal form whose values can be retrieved with the get and + * opt methods, or to convert values into a JSON text using the put and toString methods. A + * get method returns a value if one can be found, and throws an exception if one cannot be found. An + * opt method returns a default value instead of throwing an exception, and so is useful for obtaining optional + * values. *

- * The generic get() and opt() methods return an - * object, which you can cast or query for type. There are also typed - * get and opt methods that do type checking and type - * coercion for you. + * The generic get() and opt() methods return an object, which you can cast or query for type. There are + * also typed get and opt methods that do type checking and type coercion for you. *

- * The put methods adds values to an object. For example,

- *     myString = new JSONObject().put("JSON", "Hello, World!").toString();
+ * The put methods adds values to an object. For example, + * + *
+ * myString = new JSONObject().put("JSON", "Hello, World!").toString();
+ * 
+ * * produces the string {"JSON": "Hello, World"}. *

- * The texts produced by the toString methods strictly conform to - * the JSON syntax rules. - * The constructors are more forgiving in the texts they will accept: + * The texts produced by the toString methods strictly conform to the JSON syntax rules. The constructors are more + * forgiving in the texts they will accept: *

    - *
  • An extra , (comma) may appear just - * before the closing brace.
  • - *
  • Strings may be quoted with ' (single - * quote).
  • - *
  • Strings do not need to be quoted at all if they do not begin with a quote - * or single quote, and if they do not contain leading or trailing spaces, - * and if they do not contain any of these characters: - * { } [ ] / \ : , = ; # and if they do not look like numbers - * and if they are not the reserved words true, - * false, or null.
  • - *
  • Keys can be followed by = or => as well as - * by :.
  • - *
  • Values can be followed by ; (semicolon) as - * well as by , (comma).
  • + *
  • An extra , (comma) may appear just before the closing brace.
  • + *
  • Strings may be quoted with ' (single quote).
  • + *
  • Strings do not need to be quoted at all if they do not begin with a quote or single quote, and if they do not contain + * leading or trailing spaces, and if they do not contain any of these characters: { } [ ] / \ : , = ; # and if they + * do not look like numbers and if they are not the reserved words true, false, or null.
  • + *
  • Keys can be followed by = or => as well as by :.
  • + *
  • Values can be followed by ; (semicolon) as well as by , (comma).
  • *
  • Numbers may have the 0x- (hex) prefix.
  • *
* @author JSON.org * @version 2010-05-17 */ -@SuppressWarnings("unchecked") -public class JSONObject { - - /** - * JSONObject.NULL is equivalent to the value that JavaScript calls null, - * whilst Java's null is equivalent to the value that JavaScript calls - * undefined. - */ - private static final class Null { - - /** - * There is only intended to be a single instance of the NULL object, - * so the clone method returns itself. - * @return NULL. - */ - protected final Object clone() { - return this; - } - - - /** - * A Null object is equal to the null value and to itself. - * @param object An object to test for nullness. - * @return true if the object parameter is the JSONObject.NULL object - * or null. - */ - public boolean equals(Object object) { - return object == null || object == this; - } - - - /** - * Get the "null" string value. - * @return The string "null". - */ - public String toString() { - return "null"; - } - } - - - /** - * The map where the JSONObject's properties are kept. - */ +@SuppressWarnings("unchecked") public class JSONObject { + + /** + * JSONObject.NULL is equivalent to the value that JavaScript calls null, whilst Java's null is equivalent to the value that + * JavaScript calls undefined. + */ + private static final class Null { + + /** + * There is only intended to be a single instance of the NULL object, so the clone method returns itself. + * @return NULL. + */ + protected final Object clone () { + return this; + } + + /** + * A Null object is equal to the null value and to itself. + * @param object An object to test for nullness. + * @return true if the object parameter is the JSONObject.NULL object or null. + */ + public boolean equals (Object object) { + return object == null || object == this; + } + + /** + * Get the "null" string value. + * @return The string "null". + */ + public String toString () { + return "null"; + } + } + + /** + * The map where the JSONObject's properties are kept. + */ private Map map; - - /** - * It is sometimes more convenient and less ambiguous to have a - * NULL object than to use Java's null value. - * JSONObject.NULL.equals(null) returns true. - * JSONObject.NULL.toString() returns "null". - */ - public static final Object NULL = new Null(); - - - /** - * Construct an empty JSONObject. - */ - public JSONObject() { - this.map = new HashMap(); - } - - - /** - * Construct a JSONObject from a subset of another JSONObject. - * An array of strings is used to identify the keys that should be copied. - * Missing keys are ignored. - * @param jo A JSONObject. - * @param names An array of strings. - * @throws JSONException - * @exception JSONException If a value is a non-finite number or if a name is duplicated. - */ - public JSONObject(JSONObject jo, String[] names) { - this(); - for (int i = 0; i < names.length; i += 1) { - try { - putOnce(names[i], jo.opt(names[i])); - } catch (Exception ignore) { - } - } - } - - - /** - * Construct a JSONObject from a JSONTokener. - * @param x A JSONTokener object containing the source string. - * @throws JSONException If there is a syntax error in the source string - * or a duplicated key. - */ - public JSONObject(JSONTokener x) throws JSONException { - this(); - char c; - String key; - - if (x.nextClean() != '{') { - throw x.syntaxError("A JSONObject text must begin with '{'"); - } - for (;;) { - c = x.nextClean(); - switch (c) { - case 0: - throw x.syntaxError("A JSONObject text must end with '}'"); - case '}': - return; - default: - x.back(); - key = x.nextValue().toString(); - } - - /* - * The key is followed by ':'. We will also tolerate '=' or '=>'. - */ - - c = x.nextClean(); - if (c == '=') { - if (x.next() != '>') { - x.back(); - } - } else if (c != ':') { - throw x.syntaxError("Expected a ':' after a key"); - } - putOnce(key, x.nextValue()); - - /* - * Pairs are separated by ','. We will also tolerate ';'. - */ - - switch (x.nextClean()) { - case ';': - case ',': - if (x.nextClean() == '}') { - return; - } - x.back(); - break; - case '}': - return; - default: - throw x.syntaxError("Expected a ',' or '}'"); - } - } - } - - - /** - * Construct a JSONObject from a Map. - * - * @param map A map object that can be used to initialize the contents of - * the JSONObject. - * @throws JSONException - */ - public JSONObject(Map map) { - this.map = new HashMap(); - if (map != null) { - Iterator i = map.entrySet().iterator(); - while (i.hasNext()) { - Map.Entry e = (Map.Entry)i.next(); - this.map.put(e.getKey(), wrap(e.getValue())); - } - } - } - - - /** - * Construct a JSONObject from an Object using bean getters. - * It reflects on all of the public methods of the object. - * For each of the methods with no parameters and a name starting - * with "get" or "is" followed by an uppercase letter, - * the method is invoked, and a key and the value returned from the getter method - * are put into the new JSONObject. - * - * The key is formed by removing the "get" or "is" prefix. - * If the second remaining character is not upper case, then the first - * character is converted to lower case. - * - * For example, if an object has a method named "getName", and - * if the result of calling object.getName() is "Larry Fine", - * then the JSONObject will contain "name": "Larry Fine". - * - * @param bean An object that has getter methods that should be used - * to make a JSONObject. - */ - public JSONObject(Object bean) { - this(); - populateMap(bean); - } - - - /** - * Construct a JSONObject from an Object, using reflection to find the - * public members. The resulting JSONObject's keys will be the strings - * from the names array, and the values will be the field values associated - * with those keys in the object. If a key is not found or not visible, - * then it will not be copied into the new JSONObject. - * @param object An object that has fields that should be used to make a - * JSONObject. - * @param names An array of strings, the names of the fields to be obtained - * from the object. - */ - public JSONObject(Object object, String names[]) { - this(); - Class c = object.getClass(); - for (int i = 0; i < names.length; i += 1) { - String name = names[i]; - try { - putOpt(name, c.getField(name).get(object)); - } catch (Exception ignore) { - } - } - } - - - /** - * Construct a JSONObject from a source JSON text string. - * This is the most commonly used JSONObject constructor. - * @param source A string beginning - * with { (left brace) and ending - * with } (right brace). - * @exception JSONException If there is a syntax error in the source - * string or a duplicated key. - */ - public JSONObject(String source) throws JSONException { - this(new JSONTokener(source)); - } - - - /** - * Accumulate values under a key. It is similar to the put method except - * that if there is already an object stored under the key then a - * JSONArray is stored under the key to hold all of the accumulated values. - * If there is already a JSONArray, then the new value is appended to it. - * In contrast, the put method replaces the previous value. - * @param key A key string. - * @param value An object to be accumulated under the key. - * @return this. - * @throws JSONException If the value is an invalid number - * or if the key is null. - */ - public JSONObject accumulate(String key, Object value) - throws JSONException { - testValidity(value); - Object o = opt(key); - if (o == null) { - put(key, value instanceof JSONArray ? - new JSONArray().put(value) : - value); - } else if (o instanceof JSONArray) { - ((JSONArray)o).put(value); - } else { - put(key, new JSONArray().put(o).put(value)); - } - return this; - } - - - /** - * Append values to the array under a key. If the key does not exist in the - * JSONObject, then the key is put in the JSONObject with its value being a - * JSONArray containing the value parameter. If the key was already - * associated with a JSONArray, then the value parameter is appended to it. - * @param key A key string. - * @param value An object to be accumulated under the key. - * @return this. - * @throws JSONException If the key is null or if the current value - * associated with the key is not a JSONArray. - */ - public JSONObject append(String key, Object value) throws JSONException { - testValidity(value); - Object o = opt(key); - if (o == null) { - put(key, new JSONArray().put(value)); - } else if (o instanceof JSONArray) { - put(key, ((JSONArray)o).put(value)); - } else { - throw new JSONException("JSONObject[" + key + - "] is not a JSONArray."); - } - return this; - } - - - /** - * Produce a string from a double. The string "null" will be returned if - * the number is not finite. - * @param d A double. - * @return A String. - */ - static public String doubleToString(double d) { - if (Double.isInfinite(d) || Double.isNaN(d)) { - return "null"; - } + /** + * It is sometimes more convenient and less ambiguous to have a NULL object than to use Java's null + * value. JSONObject.NULL.equals(null) returns true. JSONObject.NULL.toString() returns + * "null". + */ + public static final Object NULL = new Null(); + + /** + * Construct an empty JSONObject. + */ + public JSONObject () { + this.map = new HashMap(); + } + + /** + * Construct a JSONObject from a subset of another JSONObject. An array of strings is used to identify the keys that should be + * copied. Missing keys are ignored. + * @param jo A JSONObject. + * @param names An array of strings. + * @throws JSONException + * @exception JSONException If a value is a non-finite number or if a name is duplicated. + */ + public JSONObject (JSONObject jo, String[] names) { + this(); + for (int i = 0; i < names.length; i += 1) { + try { + putOnce(names[i], jo.opt(names[i])); + } catch (Exception ignore) { + } + } + } + + /** + * Construct a JSONObject from a JSONTokener. + * @param x A JSONTokener object containing the source string. + * @throws JSONException If there is a syntax error in the source string or a duplicated key. + */ + public JSONObject (JSONTokener x) throws JSONException { + this(); + char c; + String key; + + if (x.nextClean() != '{') { + throw x.syntaxError("A JSONObject text must begin with '{'"); + } + for (;;) { + c = x.nextClean(); + switch (c) { + case 0: + throw x.syntaxError("A JSONObject text must end with '}'"); + case '}': + return; + default: + x.back(); + key = x.nextValue().toString(); + } + + /* + * The key is followed by ':'. We will also tolerate '=' or '=>'. + */ + + c = x.nextClean(); + if (c == '=') { + if (x.next() != '>') { + x.back(); + } + } else if (c != ':') { + throw x.syntaxError("Expected a ':' after a key"); + } + putOnce(key, x.nextValue()); + + /* + * Pairs are separated by ','. We will also tolerate ';'. + */ + + switch (x.nextClean()) { + case ';': + case ',': + if (x.nextClean() == '}') { + return; + } + x.back(); + break; + case '}': + return; + default: + throw x.syntaxError("Expected a ',' or '}'"); + } + } + } + + /** + * Construct a JSONObject from a Map. + * + * @param map A map object that can be used to initialize the contents of the JSONObject. + * @throws JSONException + */ + public JSONObject (Map map) { + this.map = new HashMap(); + if (map != null) { + Iterator i = map.entrySet().iterator(); + while (i.hasNext()) { + Map.Entry e = (Map.Entry)i.next(); + this.map.put(e.getKey(), wrap(e.getValue())); + } + } + } + + /** + * Construct a JSONObject from an Object using bean getters. It reflects on all of the public methods of the object. For each + * of the methods with no parameters and a name starting with "get" or "is" followed by an uppercase + * letter, the method is invoked, and a key and the value returned from the getter method are put into the new JSONObject. + * + * The key is formed by removing the "get" or "is" prefix. If the second remaining character is not + * upper case, then the first character is converted to lower case. + * + * For example, if an object has a method named "getName", and if the result of calling + * object.getName() is "Larry Fine", then the JSONObject will contain + * "name": "Larry Fine". + * + * @param bean An object that has getter methods that should be used to make a JSONObject. + */ + public JSONObject (Object bean) { + this(); + populateMap(bean); + } + + /** + * Construct a JSONObject from an Object, using reflection to find the public members. The resulting JSONObject's keys will be + * the strings from the names array, and the values will be the field values associated with those keys in the object. If a key + * is not found or not visible, then it will not be copied into the new JSONObject. + * @param object An object that has fields that should be used to make a JSONObject. + * @param names An array of strings, the names of the fields to be obtained from the object. + */ + public JSONObject (Object object, String names[]) { + this(); + Class c = object.getClass(); + for (int i = 0; i < names.length; i += 1) { + String name = names[i]; + try { + putOpt(name, c.getField(name).get(object)); + } catch (Exception ignore) { + } + } + } + + /** + * Construct a JSONObject from a source JSON text string. This is the most commonly used JSONObject constructor. + * @param source A string beginning with { (left brace) and ending with } + *  (right brace). + * @exception JSONException If there is a syntax error in the source string or a duplicated key. + */ + public JSONObject (String source) throws JSONException { + this(new JSONTokener(source)); + } + + /** + * Accumulate values under a key. It is similar to the put method except that if there is already an object stored under the + * key then a JSONArray is stored under the key to hold all of the accumulated values. If there is already a JSONArray, then + * the new value is appended to it. In contrast, the put method replaces the previous value. + * @param key A key string. + * @param value An object to be accumulated under the key. + * @return this. + * @throws JSONException If the value is an invalid number or if the key is null. + */ + public JSONObject accumulate (String key, Object value) throws JSONException { + testValidity(value); + Object o = opt(key); + if (o == null) { + put(key, value instanceof JSONArray ? new JSONArray().put(value) : value); + } else if (o instanceof JSONArray) { + ((JSONArray)o).put(value); + } else { + put(key, new JSONArray().put(o).put(value)); + } + return this; + } + + /** + * Append values to the array under a key. If the key does not exist in the JSONObject, then the key is put in the JSONObject + * with its value being a JSONArray containing the value parameter. If the key was already associated with a JSONArray, then + * the value parameter is appended to it. + * @param key A key string. + * @param value An object to be accumulated under the key. + * @return this. + * @throws JSONException If the key is null or if the current value associated with the key is not a JSONArray. + */ + public JSONObject append (String key, Object value) throws JSONException { + testValidity(value); + Object o = opt(key); + if (o == null) { + put(key, new JSONArray().put(value)); + } else if (o instanceof JSONArray) { + put(key, ((JSONArray)o).put(value)); + } else { + throw new JSONException("JSONObject[" + key + "] is not a JSONArray."); + } + return this; + } + + /** + * Produce a string from a double. The string "null" will be returned if the number is not finite. + * @param d A double. + * @return A String. + */ + static public String doubleToString (double d) { + if (Double.isInfinite(d) || Double.isNaN(d)) { + return "null"; + } // Shave off trailing zeros and decimal point, if possible. - String s = Double.toString(d); - if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) { - while (s.endsWith("0")) { - s = s.substring(0, s.length() - 1); - } - if (s.endsWith(".")) { - s = s.substring(0, s.length() - 1); - } - } - return s; - } - - - /** - * Get the value object associated with a key. - * - * @param key A key string. - * @return The object associated with the key. - * @throws JSONException if the key is not found. - */ - public Object get(String key) throws JSONException { - Object o = opt(key); - if (o == null) { - throw new JSONException("JSONObject[" + quote(key) + - "] not found."); - } - return o; - } - - - /** - * Get the boolean value associated with a key. - * - * @param key A key string. - * @return The truth. - * @throws JSONException - * if the value is not a Boolean or the String "true" or "false". - */ - public boolean getBoolean(String key) throws JSONException { - Object o = get(key); - if (o.equals(Boolean.FALSE) || - (o instanceof String && - ((String)o).equalsIgnoreCase("false"))) { - return false; - } else if (o.equals(Boolean.TRUE) || - (o instanceof String && - ((String)o).equalsIgnoreCase("true"))) { - return true; - } - throw new JSONException("JSONObject[" + quote(key) + - "] is not a Boolean."); - } - - - /** - * Get the double value associated with a key. - * @param key A key string. - * @return The numeric value. - * @throws JSONException if the key is not found or - * if the value is not a Number object and cannot be converted to a number. - */ - public double getDouble(String key) throws JSONException { - Object o = get(key); - try { - return o instanceof Number ? - ((Number)o).doubleValue() : - Double.valueOf((String)o).doubleValue(); - } catch (Exception e) { - throw new JSONException("JSONObject[" + quote(key) + - "] is not a number."); - } - } - - - /** - * Get the int value associated with a key. - * - * @param key A key string. - * @return The integer value. - * @throws JSONException if the key is not found or if the value cannot - * be converted to an integer. - */ - public int getInt(String key) throws JSONException { - Object o = get(key); - try { - return o instanceof Number ? - ((Number)o).intValue() : - Integer.parseInt((String)o); - } catch (Exception e) { - throw new JSONException("JSONObject[" + quote(key) + - "] is not an int."); - } - } - - - /** - * Get the JSONArray value associated with a key. - * - * @param key A key string. - * @return A JSONArray which is the value. - * @throws JSONException if the key is not found or - * if the value is not a JSONArray. - */ - public JSONArray getJSONArray(String key) throws JSONException { - Object o = get(key); - if (o instanceof JSONArray) { - return (JSONArray)o; - } - throw new JSONException("JSONObject[" + quote(key) + - "] is not a JSONArray."); - } - - - /** - * Get the JSONObject value associated with a key. - * - * @param key A key string. - * @return A JSONObject which is the value. - * @throws JSONException if the key is not found or - * if the value is not a JSONObject. - */ - public JSONObject getJSONObject(String key) throws JSONException { - Object o = get(key); - if (o instanceof JSONObject) { - return (JSONObject)o; - } - throw new JSONException("JSONObject[" + quote(key) + - "] is not a JSONObject."); - } - - - /** - * Get the long value associated with a key. - * - * @param key A key string. - * @return The long value. - * @throws JSONException if the key is not found or if the value cannot - * be converted to a long. - */ - public long getLong(String key) throws JSONException { - Object o = get(key); - try { - return o instanceof Number ? - ((Number)o).longValue() : - Long.parseLong((String)o); - } catch (Exception e) { - throw new JSONException("JSONObject[" + quote(key) + - "] is not a long."); - } - } - - - /** - * Get an array of field names from a JSONObject. - * - * @return An array of field names, or null if there are no names. - */ - public static String[] getNames(JSONObject jo) { - int length = jo.length(); - if (length == 0) { - return null; - } - Iterator i = jo.keys(); - String[] names = new String[length]; - int j = 0; - while (i.hasNext()) { - names[j] = (String)i.next(); - j += 1; - } - return names; - } - - - /** - * Get an array of field names from an Object. - * - * @return An array of field names, or null if there are no names. - */ - public static String[] getNames(Object object) { - if (object == null) { - return null; - } - Class klass = object.getClass(); - Field[] fields = klass.getFields(); - int length = fields.length; - if (length == 0) { - return null; - } - String[] names = new String[length]; - for (int i = 0; i < length; i += 1) { - names[i] = fields[i].getName(); - } - return names; - } - - - /** - * Get the string associated with a key. - * - * @param key A key string. - * @return A string which is the value. - * @throws JSONException if the key is not found. - */ - public String getString(String key) throws JSONException { - return get(key).toString(); - } - - - /** - * Determine if the JSONObject contains a specific key. - * @param key A key string. - * @return true if the key exists in the JSONObject. - */ - public boolean has(String key) { - return this.map.containsKey(key); - } - - - /** - * Increment a property of a JSONObject. If there is no such property, - * create one with a value of 1. If there is such a property, and if - * it is an Integer, Long, Double, or Float, then add one to it. - * @param key A key string. - * @return this. - * @throws JSONException If there is already a property with this name - * that is not an Integer, Long, Double, or Float. - */ - public JSONObject increment(String key) throws JSONException { - Object value = opt(key); - if (value == null) { - put(key, 1); - } else { - if (value instanceof Integer) { - put(key, ((Integer)value).intValue() + 1); - } else if (value instanceof Long) { - put(key, ((Long)value).longValue() + 1); - } else if (value instanceof Double) { - put(key, ((Double)value).doubleValue() + 1); - } else if (value instanceof Float) { - put(key, ((Float)value).floatValue() + 1); - } else { - throw new JSONException("Unable to increment [" + key + "]."); - } - } - return this; - } - - - /** - * Determine if the value associated with the key is null or if there is - * no value. - * @param key A key string. - * @return true if there is no value associated with the key or if - * the value is the JSONObject.NULL object. - */ - public boolean isNull(String key) { - return JSONObject.NULL.equals(opt(key)); - } - - - /** - * Get an enumeration of the keys of the JSONObject. - * - * @return An iterator of the keys. - */ - public Iterator keys() { - return this.map.keySet().iterator(); - } - - - /** - * Get the number of keys stored in the JSONObject. - * - * @return The number of keys in the JSONObject. - */ - public int length() { - return this.map.size(); - } - - - /** - * Produce a JSONArray containing the names of the elements of this - * JSONObject. - * @return A JSONArray containing the key strings, or null if the JSONObject - * is empty. - */ - public JSONArray names() { - JSONArray ja = new JSONArray(); - Iterator keys = keys(); - while (keys.hasNext()) { - ja.put(keys.next()); - } - return ja.length() == 0 ? null : ja; - } - - /** - * Produce a string from a Number. - * @param n A Number - * @return A String. - * @throws JSONException If n is a non-finite number. - */ - static public String numberToString(Number n) - throws JSONException { - if (n == null) { - throw new JSONException("Null pointer"); - } - testValidity(n); + String s = Double.toString(d); + if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) { + while (s.endsWith("0")) { + s = s.substring(0, s.length() - 1); + } + if (s.endsWith(".")) { + s = s.substring(0, s.length() - 1); + } + } + return s; + } + + /** + * Get the value object associated with a key. + * + * @param key A key string. + * @return The object associated with the key. + * @throws JSONException if the key is not found. + */ + public Object get (String key) throws JSONException { + Object o = opt(key); + if (o == null) { + throw new JSONException("JSONObject[" + quote(key) + "] not found."); + } + return o; + } + + /** + * Get the boolean value associated with a key. + * + * @param key A key string. + * @return The truth. + * @throws JSONException if the value is not a Boolean or the String "true" or "false". + */ + public boolean getBoolean (String key) throws JSONException { + Object o = get(key); + if (o.equals(Boolean.FALSE) || (o instanceof String && ((String)o).equalsIgnoreCase("false"))) { + return false; + } else if (o.equals(Boolean.TRUE) || (o instanceof String && ((String)o).equalsIgnoreCase("true"))) { + return true; + } + throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean."); + } + + /** + * Get the double value associated with a key. + * @param key A key string. + * @return The numeric value. + * @throws JSONException if the key is not found or if the value is not a Number object and cannot be converted to a number. + */ + public double getDouble (String key) throws JSONException { + Object o = get(key); + try { + return o instanceof Number ? ((Number)o).doubleValue() : Double.valueOf((String)o).doubleValue(); + } catch (Exception e) { + throw new JSONException("JSONObject[" + quote(key) + "] is not a number."); + } + } + + /** + * Get the int value associated with a key. + * + * @param key A key string. + * @return The integer value. + * @throws JSONException if the key is not found or if the value cannot be converted to an integer. + */ + public int getInt (String key) throws JSONException { + Object o = get(key); + try { + return o instanceof Number ? ((Number)o).intValue() : Integer.parseInt((String)o); + } catch (Exception e) { + throw new JSONException("JSONObject[" + quote(key) + "] is not an int."); + } + } + + /** + * Get the JSONArray value associated with a key. + * + * @param key A key string. + * @return A JSONArray which is the value. + * @throws JSONException if the key is not found or if the value is not a JSONArray. + */ + public JSONArray getJSONArray (String key) throws JSONException { + Object o = get(key); + if (o instanceof JSONArray) { + return (JSONArray)o; + } + throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray."); + } + + /** + * Get the JSONObject value associated with a key. + * + * @param key A key string. + * @return A JSONObject which is the value. + * @throws JSONException if the key is not found or if the value is not a JSONObject. + */ + public JSONObject getJSONObject (String key) throws JSONException { + Object o = get(key); + if (o instanceof JSONObject) { + return (JSONObject)o; + } + throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject."); + } + + /** + * Get the long value associated with a key. + * + * @param key A key string. + * @return The long value. + * @throws JSONException if the key is not found or if the value cannot be converted to a long. + */ + public long getLong (String key) throws JSONException { + Object o = get(key); + try { + return o instanceof Number ? ((Number)o).longValue() : Long.parseLong((String)o); + } catch (Exception e) { + throw new JSONException("JSONObject[" + quote(key) + "] is not a long."); + } + } + + /** + * Get an array of field names from a JSONObject. + * + * @return An array of field names, or null if there are no names. + */ + public static String[] getNames (JSONObject jo) { + int length = jo.length(); + if (length == 0) { + return null; + } + Iterator i = jo.keys(); + String[] names = new String[length]; + int j = 0; + while (i.hasNext()) { + names[j] = (String)i.next(); + j += 1; + } + return names; + } + + /** + * Get an array of field names from an Object. + * + * @return An array of field names, or null if there are no names. + */ + public static String[] getNames (Object object) { + if (object == null) { + return null; + } + Class klass = object.getClass(); + Field[] fields = klass.getFields(); + int length = fields.length; + if (length == 0) { + return null; + } + String[] names = new String[length]; + for (int i = 0; i < length; i += 1) { + names[i] = fields[i].getName(); + } + return names; + } + + /** + * Get the string associated with a key. + * + * @param key A key string. + * @return A string which is the value. + * @throws JSONException if the key is not found. + */ + public String getString (String key) throws JSONException { + return get(key).toString(); + } + + /** + * Determine if the JSONObject contains a specific key. + * @param key A key string. + * @return true if the key exists in the JSONObject. + */ + public boolean has (String key) { + return this.map.containsKey(key); + } + + /** + * Increment a property of a JSONObject. If there is no such property, create one with a value of 1. If there is such a + * property, and if it is an Integer, Long, Double, or Float, then add one to it. + * @param key A key string. + * @return this. + * @throws JSONException If there is already a property with this name that is not an Integer, Long, Double, or Float. + */ + public JSONObject increment (String key) throws JSONException { + Object value = opt(key); + if (value == null) { + put(key, 1); + } else { + if (value instanceof Integer) { + put(key, ((Integer)value).intValue() + 1); + } else if (value instanceof Long) { + put(key, ((Long)value).longValue() + 1); + } else if (value instanceof Double) { + put(key, ((Double)value).doubleValue() + 1); + } else if (value instanceof Float) { + put(key, ((Float)value).floatValue() + 1); + } else { + throw new JSONException("Unable to increment [" + key + "]."); + } + } + return this; + } + + /** + * Determine if the value associated with the key is null or if there is no value. + * @param key A key string. + * @return true if there is no value associated with the key or if the value is the JSONObject.NULL object. + */ + public boolean isNull (String key) { + return JSONObject.NULL.equals(opt(key)); + } + + /** + * Get an enumeration of the keys of the JSONObject. + * + * @return An iterator of the keys. + */ + public Iterator keys () { + return this.map.keySet().iterator(); + } + + /** + * Get the number of keys stored in the JSONObject. + * + * @return The number of keys in the JSONObject. + */ + public int length () { + return this.map.size(); + } + + /** + * Produce a JSONArray containing the names of the elements of this JSONObject. + * @return A JSONArray containing the key strings, or null if the JSONObject is empty. + */ + public JSONArray names () { + JSONArray ja = new JSONArray(); + Iterator keys = keys(); + while (keys.hasNext()) { + ja.put(keys.next()); + } + return ja.length() == 0 ? null : ja; + } + + /** + * Produce a string from a Number. + * @param n A Number + * @return A String. + * @throws JSONException If n is a non-finite number. + */ + static public String numberToString (Number n) throws JSONException { + if (n == null) { + throw new JSONException("Null pointer"); + } + testValidity(n); // Shave off trailing zeros and decimal point, if possible. - String s = n.toString(); - if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) { - while (s.endsWith("0")) { - s = s.substring(0, s.length() - 1); - } - if (s.endsWith(".")) { - s = s.substring(0, s.length() - 1); - } - } - return s; - } - - - /** - * Get an optional value associated with a key. - * @param key A key string. - * @return An object which is the value, or null if there is no value. - */ - public Object opt(String key) { - return key == null ? null : this.map.get(key); - } - - - /** - * Get an optional boolean associated with a key. - * It returns false if there is no such key, or if the value is not - * Boolean.TRUE or the String "true". - * - * @param key A key string. - * @return The truth. - */ - public boolean optBoolean(String key) { - return optBoolean(key, false); - } - - - /** - * Get an optional boolean associated with a key. - * It returns the defaultValue if there is no such key, or if it is not - * a Boolean or the String "true" or "false" (case insensitive). - * - * @param key A key string. - * @param defaultValue The default. - * @return The truth. - */ - public boolean optBoolean(String key, boolean defaultValue) { - try { - return getBoolean(key); - } catch (Exception e) { - return defaultValue; - } - } - - - /** - * Get an optional double associated with a key, - * or NaN if there is no such key or if its value is not a number. - * If the value is a string, an attempt will be made to evaluate it as - * a number. - * - * @param key A string which is the key. - * @return An object which is the value. - */ - public double optDouble(String key) { - return optDouble(key, Double.NaN); - } - - - /** - * Get an optional double associated with a key, or the - * defaultValue if there is no such key or if its value is not a number. - * If the value is a string, an attempt will be made to evaluate it as - * a number. - * - * @param key A key string. - * @param defaultValue The default. - * @return An object which is the value. - */ - public double optDouble(String key, double defaultValue) { - try { - Object o = opt(key); - return o instanceof Number ? ((Number)o).doubleValue() : - new Double((String)o).doubleValue(); - } catch (Exception e) { - return defaultValue; - } - } - - - /** - * Get an optional int value associated with a key, - * or zero if there is no such key or if the value is not a number. - * If the value is a string, an attempt will be made to evaluate it as - * a number. - * - * @param key A key string. - * @return An object which is the value. - */ - public int optInt(String key) { - return optInt(key, 0); - } - - - /** - * Get an optional int value associated with a key, - * or the default if there is no such key or if the value is not a number. - * If the value is a string, an attempt will be made to evaluate it as - * a number. - * - * @param key A key string. - * @param defaultValue The default. - * @return An object which is the value. - */ - public int optInt(String key, int defaultValue) { - try { - return getInt(key); - } catch (Exception e) { - return defaultValue; - } - } - - - /** - * Get an optional JSONArray associated with a key. - * It returns null if there is no such key, or if its value is not a - * JSONArray. - * - * @param key A key string. - * @return A JSONArray which is the value. - */ - public JSONArray optJSONArray(String key) { - Object o = opt(key); - return o instanceof JSONArray ? (JSONArray)o : null; - } - - - /** - * Get an optional JSONObject associated with a key. - * It returns null if there is no such key, or if its value is not a - * JSONObject. - * - * @param key A key string. - * @return A JSONObject which is the value. - */ - public JSONObject optJSONObject(String key) { - Object o = opt(key); - return o instanceof JSONObject ? (JSONObject)o : null; - } - - - /** - * Get an optional long value associated with a key, - * or zero if there is no such key or if the value is not a number. - * If the value is a string, an attempt will be made to evaluate it as - * a number. - * - * @param key A key string. - * @return An object which is the value. - */ - public long optLong(String key) { - return optLong(key, 0); - } - - - /** - * Get an optional long value associated with a key, - * or the default if there is no such key or if the value is not a number. - * If the value is a string, an attempt will be made to evaluate it as - * a number. - * - * @param key A key string. - * @param defaultValue The default. - * @return An object which is the value. - */ - public long optLong(String key, long defaultValue) { - try { - return getLong(key); - } catch (Exception e) { - return defaultValue; - } - } - - - /** - * Get an optional string associated with a key. - * It returns an empty string if there is no such key. If the value is not - * a string and is not null, then it is coverted to a string. - * - * @param key A key string. - * @return A string which is the value. - */ - public String optString(String key) { - return optString(key, ""); - } - - - /** - * Get an optional string associated with a key. - * It returns the defaultValue if there is no such key. - * - * @param key A key string. - * @param defaultValue The default. - * @return A string which is the value. - */ - public String optString(String key, String defaultValue) { - Object o = opt(key); - return o != null ? o.toString() : defaultValue; - } - - - private void populateMap(Object bean) { - Class klass = bean.getClass(); - -// If klass is a System class then set includeSuperClass to false. - - boolean includeSuperClass = klass.getClassLoader() != null; - - Method[] methods = (includeSuperClass) ? - klass.getMethods() : klass.getDeclaredMethods(); - for (int i = 0; i < methods.length; i += 1) { - try { - Method method = methods[i]; - if (Modifier.isPublic(method.getModifiers())) { - String name = method.getName(); - String key = ""; - if (name.startsWith("get")) { - if (name.equals("getClass") || - name.equals("getDeclaringClass")) { - key = ""; - } else { - key = name.substring(3); - } - } else if (name.startsWith("is")) { - key = name.substring(2); - } - if (key.length() > 0 && - Character.isUpperCase(key.charAt(0)) && - method.getParameterTypes().length == 0) { - if (key.length() == 1) { - key = key.toLowerCase(); - } else if (!Character.isUpperCase(key.charAt(1))) { - key = key.substring(0, 1).toLowerCase() + - key.substring(1); - } - - Object result = method.invoke(bean, (Object[])null); - - map.put(key, wrap(result)); - } - } - } catch (Exception ignore) { - } - } - } - - - /** - * Put a key/boolean pair in the JSONObject. - * - * @param key A key string. - * @param value A boolean which is the value. - * @return this. - * @throws JSONException If the key is null. - */ - public JSONObject put(String key, boolean value) throws JSONException { - put(key, value ? Boolean.TRUE : Boolean.FALSE); - return this; - } - - - /** - * Put a key/value pair in the JSONObject, where the value will be a - * JSONArray which is produced from a Collection. - * @param key A key string. - * @param value A Collection value. - * @return this. - * @throws JSONException - */ - public JSONObject put(String key, Collection value) throws JSONException { - put(key, new JSONArray(value)); - return this; - } - - - /** - * Put a key/double pair in the JSONObject. - * - * @param key A key string. - * @param value A double which is the value. - * @return this. - * @throws JSONException If the key is null or if the number is invalid. - */ - public JSONObject put(String key, double value) throws JSONException { - put(key, new Double(value)); - return this; - } - - - /** - * Put a key/int pair in the JSONObject. - * - * @param key A key string. - * @param value An int which is the value. - * @return this. - * @throws JSONException If the key is null. - */ - public JSONObject put(String key, int value) throws JSONException { - put(key, new Integer(value)); - return this; - } - - - /** - * Put a key/long pair in the JSONObject. - * - * @param key A key string. - * @param value A long which is the value. - * @return this. - * @throws JSONException If the key is null. - */ - public JSONObject put(String key, long value) throws JSONException { - put(key, new Long(value)); - return this; - } - - - /** - * Put a key/value pair in the JSONObject, where the value will be a - * JSONObject which is produced from a Map. - * @param key A key string. - * @param value A Map value. - * @return this. - * @throws JSONException - */ - public JSONObject put(String key, Map value) throws JSONException { - put(key, new JSONObject(value)); - return this; - } - - - /** - * Put a key/value pair in the JSONObject. If the value is null, - * then the key will be removed from the JSONObject if it is present. - * @param key A key string. - * @param value An object which is the value. It should be of one of these - * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, - * or the JSONObject.NULL object. - * @return this. - * @throws JSONException If the value is non-finite number - * or if the key is null. - */ - public JSONObject put(String key, Object value) throws JSONException { - if (key == null) { - throw new JSONException("Null key."); - } - if (value != null) { - testValidity(value); - this.map.put(key, value); - } else { - remove(key); - } - return this; - } - - - /** - * Put a key/value pair in the JSONObject, but only if the key and the - * value are both non-null, and only if there is not already a member - * with that name. - * @param key - * @param value - * @return his. - * @throws JSONException if the key is a duplicate - */ - public JSONObject putOnce(String key, Object value) throws JSONException { - if (key != null && value != null) { - if (opt(key) != null) { - throw new JSONException("Duplicate key \"" + key + "\""); - } - put(key, value); - } - return this; - } - - - /** - * Put a key/value pair in the JSONObject, but only if the - * key and the value are both non-null. - * @param key A key string. - * @param value An object which is the value. It should be of one of these - * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, - * or the JSONObject.NULL object. - * @return this. - * @throws JSONException If the value is a non-finite number. - */ - public JSONObject putOpt(String key, Object value) throws JSONException { - if (key != null && value != null) { - put(key, value); - } - return this; - } - - - /** - * Produce a string in double quotes with backslash sequences in all the - * right places. A backslash will be inserted within = '\u0080' && c < '\u00a0') || - (c >= '\u2000' && c < '\u2100')) { - t = "000" + Integer.toHexString(c); - sb.append("\\u" + t.substring(t.length() - 4)); - } else { - sb.append(c); - } - } - } - sb.append('"'); - return sb.toString(); - } - - /** - * Remove a name and its value, if present. - * @param key The name to be removed. - * @return The value that was associated with the name, - * or null if there was no value. - */ - public Object remove(String key) { - return this.map.remove(key); - } - - /** - * Get an enumeration of the keys of the JSONObject. - * The keys will be sorted alphabetically. - * - * @return An iterator of the keys. - */ - public Iterator sortedKeys() { - return new TreeSet(this.map.keySet()).iterator(); - } - - /** - * Try to convert a string into a number, boolean, or null. If the string - * can't be converted, return the string. - * @param s A String. - * @return A simple JSON value. - */ - static public Object stringToValue(String s) { - if (s.equals("")) { - return s; - } - if (s.equalsIgnoreCase("true")) { - return Boolean.TRUE; - } - if (s.equalsIgnoreCase("false")) { - return Boolean.FALSE; - } - if (s.equalsIgnoreCase("null")) { - return JSONObject.NULL; - } - - /* - * If it might be a number, try converting it. - * We support the non-standard 0x- convention. - * If a number cannot be produced, then the value will just - * be a string. Note that the 0x-, plus, and implied string - * conventions are non-standard. A JSON parser may accept - * non-JSON forms as long as it accepts all correct JSON forms. - */ - - char b = s.charAt(0); - if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') { - if (b == '0' && s.length() > 2 && - (s.charAt(1) == 'x' || s.charAt(1) == 'X')) { - try { - return new Integer(Integer.parseInt(s.substring(2), 16)); - } catch (Exception ignore) { - } - } - try { - if (s.indexOf('.') > -1 || - s.indexOf('e') > -1 || s.indexOf('E') > -1) { - return Double.valueOf(s); - } else { - Long myLong = new Long(s); - if (myLong.longValue() == myLong.intValue()) { - return new Integer(myLong.intValue()); - } else { - return myLong; - } - } - } catch (Exception ignore) { - } - } - return s; - } - - - /** - * Throw an exception if the object is an NaN or infinite number. - * @param o The object to test. - * @throws JSONException If o is a non-finite number. - */ - static void testValidity(Object o) throws JSONException { - if (o != null) { - if (o instanceof Double) { - if (((Double)o).isInfinite() || ((Double)o).isNaN()) { - throw new JSONException( - "JSON does not allow non-finite numbers."); - } - } else if (o instanceof Float) { - if (((Float)o).isInfinite() || ((Float)o).isNaN()) { - throw new JSONException( - "JSON does not allow non-finite numbers."); - } - } - } - } - - - /** - * Produce a JSONArray containing the values of the members of this - * JSONObject. - * @param names A JSONArray containing a list of key strings. This - * determines the sequence of the values in the result. - * @return A JSONArray of values. - * @throws JSONException If any of the values are non-finite numbers. - */ - public JSONArray toJSONArray(JSONArray names) throws JSONException { - if (names == null || names.length() == 0) { - return null; - } - JSONArray ja = new JSONArray(); - for (int i = 0; i < names.length(); i += 1) { - ja.put(this.opt(names.getString(i))); - } - return ja; - } - - /** - * Make a JSON text of this JSONObject. For compactness, no whitespace - * is added. If this would not result in a syntactically correct JSON text, - * then null will be returned instead. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return a printable, displayable, portable, transmittable - * representation of the object, beginning - * with { (left brace) and ending - * with } (right brace). - */ - public String toString() { - try { - Iterator keys = keys(); - StringBuffer sb = new StringBuffer("{"); - - while (keys.hasNext()) { - if (sb.length() > 1) { - sb.append(','); - } - Object o = keys.next(); - sb.append(quote(o.toString())); - sb.append(':'); - sb.append(valueToString(this.map.get(o))); - } - sb.append('}'); - return sb.toString(); - } catch (Exception e) { - return null; - } - } - - - /** - * Make a prettyprinted JSON text of this JSONObject. - *

- * Warning: This method assumes that the data structure is acyclical. - * @param indentFactor The number of spaces to add to each level of - * indentation. - * @return a printable, displayable, portable, transmittable - * representation of the object, beginning - * with { (left brace) and ending - * with } (right brace). - * @throws JSONException If the object contains an invalid number. - */ - public String toString(int indentFactor) throws JSONException { - return toString(indentFactor, 0); - } - - - /** - * Make a prettyprinted JSON text of this JSONObject. - *

- * Warning: This method assumes that the data structure is acyclical. - * @param indentFactor The number of spaces to add to each level of - * indentation. - * @param indent The indentation of the top level. - * @return a printable, displayable, transmittable - * representation of the object, beginning - * with { (left brace) and ending - * with } (right brace). - * @throws JSONException If the object contains an invalid number. - */ - String toString(int indentFactor, int indent) throws JSONException { - int j; - int n = length(); - if (n == 0) { - return "{}"; - } - Iterator keys = sortedKeys(); - StringBuffer sb = new StringBuffer("{"); - int newindent = indent + indentFactor; - Object o; - if (n == 1) { - o = keys.next(); - sb.append(quote(o.toString())); - sb.append(": "); - sb.append(valueToString(this.map.get(o), indentFactor, - indent)); - } else { - while (keys.hasNext()) { - o = keys.next(); - if (sb.length() > 1) { - sb.append(",\n"); - } else { - sb.append('\n'); - } - for (j = 0; j < newindent; j += 1) { - sb.append(' '); - } - sb.append(quote(o.toString())); - sb.append(": "); - sb.append(valueToString(this.map.get(o), indentFactor, - newindent)); - } - if (sb.length() > 1) { - sb.append('\n'); - for (j = 0; j < indent; j += 1) { - sb.append(' '); - } - } - } - sb.append('}'); - return sb.toString(); - } - - - /** - * Make a JSON text of an Object value. If the object has an - * value.toJSONString() method, then that method will be used to produce - * the JSON text. The method is required to produce a strictly - * conforming text. If the object does not contain a toJSONString - * method (which is the most common case), then a text will be - * produced by other means. If the value is an array or Collection, - * then a JSONArray will be made from it and its toJSONString method - * will be called. If the value is a MAP, then a JSONObject will be made - * from it and its toJSONString method will be called. Otherwise, the - * value's toString method will be called, and the result will be quoted. - * - *

- * Warning: This method assumes that the data structure is acyclical. - * @param value The value to be serialized. - * @return a printable, displayable, transmittable - * representation of the object, beginning - * with { (left brace) and ending - * with } (right brace). - * @throws JSONException If the value is or contains an invalid number. - */ - static String valueToString(Object value) throws JSONException { - if (value == null || value.equals(null)) { - return "null"; - } - if (value instanceof JSONString) { - Object o; - try { - o = ((JSONString)value).toJSONString(); - } catch (Exception e) { - throw new JSONException(e); - } - if (o instanceof String) { - return (String)o; - } - throw new JSONException("Bad value from toJSONString: " + o); - } - if (value instanceof Number) { - return numberToString((Number) value); - } - if (value instanceof Boolean || value instanceof JSONObject || - value instanceof JSONArray) { - return value.toString(); - } - if (value instanceof Map) { - return new JSONObject((Map)value).toString(); - } - if (value instanceof Collection) { - return new JSONArray((Collection)value).toString(); - } - if (value.getClass().isArray()) { - return new JSONArray(value).toString(); - } - return quote(value.toString()); - } - - - /** - * Make a prettyprinted JSON text of an object value. - *

- * Warning: This method assumes that the data structure is acyclical. - * @param value The value to be serialized. - * @param indentFactor The number of spaces to add to each level of - * indentation. - * @param indent The indentation of the top level. - * @return a printable, displayable, transmittable - * representation of the object, beginning - * with { (left brace) and ending - * with } (right brace). - * @throws JSONException If the object contains an invalid number. - */ - static String valueToString(Object value, int indentFactor, int indent) - throws JSONException { - if (value == null || value.equals(null)) { - return "null"; - } - try { - if (value instanceof JSONString) { - Object o = ((JSONString)value).toJSONString(); - if (o instanceof String) { - return (String)o; - } - } - } catch (Exception ignore) { - } - if (value instanceof Number) { - return numberToString((Number) value); - } - if (value instanceof Boolean) { - return value.toString(); - } - if (value instanceof JSONObject) { - return ((JSONObject)value).toString(indentFactor, indent); - } - if (value instanceof JSONArray) { - return ((JSONArray)value).toString(indentFactor, indent); - } - if (value instanceof Map) { - return new JSONObject((Map)value).toString(indentFactor, indent); - } - if (value instanceof Collection) { - return new JSONArray((Collection)value).toString(indentFactor, indent); - } - if (value.getClass().isArray()) { - return new JSONArray(value).toString(indentFactor, indent); - } - return quote(value.toString()); - } - - - /** - * Wrap an object, if necessary. If the object is null, return the NULL - * object. If it is an array or collection, wrap it in a JSONArray. If - * it is a map, wrap it in a JSONObject. If it is a standard property - * (Double, String, et al) then it is already wrapped. Otherwise, if it - * comes from one of the java packages, turn it into a string. And if - * it doesn't, try to wrap it in a JSONObject. If the wrapping fails, - * then null is returned. - * - * @param object The object to wrap - * @return The wrapped value - */ - static Object wrap(Object object) { - try { - if (object == null) { - return NULL; - } - if (object instanceof JSONObject || object instanceof JSONArray || - NULL.equals(object) || object instanceof JSONString || - object instanceof Byte || object instanceof Character || - object instanceof Short || object instanceof Integer || - object instanceof Long || object instanceof Boolean || - object instanceof Float || object instanceof Double || - object instanceof String) { - return object; - } - - if (object instanceof Collection) { - return new JSONArray((Collection)object); - } - if (object.getClass().isArray()) { - return new JSONArray(object); - } - if (object instanceof Map) { - return new JSONObject((Map)object); - } - Package objectPackage = object.getClass().getPackage(); - String objectPackageName = ( objectPackage != null ? objectPackage.getName() : "" ); - if (objectPackageName.startsWith("java.") || - objectPackageName.startsWith("javax.") || - object.getClass().getClassLoader() == null) { - return object.toString(); - } - return new JSONObject(object); - } catch(Exception exception) { - return null; - } - } - - - /** - * Write the contents of the JSONObject as JSON text to a writer. - * For compactness, no whitespace is added. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return The writer. - * @throws JSONException - */ - public Writer write(Writer writer) throws JSONException { - try { - boolean b = false; - Iterator keys = keys(); - writer.write('{'); - - while (keys.hasNext()) { - if (b) { - writer.write(','); - } - Object k = keys.next(); - writer.write(quote(k.toString())); - writer.write(':'); - Object v = this.map.get(k); - if (v instanceof JSONObject) { - ((JSONObject)v).write(writer); - } else if (v instanceof JSONArray) { - ((JSONArray)v).write(writer); - } else { - writer.write(valueToString(v)); - } - b = true; - } - writer.write('}'); - return writer; - } catch (IOException exception) { - throw new JSONException(exception); - } - } -} \ No newline at end of file + String s = n.toString(); + if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) { + while (s.endsWith("0")) { + s = s.substring(0, s.length() - 1); + } + if (s.endsWith(".")) { + s = s.substring(0, s.length() - 1); + } + } + return s; + } + + /** + * Get an optional value associated with a key. + * @param key A key string. + * @return An object which is the value, or null if there is no value. + */ + public Object opt (String key) { + return key == null ? null : this.map.get(key); + } + + /** + * Get an optional boolean associated with a key. It returns false if there is no such key, or if the value is not Boolean.TRUE + * or the String "true". + * + * @param key A key string. + * @return The truth. + */ + public boolean optBoolean (String key) { + return optBoolean(key, false); + } + + /** + * Get an optional boolean associated with a key. It returns the defaultValue if there is no such key, or if it is not a + * Boolean or the String "true" or "false" (case insensitive). + * + * @param key A key string. + * @param defaultValue The default. + * @return The truth. + */ + public boolean optBoolean (String key, boolean defaultValue) { + try { + return getBoolean(key); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Get an optional double associated with a key, or NaN if there is no such key or if its value is not a number. If the value + * is a string, an attempt will be made to evaluate it as a number. + * + * @param key A string which is the key. + * @return An object which is the value. + */ + public double optDouble (String key) { + return optDouble(key, Double.NaN); + } + + /** + * Get an optional double associated with a key, or the defaultValue if there is no such key or if its value is not a number. + * If the value is a string, an attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public double optDouble (String key, double defaultValue) { + try { + Object o = opt(key); + return o instanceof Number ? ((Number)o).doubleValue() : new Double((String)o).doubleValue(); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Get an optional int value associated with a key, or zero if there is no such key or if the value is not a number. If the + * value is a string, an attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @return An object which is the value. + */ + public int optInt (String key) { + return optInt(key, 0); + } + + /** + * Get an optional int value associated with a key, or the default if there is no such key or if the value is not a number. If + * the value is a string, an attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public int optInt (String key, int defaultValue) { + try { + return getInt(key); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Get an optional JSONArray associated with a key. It returns null if there is no such key, or if its value is not a + * JSONArray. + * + * @param key A key string. + * @return A JSONArray which is the value. + */ + public JSONArray optJSONArray (String key) { + Object o = opt(key); + return o instanceof JSONArray ? (JSONArray)o : null; + } + + /** + * Get an optional JSONObject associated with a key. It returns null if there is no such key, or if its value is not a + * JSONObject. + * + * @param key A key string. + * @return A JSONObject which is the value. + */ + public JSONObject optJSONObject (String key) { + Object o = opt(key); + return o instanceof JSONObject ? (JSONObject)o : null; + } + + /** + * Get an optional long value associated with a key, or zero if there is no such key or if the value is not a number. If the + * value is a string, an attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @return An object which is the value. + */ + public long optLong (String key) { + return optLong(key, 0); + } + + /** + * Get an optional long value associated with a key, or the default if there is no such key or if the value is not a number. If + * the value is a string, an attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public long optLong (String key, long defaultValue) { + try { + return getLong(key); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Get an optional string associated with a key. It returns an empty string if there is no such key. If the value is not a + * string and is not null, then it is coverted to a string. + * + * @param key A key string. + * @return A string which is the value. + */ + public String optString (String key) { + return optString(key, ""); + } + + /** + * Get an optional string associated with a key. It returns the defaultValue if there is no such key. + * + * @param key A key string. + * @param defaultValue The default. + * @return A string which is the value. + */ + public String optString (String key, String defaultValue) { + Object o = opt(key); + return o != null ? o.toString() : defaultValue; + } + + private void populateMap (Object bean) { + Class klass = bean.getClass(); + +// If klass is a System class then set includeSuperClass to false. + + boolean includeSuperClass = klass.getClassLoader() != null; + + Method[] methods = (includeSuperClass) ? klass.getMethods() : klass.getDeclaredMethods(); + for (int i = 0; i < methods.length; i += 1) { + try { + Method method = methods[i]; + if (Modifier.isPublic(method.getModifiers())) { + String name = method.getName(); + String key = ""; + if (name.startsWith("get")) { + if (name.equals("getClass") || name.equals("getDeclaringClass")) { + key = ""; + } else { + key = name.substring(3); + } + } else if (name.startsWith("is")) { + key = name.substring(2); + } + if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) { + if (key.length() == 1) { + key = key.toLowerCase(); + } else if (!Character.isUpperCase(key.charAt(1))) { + key = key.substring(0, 1).toLowerCase() + key.substring(1); + } + + Object result = method.invoke(bean, (Object[])null); + + map.put(key, wrap(result)); + } + } + } catch (Exception ignore) { + } + } + } + + /** + * Put a key/boolean pair in the JSONObject. + * + * @param key A key string. + * @param value A boolean which is the value. + * @return this. + * @throws JSONException If the key is null. + */ + public JSONObject put (String key, boolean value) throws JSONException { + put(key, value ? Boolean.TRUE : Boolean.FALSE); + return this; + } + + /** + * Put a key/value pair in the JSONObject, where the value will be a JSONArray which is produced from a Collection. + * @param key A key string. + * @param value A Collection value. + * @return this. + * @throws JSONException + */ + public JSONObject put (String key, Collection value) throws JSONException { + put(key, new JSONArray(value)); + return this; + } + + /** + * Put a key/double pair in the JSONObject. + * + * @param key A key string. + * @param value A double which is the value. + * @return this. + * @throws JSONException If the key is null or if the number is invalid. + */ + public JSONObject put (String key, double value) throws JSONException { + put(key, new Double(value)); + return this; + } + + /** + * Put a key/int pair in the JSONObject. + * + * @param key A key string. + * @param value An int which is the value. + * @return this. + * @throws JSONException If the key is null. + */ + public JSONObject put (String key, int value) throws JSONException { + put(key, new Integer(value)); + return this; + } + + /** + * Put a key/long pair in the JSONObject. + * + * @param key A key string. + * @param value A long which is the value. + * @return this. + * @throws JSONException If the key is null. + */ + public JSONObject put (String key, long value) throws JSONException { + put(key, new Long(value)); + return this; + } + + /** + * Put a key/value pair in the JSONObject, where the value will be a JSONObject which is produced from a Map. + * @param key A key string. + * @param value A Map value. + * @return this. + * @throws JSONException + */ + public JSONObject put (String key, Map value) throws JSONException { + put(key, new JSONObject(value)); + return this; + } + + /** + * Put a key/value pair in the JSONObject. If the value is null, then the key will be removed from the JSONObject if it is + * present. + * @param key A key string. + * @param value An object which is the value. It should be of one of these types: Boolean, Double, Integer, JSONArray, + * JSONObject, Long, String, or the JSONObject.NULL object. + * @return this. + * @throws JSONException If the value is non-finite number or if the key is null. + */ + public JSONObject put (String key, Object value) throws JSONException { + if (key == null) { + throw new JSONException("Null key."); + } + if (value != null) { + testValidity(value); + this.map.put(key, value); + } else { + remove(key); + } + return this; + } + + /** + * Put a key/value pair in the JSONObject, but only if the key and the value are both non-null, and only if there is not + * already a member with that name. + * @param key + * @param value + * @return his. + * @throws JSONException if the key is a duplicate + */ + public JSONObject putOnce (String key, Object value) throws JSONException { + if (key != null && value != null) { + if (opt(key) != null) { + throw new JSONException("Duplicate key \"" + key + "\""); + } + put(key, value); + } + return this; + } + + /** + * Put a key/value pair in the JSONObject, but only if the key and the value are both non-null. + * @param key A key string. + * @param value An object which is the value. It should be of one of these types: Boolean, Double, Integer, JSONArray, + * JSONObject, Long, String, or the JSONObject.NULL object. + * @return this. + * @throws JSONException If the value is a non-finite number. + */ + public JSONObject putOpt (String key, Object value) throws JSONException { + if (key != null && value != null) { + put(key, value); + } + return this; + } + + /** + * Produce a string in double quotes with backslash sequences in all the right places. A backslash will be inserted within = '\u0080' && c < '\u00a0') || (c >= '\u2000' && c < '\u2100')) { + t = "000" + Integer.toHexString(c); + sb.append("\\u" + t.substring(t.length() - 4)); + } else { + sb.append(c); + } + } + } + sb.append('"'); + return sb.toString(); + } + + /** + * Remove a name and its value, if present. + * @param key The name to be removed. + * @return The value that was associated with the name, or null if there was no value. + */ + public Object remove (String key) { + return this.map.remove(key); + } + + /** + * Get an enumeration of the keys of the JSONObject. The keys will be sorted alphabetically. + * + * @return An iterator of the keys. + */ + public Iterator sortedKeys () { + return new TreeSet(this.map.keySet()).iterator(); + } + + /** + * Try to convert a string into a number, boolean, or null. If the string can't be converted, return the string. + * @param s A String. + * @return A simple JSON value. + */ + static public Object stringToValue (String s) { + if (s.equals("")) { + return s; + } + if (s.equalsIgnoreCase("true")) { + return Boolean.TRUE; + } + if (s.equalsIgnoreCase("false")) { + return Boolean.FALSE; + } + if (s.equalsIgnoreCase("null")) { + return JSONObject.NULL; + } + + /* + * If it might be a number, try converting it. We support the non-standard 0x- convention. If a number cannot be produced, + * then the value will just be a string. Note that the 0x-, plus, and implied string conventions are non-standard. A JSON + * parser may accept non-JSON forms as long as it accepts all correct JSON forms. + */ + + char b = s.charAt(0); + if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') { + if (b == '0' && s.length() > 2 && (s.charAt(1) == 'x' || s.charAt(1) == 'X')) { + try { + return new Integer(Integer.parseInt(s.substring(2), 16)); + } catch (Exception ignore) { + } + } + try { + if (s.indexOf('.') > -1 || s.indexOf('e') > -1 || s.indexOf('E') > -1) { + return Double.valueOf(s); + } else { + Long myLong = new Long(s); + if (myLong.longValue() == myLong.intValue()) { + return new Integer(myLong.intValue()); + } else { + return myLong; + } + } + } catch (Exception ignore) { + } + } + return s; + } + + /** + * Throw an exception if the object is an NaN or infinite number. + * @param o The object to test. + * @throws JSONException If o is a non-finite number. + */ + static void testValidity (Object o) throws JSONException { + if (o != null) { + if (o instanceof Double) { + if (((Double)o).isInfinite() || ((Double)o).isNaN()) { + throw new JSONException("JSON does not allow non-finite numbers."); + } + } else if (o instanceof Float) { + if (((Float)o).isInfinite() || ((Float)o).isNaN()) { + throw new JSONException("JSON does not allow non-finite numbers."); + } + } + } + } + + /** + * Produce a JSONArray containing the values of the members of this JSONObject. + * @param names A JSONArray containing a list of key strings. This determines the sequence of the values in the result. + * @return A JSONArray of values. + * @throws JSONException If any of the values are non-finite numbers. + */ + public JSONArray toJSONArray (JSONArray names) throws JSONException { + if (names == null || names.length() == 0) { + return null; + } + JSONArray ja = new JSONArray(); + for (int i = 0; i < names.length(); i += 1) { + ja.put(this.opt(names.getString(i))); + } + return ja; + } + + /** + * Make a JSON text of this JSONObject. For compactness, no whitespace is added. If this would not result in a syntactically + * correct JSON text, then null will be returned instead. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @return a printable, displayable, portable, transmittable representation of the object, beginning with { + *  (left brace) and ending with } (right brace). + */ + public String toString () { + try { + Iterator keys = keys(); + StringBuffer sb = new StringBuffer("{"); + + while (keys.hasNext()) { + if (sb.length() > 1) { + sb.append(','); + } + Object o = keys.next(); + sb.append(quote(o.toString())); + sb.append(':'); + sb.append(valueToString(this.map.get(o))); + } + sb.append('}'); + return sb.toString(); + } catch (Exception e) { + return null; + } + } + + /** + * Make a prettyprinted JSON text of this JSONObject. + *

+ * Warning: This method assumes that the data structure is acyclical. + * @param indentFactor The number of spaces to add to each level of indentation. + * @return a printable, displayable, portable, transmittable representation of the object, beginning with { + *  (left brace) and ending with } (right brace). + * @throws JSONException If the object contains an invalid number. + */ + public String toString (int indentFactor) throws JSONException { + return toString(indentFactor, 0); + } + + /** + * Make a prettyprinted JSON text of this JSONObject. + *

+ * Warning: This method assumes that the data structure is acyclical. + * @param indentFactor The number of spaces to add to each level of indentation. + * @param indent The indentation of the top level. + * @return a printable, displayable, transmittable representation of the object, beginning with { + *  (left brace) and ending with } (right brace). + * @throws JSONException If the object contains an invalid number. + */ + String toString (int indentFactor, int indent) throws JSONException { + int j; + int n = length(); + if (n == 0) { + return "{}"; + } + Iterator keys = sortedKeys(); + StringBuffer sb = new StringBuffer("{"); + int newindent = indent + indentFactor; + Object o; + if (n == 1) { + o = keys.next(); + sb.append(quote(o.toString())); + sb.append(": "); + sb.append(valueToString(this.map.get(o), indentFactor, indent)); + } else { + while (keys.hasNext()) { + o = keys.next(); + if (sb.length() > 1) { + sb.append(",\n"); + } else { + sb.append('\n'); + } + for (j = 0; j < newindent; j += 1) { + sb.append(' '); + } + sb.append(quote(o.toString())); + sb.append(": "); + sb.append(valueToString(this.map.get(o), indentFactor, newindent)); + } + if (sb.length() > 1) { + sb.append('\n'); + for (j = 0; j < indent; j += 1) { + sb.append(' '); + } + } + } + sb.append('}'); + return sb.toString(); + } + + /** + * Make a JSON text of an Object value. If the object has an value.toJSONString() method, then that method will be used to + * produce the JSON text. The method is required to produce a strictly conforming text. If the object does not contain a + * toJSONString method (which is the most common case), then a text will be produced by other means. If the value is an array + * or Collection, then a JSONArray will be made from it and its toJSONString method will be called. If the value is a MAP, then + * a JSONObject will be made from it and its toJSONString method will be called. Otherwise, the value's toString method will be + * called, and the result will be quoted. + * + *

+ * Warning: This method assumes that the data structure is acyclical. + * @param value The value to be serialized. + * @return a printable, displayable, transmittable representation of the object, beginning with { + *  (left brace) and ending with } (right brace). + * @throws JSONException If the value is or contains an invalid number. + */ + static String valueToString (Object value) throws JSONException { + if (value == null || value.equals(null)) { + return "null"; + } + if (value instanceof JSONString) { + Object o; + try { + o = ((JSONString)value).toJSONString(); + } catch (Exception e) { + throw new JSONException(e); + } + if (o instanceof String) { + return (String)o; + } + throw new JSONException("Bad value from toJSONString: " + o); + } + if (value instanceof Number) { + return numberToString((Number)value); + } + if (value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) { + return value.toString(); + } + if (value instanceof Map) { + return new JSONObject((Map)value).toString(); + } + if (value instanceof Collection) { + return new JSONArray((Collection)value).toString(); + } + if (value.getClass().isArray()) { + return new JSONArray(value).toString(); + } + return quote(value.toString()); + } + + /** + * Make a prettyprinted JSON text of an object value. + *

+ * Warning: This method assumes that the data structure is acyclical. + * @param value The value to be serialized. + * @param indentFactor The number of spaces to add to each level of indentation. + * @param indent The indentation of the top level. + * @return a printable, displayable, transmittable representation of the object, beginning with { + *  (left brace) and ending with } (right brace). + * @throws JSONException If the object contains an invalid number. + */ + static String valueToString (Object value, int indentFactor, int indent) throws JSONException { + if (value == null || value.equals(null)) { + return "null"; + } + try { + if (value instanceof JSONString) { + Object o = ((JSONString)value).toJSONString(); + if (o instanceof String) { + return (String)o; + } + } + } catch (Exception ignore) { + } + if (value instanceof Number) { + return numberToString((Number)value); + } + if (value instanceof Boolean) { + return value.toString(); + } + if (value instanceof JSONObject) { + return ((JSONObject)value).toString(indentFactor, indent); + } + if (value instanceof JSONArray) { + return ((JSONArray)value).toString(indentFactor, indent); + } + if (value instanceof Map) { + return new JSONObject((Map)value).toString(indentFactor, indent); + } + if (value instanceof Collection) { + return new JSONArray((Collection)value).toString(indentFactor, indent); + } + if (value.getClass().isArray()) { + return new JSONArray(value).toString(indentFactor, indent); + } + return quote(value.toString()); + } + + /** + * Wrap an object, if necessary. If the object is null, return the NULL object. If it is an array or collection, wrap it in a + * JSONArray. If it is a map, wrap it in a JSONObject. If it is a standard property (Double, String, et al) then it is already + * wrapped. Otherwise, if it comes from one of the java packages, turn it into a string. And if it doesn't, try to wrap it in a + * JSONObject. If the wrapping fails, then null is returned. + * + * @param object The object to wrap + * @return The wrapped value + */ + static Object wrap (Object object) { + try { + if (object == null) { + return NULL; + } + if (object instanceof JSONObject || object instanceof JSONArray || NULL.equals(object) || object instanceof JSONString + || object instanceof Byte || object instanceof Character || object instanceof Short || object instanceof Integer + || object instanceof Long || object instanceof Boolean || object instanceof Float || object instanceof Double + || object instanceof String) { + return object; + } + + if (object instanceof Collection) { + return new JSONArray((Collection)object); + } + if (object.getClass().isArray()) { + return new JSONArray(object); + } + if (object instanceof Map) { + return new JSONObject((Map)object); + } + Package objectPackage = object.getClass().getPackage(); + String objectPackageName = (objectPackage != null ? objectPackage.getName() : ""); + if (objectPackageName.startsWith("java.") || objectPackageName.startsWith("javax.") + || object.getClass().getClassLoader() == null) { + return object.toString(); + } + return new JSONObject(object); + } catch (Exception exception) { + return null; + } + } + + /** + * Write the contents of the JSONObject as JSON text to a writer. For compactness, no whitespace is added. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @return The writer. + * @throws JSONException + */ + public Writer write (Writer writer) throws JSONException { + try { + boolean b = false; + Iterator keys = keys(); + writer.write('{'); + + while (keys.hasNext()) { + if (b) { + writer.write(','); + } + Object k = keys.next(); + writer.write(quote(k.toString())); + writer.write(':'); + Object v = this.map.get(k); + if (v instanceof JSONObject) { + ((JSONObject)v).write(writer); + } else if (v instanceof JSONArray) { + ((JSONArray)v).write(writer); + } else { + writer.write(valueToString(v)); + } + b = true; + } + writer.write('}'); + return writer; + } catch (IOException exception) { + throw new JSONException(exception); + } + } +} diff --git a/gdx/src/com/badlogic/gdx/utils/json/JSONString.java b/gdx/src/com/badlogic/gdx/utils/json/JSONString.java index ca9558eb9..c5035f145 100644 --- a/gdx/src/com/badlogic/gdx/utils/json/JSONString.java +++ b/gdx/src/com/badlogic/gdx/utils/json/JSONString.java @@ -1,18 +1,17 @@ + package com.badlogic.gdx.utils.json; + /** - * The JSONString interface allows a toJSONString() - * method so that a class can change the behavior of - * JSONObject.toString(), JSONArray.toString(), - * and JSONWriter.value(Object). The - * toJSONString method will be used instead of the default behavior - * of using the Object's toString() method and quoting the result. + * The JSONString interface allows a toJSONString() method so that a class can change the behavior of + * JSONObject.toString(), JSONArray.toString(), and JSONWriter.value(Object). + * The toJSONString method will be used instead of the default behavior of using the Object's toString() + * method and quoting the result. */ public interface JSONString { /** - * The toJSONString method allows a class to produce its own JSON - * serialization. + * The toJSONString method allows a class to produce its own JSON serialization. * * @return A strictly syntactically correct JSON text. */ - public String toJSONString(); + public String toJSONString (); } diff --git a/gdx/src/com/badlogic/gdx/utils/json/JSONStringer.java b/gdx/src/com/badlogic/gdx/utils/json/JSONStringer.java index 8e8071ca7..3fe897d40 100644 --- a/gdx/src/com/badlogic/gdx/utils/json/JSONStringer.java +++ b/gdx/src/com/badlogic/gdx/utils/json/JSONStringer.java @@ -1,78 +1,68 @@ + package com.badlogic.gdx.utils.json; /* -Copyright (c) 2006 JSON.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -The Software shall be used for Good, not Evil. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ + * Copyright (c) 2006 JSON.org + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, + * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software + * is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * The Software shall be used for Good, not Evil. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR + * IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ import java.io.StringWriter; /** - * JSONStringer provides a quick and convenient way of producing JSON text. - * The texts produced strictly conform to JSON syntax rules. No whitespace is - * added, so the results are ready for transmission or storage. Each instance of - * JSONStringer can produce one JSON text. + * JSONStringer provides a quick and convenient way of producing JSON text. The texts produced strictly conform to JSON syntax + * rules. No whitespace is added, so the results are ready for transmission or storage. Each instance of JSONStringer can produce + * one JSON text. *

- * A JSONStringer instance provides a value method for appending - * values to the - * text, and a key - * method for adding keys before values in objects. There are array - * and endArray methods that make and bound array values, and - * object and endObject methods which make and bound - * object values. All of these methods return the JSONWriter instance, - * permitting cascade style. For example,

- * myString = new JSONStringer()
- *     .object()
- *         .key("JSON")
- *         .value("Hello, World!")
- *     .endObject()
- *     .toString();
which produces the string
- * {"JSON":"Hello, World!"}
+ * A JSONStringer instance provides a value method for appending values to the text, and a key method + * for adding keys before values in objects. There are array and endArray methods that make and bound + * array values, and object and endObject methods which make and bound object values. All of these + * methods return the JSONWriter instance, permitting cascade style. For example, + * + *
+ * myString = new JSONStringer().object().key("JSON").value("Hello, World!").endObject().toString();
+ * 
+ * + * which produces the string + * + *
+ * {"JSON":"Hello, World!"}
+ * 
*

- * The first method called must be array or object. - * There are no methods for adding commas or colons. JSONStringer adds them for - * you. Objects and arrays can be nested up to 20 levels deep. + * The first method called must be array or object. There are no methods for adding commas or colons. + * JSONStringer adds them for you. Objects and arrays can be nested up to 20 levels deep. *

* This can sometimes be easier than using a JSONObject to build a string. * @author JSON.org * @version 2008-09-18 */ public class JSONStringer extends JSONWriter { - /** - * Make a fresh JSONStringer. It can be used to build one JSON text. - */ - public JSONStringer() { - super(new StringWriter()); - } + /** + * Make a fresh JSONStringer. It can be used to build one JSON text. + */ + public JSONStringer () { + super(new StringWriter()); + } - /** - * Return the JSON text. This method is used to obtain the product of the - * JSONStringer instance. It will return null if there was a - * problem in the construction of the JSON text (such as the calls to - * array were not properly balanced with calls to - * endArray). - * @return The JSON text. - */ - public String toString() { - return this.mode == 'd' ? this.writer.toString() : null; - } + /** + * Return the JSON text. This method is used to obtain the product of the JSONStringer instance. It will return + * null if there was a problem in the construction of the JSON text (such as the calls to array were + * not properly balanced with calls to endArray). + * @return The JSON text. + */ + public String toString () { + return this.mode == 'd' ? this.writer.toString() : null; + } } diff --git a/gdx/src/com/badlogic/gdx/utils/json/JSONTokener.java b/gdx/src/com/badlogic/gdx/utils/json/JSONTokener.java index 5b5f0d915..c4b365bac 100644 --- a/gdx/src/com/badlogic/gdx/utils/json/JSONTokener.java +++ b/gdx/src/com/badlogic/gdx/utils/json/JSONTokener.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.utils.json; import java.io.BufferedReader; @@ -6,430 +7,390 @@ import java.io.Reader; import java.io.StringReader; /* -Copyright (c) 2002 JSON.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -The Software shall be used for Good, not Evil. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ + * Copyright (c) 2002 JSON.org + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, + * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software + * is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * The Software shall be used for Good, not Evil. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR + * IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ /** - * A JSONTokener takes a source string and extracts characters and tokens from - * it. It is used by the JSONObject and JSONArray constructors to parse - * JSON source strings. + * A JSONTokener takes a source string and extracts characters and tokens from it. It is used by the JSONObject and JSONArray + * constructors to parse JSON source strings. * @author JSON.org * @version 2010-02-02 */ public class JSONTokener { - private int character; + private int character; private boolean eof; - private int index; - private int line; - private char previous; - private Reader reader; - private boolean usePrevious; - - - /** - * Construct a JSONTokener from a reader. - * - * @param reader A reader. - */ - public JSONTokener(Reader reader) { - this.reader = reader.markSupported() ? - reader : new BufferedReader(reader); - this.eof = false; - this.usePrevious = false; - this.previous = 0; - this.index = 0; - this.character = 1; - this.line = 1; - } - - - /** - * Construct a JSONTokener from a string. - * - * @param s A source string. - */ - public JSONTokener(String s) { - this(new StringReader(s)); - } - - - /** - * Back up one character. This provides a sort of lookahead capability, - * so that you can test for a digit or letter before attempting to parse - * the next number or identifier. - */ - public void back() throws JSONException { - if (usePrevious || index <= 0) { - throw new JSONException("Stepping back two steps is not supported"); - } - this.index -= 1; - this.character -= 1; - this.usePrevious = true; - this.eof = false; - } - - - /** - * Get the hex value of a character (base16). - * @param c A character between '0' and '9' or between 'A' and 'F' or - * between 'a' and 'f'. - * @return An int between 0 and 15, or -1 if c was not a hex digit. - */ - public static int dehexchar(char c) { - if (c >= '0' && c <= '9') { - return c - '0'; - } - if (c >= 'A' && c <= 'F') { - return c - ('A' - 10); - } - if (c >= 'a' && c <= 'f') { - return c - ('a' - 10); - } - return -1; - } - - public boolean end() { - return eof && !usePrevious; - } - - - /** - * Determine if the source string still contains characters that next() - * can consume. - * @return true if not yet at the end of the source. - */ - public boolean more() throws JSONException { - next(); - if (end()) { - return false; - } - back(); - return true; - } - - - /** - * Get the next character in the source string. - * - * @return The next character, or 0 if past the end of the source string. - */ - public char next() throws JSONException { - int c; - if (this.usePrevious) { - this.usePrevious = false; - c = this.previous; - } else { - try { - c = this.reader.read(); - } catch (IOException exception) { - throw new JSONException(exception); - } - - if (c <= 0) { // End of stream - this.eof = true; - c = 0; - } - } - this.index += 1; - if (this.previous == '\r') { - this.line += 1; - this.character = c == '\n' ? 0 : 1; - } else if (c == '\n') { - this.line += 1; - this.character = 0; - } else { - this.character += 1; - } - this.previous = (char) c; - return this.previous; - } - - - /** - * Consume the next character, and check that it matches a specified - * character. - * @param c The character to match. - * @return The character. - * @throws JSONException if the character does not match. - */ - public char next(char c) throws JSONException { - char n = next(); - if (n != c) { - throw syntaxError("Expected '" + c + "' and instead saw '" + - n + "'"); - } - return n; - } - - - /** - * Get the next n characters. - * - * @param n The number of characters to take. - * @return A string of n characters. - * @throws JSONException - * Substring bounds error if there are not - * n characters remaining in the source string. - */ - public String next(int n) throws JSONException { - if (n == 0) { - return ""; - } - - char[] buffer = new char[n]; - int pos = 0; - - while (pos < n) { - buffer[pos] = next(); - if (end()) { - throw syntaxError("Substring bounds error"); - } - pos += 1; - } - return new String(buffer); - } - - - /** - * Get the next char in the string, skipping whitespace. - * @throws JSONException - * @return A character, or 0 if there are no more characters. - */ - public char nextClean() throws JSONException { - for (;;) { - char c = next(); - if (c == 0 || c > ' ') { - return c; - } - } - } - - - /** - * Return the characters up to the next close quote character. - * Backslash processing is done. The formal JSON format does not - * allow strings in single quotes, but an implementation is allowed to - * accept them. - * @param quote The quoting character, either - * " (double quote) or - * ' (single quote). - * @return A String. - * @throws JSONException Unterminated string. - */ - public String nextString(char quote) throws JSONException { - char c; - StringBuffer sb = new StringBuffer(); - for (;;) { - c = next(); - switch (c) { - case 0: - case '\n': - case '\r': - throw syntaxError("Unterminated string"); - case '\\': - c = next(); - switch (c) { - case 'b': - sb.append('\b'); - break; - case 't': - sb.append('\t'); - break; - case 'n': - sb.append('\n'); - break; - case 'f': - sb.append('\f'); - break; - case 'r': - sb.append('\r'); - break; - case 'u': - sb.append((char)Integer.parseInt(next(4), 16)); - break; - case '"': - case '\'': - case '\\': - case '/': - sb.append(c); - break; - default: - throw syntaxError("Illegal escape."); - } - break; - default: - if (c == quote) { - return sb.toString(); - } - sb.append(c); - } - } - } - - - /** - * Get the text up but not including the specified character or the - * end of line, whichever comes first. - * @param d A delimiter character. - * @return A string. - */ - public String nextTo(char d) throws JSONException { - StringBuffer sb = new StringBuffer(); - for (;;) { - char c = next(); - if (c == d || c == 0 || c == '\n' || c == '\r') { - if (c != 0) { - back(); - } - return sb.toString().trim(); - } - sb.append(c); - } - } - - - /** - * Get the text up but not including one of the specified delimiter - * characters or the end of line, whichever comes first. - * @param delimiters A set of delimiter characters. - * @return A string, trimmed. - */ - public String nextTo(String delimiters) throws JSONException { - char c; - StringBuffer sb = new StringBuffer(); - for (;;) { - c = next(); - if (delimiters.indexOf(c) >= 0 || c == 0 || - c == '\n' || c == '\r') { - if (c != 0) { - back(); - } - return sb.toString().trim(); - } - sb.append(c); - } - } - - - /** - * Get the next value. The value can be a Boolean, Double, Integer, - * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. - * @throws JSONException If syntax error. - * - * @return An object. - */ - public Object nextValue() throws JSONException { - char c = nextClean(); - String s; - - switch (c) { - case '"': - case '\'': - return nextString(c); - case '{': - back(); - return new JSONObject(this); - case '[': - case '(': - back(); - return new JSONArray(this); - } - - /* - * Handle unquoted text. This could be the values true, false, or - * null, or it can be a number. An implementation (such as this one) - * is allowed to also accept non-standard forms. - * - * Accumulate characters until we reach the end of the text or a - * formatting character. - */ - - StringBuffer sb = new StringBuffer(); - while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { - sb.append(c); - c = next(); - } - back(); - - s = sb.toString().trim(); - if (s.equals("")) { - throw syntaxError("Missing value"); - } - return JSONObject.stringToValue(s); - } - - - /** - * Skip characters until the next character is the requested character. - * If the requested character is not found, no characters are skipped. - * @param to A character to skip to. - * @return The requested character, or zero if the requested character - * is not found. - */ - public char skipTo(char to) throws JSONException { - char c; - try { - int startIndex = this.index; - int startCharacter = this.character; - int startLine = this.line; - reader.mark(Integer.MAX_VALUE); - do { - c = next(); - if (c == 0) { - reader.reset(); - this.index = startIndex; - this.character = startCharacter; - this.line = startLine; - return c; - } - } while (c != to); - } catch (IOException exc) { - throw new JSONException(exc); - } - - back(); - return c; - } - - - /** - * Make a JSONException to signal a syntax error. - * - * @param message The error message. - * @return A JSONException object, suitable for throwing - */ - public JSONException syntaxError(String message) { - return new JSONException(message + toString()); - } - - - /** - * Make a printable string of this JSONTokener. - * - * @return " at {index} [character {character} line {line}]" - */ - public String toString() { - return " at " + index + " [character " + this.character + " line " + this.line + "]"; - } -} \ No newline at end of file + private int index; + private int line; + private char previous; + private Reader reader; + private boolean usePrevious; + + /** + * Construct a JSONTokener from a reader. + * + * @param reader A reader. + */ + public JSONTokener (Reader reader) { + this.reader = reader.markSupported() ? reader : new BufferedReader(reader); + this.eof = false; + this.usePrevious = false; + this.previous = 0; + this.index = 0; + this.character = 1; + this.line = 1; + } + + /** + * Construct a JSONTokener from a string. + * + * @param s A source string. + */ + public JSONTokener (String s) { + this(new StringReader(s)); + } + + /** + * Back up one character. This provides a sort of lookahead capability, so that you can test for a digit or letter before + * attempting to parse the next number or identifier. + */ + public void back () throws JSONException { + if (usePrevious || index <= 0) { + throw new JSONException("Stepping back two steps is not supported"); + } + this.index -= 1; + this.character -= 1; + this.usePrevious = true; + this.eof = false; + } + + /** + * Get the hex value of a character (base16). + * @param c A character between '0' and '9' or between 'A' and 'F' or between 'a' and 'f'. + * @return An int between 0 and 15, or -1 if c was not a hex digit. + */ + public static int dehexchar (char c) { + if (c >= '0' && c <= '9') { + return c - '0'; + } + if (c >= 'A' && c <= 'F') { + return c - ('A' - 10); + } + if (c >= 'a' && c <= 'f') { + return c - ('a' - 10); + } + return -1; + } + + public boolean end () { + return eof && !usePrevious; + } + + /** + * Determine if the source string still contains characters that next() can consume. + * @return true if not yet at the end of the source. + */ + public boolean more () throws JSONException { + next(); + if (end()) { + return false; + } + back(); + return true; + } + + /** + * Get the next character in the source string. + * + * @return The next character, or 0 if past the end of the source string. + */ + public char next () throws JSONException { + int c; + if (this.usePrevious) { + this.usePrevious = false; + c = this.previous; + } else { + try { + c = this.reader.read(); + } catch (IOException exception) { + throw new JSONException(exception); + } + + if (c <= 0) { // End of stream + this.eof = true; + c = 0; + } + } + this.index += 1; + if (this.previous == '\r') { + this.line += 1; + this.character = c == '\n' ? 0 : 1; + } else if (c == '\n') { + this.line += 1; + this.character = 0; + } else { + this.character += 1; + } + this.previous = (char)c; + return this.previous; + } + + /** + * Consume the next character, and check that it matches a specified character. + * @param c The character to match. + * @return The character. + * @throws JSONException if the character does not match. + */ + public char next (char c) throws JSONException { + char n = next(); + if (n != c) { + throw syntaxError("Expected '" + c + "' and instead saw '" + n + "'"); + } + return n; + } + + /** + * Get the next n characters. + * + * @param n The number of characters to take. + * @return A string of n characters. + * @throws JSONException Substring bounds error if there are not n characters remaining in the source string. + */ + public String next (int n) throws JSONException { + if (n == 0) { + return ""; + } + + char[] buffer = new char[n]; + int pos = 0; + + while (pos < n) { + buffer[pos] = next(); + if (end()) { + throw syntaxError("Substring bounds error"); + } + pos += 1; + } + return new String(buffer); + } + + /** + * Get the next char in the string, skipping whitespace. + * @throws JSONException + * @return A character, or 0 if there are no more characters. + */ + public char nextClean () throws JSONException { + for (;;) { + char c = next(); + if (c == 0 || c > ' ') { + return c; + } + } + } + + /** + * Return the characters up to the next close quote character. Backslash processing is done. The formal JSON format does not + * allow strings in single quotes, but an implementation is allowed to accept them. + * @param quote The quoting character, either " (double quote) or ' + *  (single quote). + * @return A String. + * @throws JSONException Unterminated string. + */ + public String nextString (char quote) throws JSONException { + char c; + StringBuffer sb = new StringBuffer(); + for (;;) { + c = next(); + switch (c) { + case 0: + case '\n': + case '\r': + throw syntaxError("Unterminated string"); + case '\\': + c = next(); + switch (c) { + case 'b': + sb.append('\b'); + break; + case 't': + sb.append('\t'); + break; + case 'n': + sb.append('\n'); + break; + case 'f': + sb.append('\f'); + break; + case 'r': + sb.append('\r'); + break; + case 'u': + sb.append((char)Integer.parseInt(next(4), 16)); + break; + case '"': + case '\'': + case '\\': + case '/': + sb.append(c); + break; + default: + throw syntaxError("Illegal escape."); + } + break; + default: + if (c == quote) { + return sb.toString(); + } + sb.append(c); + } + } + } + + /** + * Get the text up but not including the specified character or the end of line, whichever comes first. + * @param d A delimiter character. + * @return A string. + */ + public String nextTo (char d) throws JSONException { + StringBuffer sb = new StringBuffer(); + for (;;) { + char c = next(); + if (c == d || c == 0 || c == '\n' || c == '\r') { + if (c != 0) { + back(); + } + return sb.toString().trim(); + } + sb.append(c); + } + } + + /** + * Get the text up but not including one of the specified delimiter characters or the end of line, whichever comes first. + * @param delimiters A set of delimiter characters. + * @return A string, trimmed. + */ + public String nextTo (String delimiters) throws JSONException { + char c; + StringBuffer sb = new StringBuffer(); + for (;;) { + c = next(); + if (delimiters.indexOf(c) >= 0 || c == 0 || c == '\n' || c == '\r') { + if (c != 0) { + back(); + } + return sb.toString().trim(); + } + sb.append(c); + } + } + + /** + * Get the next value. The value can be a Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the + * JSONObject.NULL object. + * @throws JSONException If syntax error. + * + * @return An object. + */ + public Object nextValue () throws JSONException { + char c = nextClean(); + String s; + + switch (c) { + case '"': + case '\'': + return nextString(c); + case '{': + back(); + return new JSONObject(this); + case '[': + case '(': + back(); + return new JSONArray(this); + } + + /* + * Handle unquoted text. This could be the values true, false, or null, or it can be a number. An implementation (such as + * this one) is allowed to also accept non-standard forms. + * + * Accumulate characters until we reach the end of the text or a formatting character. + */ + + StringBuffer sb = new StringBuffer(); + while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { + sb.append(c); + c = next(); + } + back(); + + s = sb.toString().trim(); + if (s.equals("")) { + throw syntaxError("Missing value"); + } + return JSONObject.stringToValue(s); + } + + /** + * Skip characters until the next character is the requested character. If the requested character is not found, no characters + * are skipped. + * @param to A character to skip to. + * @return The requested character, or zero if the requested character is not found. + */ + public char skipTo (char to) throws JSONException { + char c; + try { + int startIndex = this.index; + int startCharacter = this.character; + int startLine = this.line; + reader.mark(Integer.MAX_VALUE); + do { + c = next(); + if (c == 0) { + reader.reset(); + this.index = startIndex; + this.character = startCharacter; + this.line = startLine; + return c; + } + } while (c != to); + } catch (IOException exc) { + throw new JSONException(exc); + } + + back(); + return c; + } + + /** + * Make a JSONException to signal a syntax error. + * + * @param message The error message. + * @return A JSONException object, suitable for throwing + */ + public JSONException syntaxError (String message) { + return new JSONException(message + toString()); + } + + /** + * Make a printable string of this JSONTokener. + * + * @return " at {index} [character {character} line {line}]" + */ + public String toString () { + return " at " + index + " [character " + this.character + " line " + this.line + "]"; + } +} diff --git a/gdx/src/com/badlogic/gdx/utils/json/JSONWriter.java b/gdx/src/com/badlogic/gdx/utils/json/JSONWriter.java index 38484f51e..a48e638f6 100644 --- a/gdx/src/com/badlogic/gdx/utils/json/JSONWriter.java +++ b/gdx/src/com/badlogic/gdx/utils/json/JSONWriter.java @@ -1,323 +1,295 @@ + package com.badlogic.gdx.utils.json; import java.io.IOException; import java.io.Writer; /* -Copyright (c) 2006 JSON.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -The Software shall be used for Good, not Evil. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ + * Copyright (c) 2006 JSON.org + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, + * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software + * is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * The Software shall be used for Good, not Evil. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR + * IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ /** - * JSONWriter provides a quick and convenient way of producing JSON text. - * The texts produced strictly conform to JSON syntax rules. No whitespace is - * added, so the results are ready for transmission or storage. Each instance of - * JSONWriter can produce one JSON text. + * JSONWriter provides a quick and convenient way of producing JSON text. The texts produced strictly conform to JSON syntax + * rules. No whitespace is added, so the results are ready for transmission or storage. Each instance of JSONWriter can produce + * one JSON text. *

- * A JSONWriter instance provides a value method for appending - * values to the - * text, and a key - * method for adding keys before values in objects. There are array - * and endArray methods that make and bound array values, and - * object and endObject methods which make and bound - * object values. All of these methods return the JSONWriter instance, - * permitting a cascade style. For example,

- * new JSONWriter(myWriter)
- *     .object()
- *         .key("JSON")
- *         .value("Hello, World!")
- *     .endObject();
which writes
- * {"JSON":"Hello, World!"}
+ * A JSONWriter instance provides a value method for appending values to the text, and a key method for + * adding keys before values in objects. There are array and endArray methods that make and bound array + * values, and object and endObject methods which make and bound object values. All of these methods + * return the JSONWriter instance, permitting a cascade style. For example, + * + *
+ * new JSONWriter(myWriter).object().key("JSON").value("Hello, World!").endObject();
+ * 
+ * + * which writes + * + *
+ * {"JSON":"Hello, World!"}
+ * 
*

- * The first method called must be array or object. - * There are no methods for adding commas or colons. JSONWriter adds them for - * you. Objects and arrays can be nested up to 20 levels deep. + * The first method called must be array or object. There are no methods for adding commas or colons. + * JSONWriter adds them for you. Objects and arrays can be nested up to 20 levels deep. *

* This can sometimes be easier than using a JSONObject to build a string. * @author JSON.org * @version 2010-03-11 */ public class JSONWriter { - private static final int maxdepth = 20; - - /** - * The comma flag determines if a comma should be output before the next - * value. - */ - private boolean comma; - - /** - * The current mode. Values: - * 'a' (array), - * 'd' (done), - * 'i' (initial), - * 'k' (key), - * 'o' (object). - */ - protected char mode; - - /** - * The object/array stack. - */ - private JSONObject stack[]; - - /** - * The stack top index. A value of 0 indicates that the stack is empty. - */ - private int top; + private static final int maxdepth = 20; - /** - * The writer that will receive the output. - */ - protected Writer writer; + /** + * The comma flag determines if a comma should be output before the next value. + */ + private boolean comma; - /** - * Make a fresh JSONWriter. It can be used to build one JSON text. - */ - public JSONWriter(Writer w) { - this.comma = false; - this.mode = 'i'; - this.stack = new JSONObject[maxdepth]; - this.top = 0; - this.writer = w; - } + /** + * The current mode. Values: 'a' (array), 'd' (done), 'i' (initial), 'k' (key), 'o' (object). + */ + protected char mode; - /** - * Append a value. - * @param s A string value. - * @return this - * @throws JSONException If the value is out of sequence. - */ - private JSONWriter append(String s) throws JSONException { - if (s == null) { - throw new JSONException("Null pointer"); - } - if (this.mode == 'o' || this.mode == 'a') { - try { - if (this.comma && this.mode == 'a') { - this.writer.write(','); - } - this.writer.write(s); - } catch (IOException e) { - throw new JSONException(e); - } - if (this.mode == 'o') { - this.mode = 'k'; - } - this.comma = true; - return this; - } - throw new JSONException("Value out of sequence."); - } + /** + * The object/array stack. + */ + private JSONObject stack[]; - /** - * Begin appending a new array. All values until the balancing - * endArray will be appended to this array. The - * endArray method must be called to mark the array's end. - * @return this - * @throws JSONException If the nesting is too deep, or if the object is - * started in the wrong place (for example as a key or after the end of the - * outermost array or object). - */ - public JSONWriter array() throws JSONException { - if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { - this.push(null); - this.append("["); - this.comma = false; - return this; - } - throw new JSONException("Misplaced array."); - } + /** + * The stack top index. A value of 0 indicates that the stack is empty. + */ + private int top; - /** - * End something. - * @param m Mode - * @param c Closing character - * @return this - * @throws JSONException If unbalanced. - */ - private JSONWriter end(char m, char c) throws JSONException { - if (this.mode != m) { - throw new JSONException(m == 'a' ? "Misplaced endArray." : - "Misplaced endObject."); - } - this.pop(m); - try { - this.writer.write(c); - } catch (IOException e) { - throw new JSONException(e); - } - this.comma = true; - return this; - } + /** + * The writer that will receive the output. + */ + protected Writer writer; - /** - * End an array. This method most be called to balance calls to - * array. - * @return this - * @throws JSONException If incorrectly nested. - */ - public JSONWriter endArray() throws JSONException { - return this.end('a', ']'); - } + /** + * Make a fresh JSONWriter. It can be used to build one JSON text. + */ + public JSONWriter (Writer w) { + this.comma = false; + this.mode = 'i'; + this.stack = new JSONObject[maxdepth]; + this.top = 0; + this.writer = w; + } - /** - * End an object. This method most be called to balance calls to - * object. - * @return this - * @throws JSONException If incorrectly nested. - */ - public JSONWriter endObject() throws JSONException { - return this.end('k', '}'); - } + /** + * Append a value. + * @param s A string value. + * @return this + * @throws JSONException If the value is out of sequence. + */ + private JSONWriter append (String s) throws JSONException { + if (s == null) { + throw new JSONException("Null pointer"); + } + if (this.mode == 'o' || this.mode == 'a') { + try { + if (this.comma && this.mode == 'a') { + this.writer.write(','); + } + this.writer.write(s); + } catch (IOException e) { + throw new JSONException(e); + } + if (this.mode == 'o') { + this.mode = 'k'; + } + this.comma = true; + return this; + } + throw new JSONException("Value out of sequence."); + } - /** - * Append a key. The key will be associated with the next value. In an - * object, every value must be preceded by a key. - * @param s A key string. - * @return this - * @throws JSONException If the key is out of place. For example, keys - * do not belong in arrays or if the key is null. - */ - public JSONWriter key(String s) throws JSONException { - if (s == null) { - throw new JSONException("Null key."); - } - if (this.mode == 'k') { - try { - stack[top - 1].putOnce(s, Boolean.TRUE); - if (this.comma) { - this.writer.write(','); - } - this.writer.write(JSONObject.quote(s)); - this.writer.write(':'); - this.comma = false; - this.mode = 'o'; - return this; - } catch (IOException e) { - throw new JSONException(e); - } - } - throw new JSONException("Misplaced key."); - } + /** + * Begin appending a new array. All values until the balancing endArray will be appended to this array. The + * endArray method must be called to mark the array's end. + * @return this + * @throws JSONException If the nesting is too deep, or if the object is started in the wrong place (for example as a key or + * after the end of the outermost array or object). + */ + public JSONWriter array () throws JSONException { + if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { + this.push(null); + this.append("["); + this.comma = false; + return this; + } + throw new JSONException("Misplaced array."); + } + /** + * End something. + * @param m Mode + * @param c Closing character + * @return this + * @throws JSONException If unbalanced. + */ + private JSONWriter end (char m, char c) throws JSONException { + if (this.mode != m) { + throw new JSONException(m == 'a' ? "Misplaced endArray." : "Misplaced endObject."); + } + this.pop(m); + try { + this.writer.write(c); + } catch (IOException e) { + throw new JSONException(e); + } + this.comma = true; + return this; + } - /** - * Begin appending a new object. All keys and values until the balancing - * endObject will be appended to this object. The - * endObject method must be called to mark the object's end. - * @return this - * @throws JSONException If the nesting is too deep, or if the object is - * started in the wrong place (for example as a key or after the end of the - * outermost array or object). - */ - public JSONWriter object() throws JSONException { - if (this.mode == 'i') { - this.mode = 'o'; - } - if (this.mode == 'o' || this.mode == 'a') { - this.append("{"); - this.push(new JSONObject()); - this.comma = false; - return this; - } - throw new JSONException("Misplaced object."); + /** + * End an array. This method most be called to balance calls to array. + * @return this + * @throws JSONException If incorrectly nested. + */ + public JSONWriter endArray () throws JSONException { + return this.end('a', ']'); + } - } + /** + * End an object. This method most be called to balance calls to object. + * @return this + * @throws JSONException If incorrectly nested. + */ + public JSONWriter endObject () throws JSONException { + return this.end('k', '}'); + } + /** + * Append a key. The key will be associated with the next value. In an object, every value must be preceded by a key. + * @param s A key string. + * @return this + * @throws JSONException If the key is out of place. For example, keys do not belong in arrays or if the key is null. + */ + public JSONWriter key (String s) throws JSONException { + if (s == null) { + throw new JSONException("Null key."); + } + if (this.mode == 'k') { + try { + stack[top - 1].putOnce(s, Boolean.TRUE); + if (this.comma) { + this.writer.write(','); + } + this.writer.write(JSONObject.quote(s)); + this.writer.write(':'); + this.comma = false; + this.mode = 'o'; + return this; + } catch (IOException e) { + throw new JSONException(e); + } + } + throw new JSONException("Misplaced key."); + } - /** - * Pop an array or object scope. - * @param c The scope to close. - * @throws JSONException If nesting is wrong. - */ - private void pop(char c) throws JSONException { - if (this.top <= 0) { - throw new JSONException("Nesting error."); - } - char m = this.stack[this.top - 1] == null ? 'a' : 'k'; - if (m != c) { - throw new JSONException("Nesting error."); - } - this.top -= 1; - this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k'; - } + /** + * Begin appending a new object. All keys and values until the balancing endObject will be appended to this + * object. The endObject method must be called to mark the object's end. + * @return this + * @throws JSONException If the nesting is too deep, or if the object is started in the wrong place (for example as a key or + * after the end of the outermost array or object). + */ + public JSONWriter object () throws JSONException { + if (this.mode == 'i') { + this.mode = 'o'; + } + if (this.mode == 'o' || this.mode == 'a') { + this.append("{"); + this.push(new JSONObject()); + this.comma = false; + return this; + } + throw new JSONException("Misplaced object."); - /** - * Push an array or object scope. - * @param c The scope to open. - * @throws JSONException If nesting is too deep. - */ - private void push(JSONObject jo) throws JSONException { - if (this.top >= maxdepth) { - throw new JSONException("Nesting too deep."); - } - this.stack[this.top] = jo; - this.mode = jo == null ? 'a' : 'k'; - this.top += 1; - } + } + /** + * Pop an array or object scope. + * @param c The scope to close. + * @throws JSONException If nesting is wrong. + */ + private void pop (char c) throws JSONException { + if (this.top <= 0) { + throw new JSONException("Nesting error."); + } + char m = this.stack[this.top - 1] == null ? 'a' : 'k'; + if (m != c) { + throw new JSONException("Nesting error."); + } + this.top -= 1; + this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k'; + } - /** - * Append either the value true or the value - * false. - * @param b A boolean. - * @return this - * @throws JSONException - */ - public JSONWriter value(boolean b) throws JSONException { - return this.append(b ? "true" : "false"); - } + /** + * Push an array or object scope. + * @param c The scope to open. + * @throws JSONException If nesting is too deep. + */ + private void push (JSONObject jo) throws JSONException { + if (this.top >= maxdepth) { + throw new JSONException("Nesting too deep."); + } + this.stack[this.top] = jo; + this.mode = jo == null ? 'a' : 'k'; + this.top += 1; + } - /** - * Append a double value. - * @param d A double. - * @return this - * @throws JSONException If the number is not finite. - */ - public JSONWriter value(double d) throws JSONException { - return this.value(new Double(d)); - } + /** + * Append either the value true or the value false. + * @param b A boolean. + * @return this + * @throws JSONException + */ + public JSONWriter value (boolean b) throws JSONException { + return this.append(b ? "true" : "false"); + } - /** - * Append a long value. - * @param l A long. - * @return this - * @throws JSONException - */ - public JSONWriter value(long l) throws JSONException { - return this.append(Long.toString(l)); - } + /** + * Append a double value. + * @param d A double. + * @return this + * @throws JSONException If the number is not finite. + */ + public JSONWriter value (double d) throws JSONException { + return this.value(new Double(d)); + } + /** + * Append a long value. + * @param l A long. + * @return this + * @throws JSONException + */ + public JSONWriter value (long l) throws JSONException { + return this.append(Long.toString(l)); + } - /** - * Append an object value. - * @param o The object to append. It can be null, or a Boolean, Number, - * String, JSONObject, or JSONArray, or an object with a toJSONString() - * method. - * @return this - * @throws JSONException If the value is out of sequence. - */ - public JSONWriter value(Object o) throws JSONException { - return this.append(JSONObject.valueToString(o)); - } + /** + * Append an object value. + * @param o The object to append. It can be null, or a Boolean, Number, String, JSONObject, or JSONArray, or an object with a + * toJSONString() method. + * @return this + * @throws JSONException If the value is out of sequence. + */ + public JSONWriter value (Object o) throws JSONException { + return this.append(JSONObject.valueToString(o)); + } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/AlphaTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/AlphaTest.java index 0691e77fb..3ccc88d6d 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/AlphaTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/AlphaTest.java @@ -1,15 +1,14 @@ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class AlphaTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( false ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.AlphaTest() ); +public class AlphaTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(false); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.AlphaTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/AudioDeviceTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/AudioDeviceTest.java index 32ba706ae..b1ddf641f 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/AudioDeviceTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/AudioDeviceTest.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class AudioDeviceTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( false ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.AudioDeviceTest() ); +public class AudioDeviceTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(false); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.AudioDeviceTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/AudioRecorderTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/AudioRecorderTest.java index b4b29b1fa..893ad6332 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/AudioRecorderTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/AudioRecorderTest.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class AudioRecorderTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( false ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.AudioRecorderTest() ); +public class AudioRecorderTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(false); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.AudioRecorderTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/BitmapFontTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/BitmapFontTest.java index b78f9a678..151daff95 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/BitmapFontTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/BitmapFontTest.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class BitmapFontTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( false ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.BitmapFontTest() ); +public class BitmapFontTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(false); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.BitmapFontTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/Box2DTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/Box2DTest.java index 9ae72a8b9..eb0c35bc6 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/Box2DTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/Box2DTest.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class Box2DTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); +public class Box2DTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); initialize(false); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.Box2DTest() ); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.Box2DTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/BufferUtilsTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/BufferUtilsTest.java index cdc64ea8f..5abd03f76 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/BufferUtilsTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/BufferUtilsTest.java @@ -1,29 +1,27 @@ + package com.badlogic.gdx; import java.nio.ByteBuffer; import java.nio.ByteOrder; -import com.badlogic.gdx.utils.BufferUtils; - import android.app.Activity; import android.os.Bundle; -public class BufferUtilsTest extends Activity -{ - static - { - System.loadLibrary( "gdx" ); +import com.badlogic.gdx.utils.BufferUtils; + +public class BufferUtilsTest extends Activity { + static { + System.loadLibrary("gdx"); } - - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - - ByteBuffer buffer = ByteBuffer.allocateDirect( 6 * 5000 * (2 + 4 + 2) ); + + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + + ByteBuffer buffer = ByteBuffer.allocateDirect(6 * 5000 * (2 + 4 + 2)); buffer.order(ByteOrder.nativeOrder()); float[] test = new float[4000]; - - BufferUtils.copy( test, buffer, 4000, 0 ); - + + BufferUtils.copy(test, buffer, 4000, 0); + } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/FillrateTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/FillrateTest.java index bf7546e14..1686f30d6 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/FillrateTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/FillrateTest.java @@ -1,16 +1,15 @@ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class FillrateTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( false ); - - getGraphics().setRenderListener( new com.badlogic.gdx.tests.FillrateTest() ); +public class FillrateTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(false); + + getGraphics().setRenderListener(new com.badlogic.gdx.tests.FillrateTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/FixedPointMeshRendererTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/FixedPointMeshRendererTest.java index c55946538..cf6138a94 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/FixedPointMeshRendererTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/FixedPointMeshRendererTest.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class FixedPointMeshRendererTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( false ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.FixedPointMeshTest() ); +public class FixedPointMeshRendererTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(false); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.FixedPointMeshTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/FixedPointTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/FixedPointTest.java index ac56a994d..eff8c4505 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/FixedPointTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/FixedPointTest.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class FixedPointTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( false ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.FixedPointTest() ); +public class FixedPointTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(false); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.FixedPointTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/FloatTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/FloatTest.java index 4b37c25f3..9313aa2ec 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/FloatTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/FloatTest.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class FloatTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { +public class FloatTest extends AndroidApplication { + public void onCreate (Bundle bundle) { super.onCreate(bundle); - initialize( false ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.FloatTest() ); + initialize(false); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.FloatTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/FrameBufferTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/FrameBufferTest.java index 16d2cfd42..81b45e88d 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/FrameBufferTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/FrameBufferTest.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class FrameBufferTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( true ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.FrameBufferTest( ) ); +public class FrameBufferTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(true); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.FrameBufferTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/GDXTester.java b/tests/gdx-tests-android/src/com/badlogic/gdx/GDXTester.java index 300758f44..fc9b7453a 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/GDXTester.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/GDXTester.java @@ -1,21 +1,17 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ -package com.badlogic.gdx; -import com.badlogic.gdx.box2d.TestCollection; +package com.badlogic.gdx; import android.app.ListActivity; import android.content.Intent; @@ -24,111 +20,70 @@ import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; -public class GDXTester extends ListActivity -{ - String[] items = new String[]{ "Life Cycle Test", "Simple Test", "Vertex Array Test", "Vertex Buffer Object Test", "MeshRenderer Test", - "Fixed Point MeshRenderer Test", "Managed Test", "Text Test", "Sound Test", "Input Test", "Obj Test", - "Fixed Point Test", "Float Test", "Lag Test", "Pong", "Audio Device Test", - "Mpg123 Test", "Vorbis Test", "Performance Test", "Mesh Shader Test", "SpriteBatch Test", - "SpriteBatch Shader Test", "FrameBuffer Test", "SpriteBatch Rotation Test", "Box2D Test", - "Audio Recorder Test", "Box2D Test Collection", "Resources Test", "MD5 Test", "Micro Benchmarks", "Multitouch Test", "BufferUtils Test", "Terrain Test", "Water Ripples", - "Stage Test", "Windowed Test", "Fillrate Test", "Alpha Test", "BitmapFont Test"}; - - @Override - public void onCreate(Bundle savedInstanceState) - { - super.onCreate(savedInstanceState); - setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, items)); +import com.badlogic.gdx.box2d.TestCollection; + +public class GDXTester extends ListActivity { + String[] items = new String[] {"Life Cycle Test", "Simple Test", "Vertex Array Test", "Vertex Buffer Object Test", + "MeshRenderer Test", "Fixed Point MeshRenderer Test", "Managed Test", "Text Test", "Sound Test", "Input Test", "Obj Test", + "Fixed Point Test", "Float Test", "Lag Test", "Pong", "Audio Device Test", "Mpg123 Test", "Vorbis Test", + "Performance Test", "Mesh Shader Test", "SpriteBatch Test", "SpriteBatch Shader Test", "FrameBuffer Test", + "SpriteBatch Rotation Test", "Box2D Test", "Audio Recorder Test", "Box2D Test Collection", "Resources Test", "MD5 Test", + "Micro Benchmarks", "Multitouch Test", "BufferUtils Test", "Terrain Test", "Water Ripples", "Stage Test", "Windowed Test", + "Fillrate Test", "Alpha Test", "BitmapFont Test"}; + + @Override public void onCreate (Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, items)); } - protected void onListItemClick(ListView l, View v, int position, long id) - { + protected void onListItemClick (ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); - + Object o = this.getListAdapter().getItem(position); String keyword = o.toString(); Intent intent = null; - if( keyword.equals( items[0] ) ) - intent = new Intent( this, LifeCycleTest.class ); - if( keyword.equals( items[1] ) ) - intent = new Intent( this, SimpleTest.class ); - if( keyword.equals( items[2] ) ) - intent = new Intent( this, VertexArrayTest.class ); - if( keyword.equals( items[3] ) ) - intent = new Intent( this, VertexBufferObjectTest.class ); - if( keyword.equals( items[4] ) ) - intent = new Intent( this, MeshRendererTest.class ); - if( keyword.equals( items[5] ) ) - intent = new Intent( this, FixedPointMeshRendererTest.class ); - if( keyword.equals( items[6] ) ) - intent = new Intent( this, ManagedTest.class ); - if( keyword.equals( items[7] ) ) - intent = new Intent( this, TextTest.class ); - if( keyword.equals( items[8] ) ) - intent = new Intent( this, SoundTest.class ); - if( keyword.equals( items[9] ) ) - intent = new Intent( this, InputTest.class ); - if( keyword.equals( items[10] ) ) - intent = new Intent( this, ObjTest.class ); - if( keyword.equals( items[11] ) ) - intent = new Intent( this, FixedPointTest.class ); - if( keyword.equals( items[12] ) ) - intent = new Intent( this, FloatTest.class ); - if( keyword.equals( items[13] ) ) - intent = new Intent( this, LagTest.class ); - if( keyword.equals( items[14] ) ) - intent = new Intent( this, Pong.class ); - if( keyword.equals( items[15] ) ) - intent = new Intent( this, AudioDeviceTest.class ); - if( keyword.equals( items[16] ) ) - intent = new Intent( this, Mpg123Test.class ); - if( keyword.equals( items[17] ) ) - intent = new Intent( this, VorbisTest.class ); - if( keyword.equals( items[18] ) ) - intent = new Intent( this, PerformanceTest.class ); - if( keyword.equals( items[19] ) ) - intent = new Intent( this, MeshShaderTest.class ); - if( keyword.equals( items[20] ) ) - intent = new Intent( this, SpriteBatchTest.class ); - if( keyword.equals( items[21] ) ) - intent = new Intent( this, SpriteBatchShaderTest.class ); - if( keyword.equals( items[22] ) ) - intent = new Intent( this, FrameBufferTest.class ); - if( keyword.equals( items[23] ) ) - intent = new Intent( this, SpriteBatchRotationTest.class ); - if( keyword.equals( items[24] ) ) - intent = new Intent( this, Box2DTest.class ); - if( keyword.equals( items[25] ) ) - intent = new Intent( this, AudioRecorderTest.class ); - if( keyword.equals( items[26] ) ) - intent = new Intent( this, TestCollection.class ); - if( keyword.equals( items[27] ) ) - intent = new Intent( this, ResourcesTest.class ); - if( keyword.equals( items[28] ) ) - intent = new Intent( this, MD5Test.class ); - if( keyword.equals( items[29] ) ) - intent = new Intent( this, MicroBenchmarks.class ); - if( keyword.equals( items[30] ) ) - intent = new Intent( this, MultitouchTest.class ); - if( keyword.equals( items[31] ) ) - intent = new Intent( this, BufferUtilsTest.class ); - if( keyword.equals( items[32] ) ) - intent = new Intent( this, TerrainTest.class ); - if( keyword.equals( items[33] ) ) - intent = new Intent( this, WaterRipples.class ); - if( keyword.equals( items[34] ) ) - intent = new Intent( this, StageTest.class ); - if( keyword.equals( items[35] ) ) - intent = new Intent( this, WindowedTest.class ); - if( keyword.equals( items[36] ) ) - intent = new Intent( this, FillrateTest.class ); - if( keyword.equals( items[37] ) ) - intent = new Intent( this, AlphaTest.class ); - if( keyword.equals( items[38] ) ) - intent = new Intent( this, BitmapFontTest.class ); - - startActivity( intent ); + if (keyword.equals(items[0])) intent = new Intent(this, LifeCycleTest.class); + if (keyword.equals(items[1])) intent = new Intent(this, SimpleTest.class); + if (keyword.equals(items[2])) intent = new Intent(this, VertexArrayTest.class); + if (keyword.equals(items[3])) intent = new Intent(this, VertexBufferObjectTest.class); + if (keyword.equals(items[4])) intent = new Intent(this, MeshRendererTest.class); + if (keyword.equals(items[5])) intent = new Intent(this, FixedPointMeshRendererTest.class); + if (keyword.equals(items[6])) intent = new Intent(this, ManagedTest.class); + if (keyword.equals(items[7])) intent = new Intent(this, TextTest.class); + if (keyword.equals(items[8])) intent = new Intent(this, SoundTest.class); + if (keyword.equals(items[9])) intent = new Intent(this, InputTest.class); + if (keyword.equals(items[10])) intent = new Intent(this, ObjTest.class); + if (keyword.equals(items[11])) intent = new Intent(this, FixedPointTest.class); + if (keyword.equals(items[12])) intent = new Intent(this, FloatTest.class); + if (keyword.equals(items[13])) intent = new Intent(this, LagTest.class); + if (keyword.equals(items[14])) intent = new Intent(this, Pong.class); + if (keyword.equals(items[15])) intent = new Intent(this, AudioDeviceTest.class); + if (keyword.equals(items[16])) intent = new Intent(this, Mpg123Test.class); + if (keyword.equals(items[17])) intent = new Intent(this, VorbisTest.class); + if (keyword.equals(items[18])) intent = new Intent(this, PerformanceTest.class); + if (keyword.equals(items[19])) intent = new Intent(this, MeshShaderTest.class); + if (keyword.equals(items[20])) intent = new Intent(this, SpriteBatchTest.class); + if (keyword.equals(items[21])) intent = new Intent(this, SpriteBatchShaderTest.class); + if (keyword.equals(items[22])) intent = new Intent(this, FrameBufferTest.class); + if (keyword.equals(items[23])) intent = new Intent(this, SpriteBatchRotationTest.class); + if (keyword.equals(items[24])) intent = new Intent(this, Box2DTest.class); + if (keyword.equals(items[25])) intent = new Intent(this, AudioRecorderTest.class); + if (keyword.equals(items[26])) intent = new Intent(this, TestCollection.class); + if (keyword.equals(items[27])) intent = new Intent(this, ResourcesTest.class); + if (keyword.equals(items[28])) intent = new Intent(this, MD5Test.class); + if (keyword.equals(items[29])) intent = new Intent(this, MicroBenchmarks.class); + if (keyword.equals(items[30])) intent = new Intent(this, MultitouchTest.class); + if (keyword.equals(items[31])) intent = new Intent(this, BufferUtilsTest.class); + if (keyword.equals(items[32])) intent = new Intent(this, TerrainTest.class); + if (keyword.equals(items[33])) intent = new Intent(this, WaterRipples.class); + if (keyword.equals(items[34])) intent = new Intent(this, StageTest.class); + if (keyword.equals(items[35])) intent = new Intent(this, WindowedTest.class); + if (keyword.equals(items[36])) intent = new Intent(this, FillrateTest.class); + if (keyword.equals(items[37])) intent = new Intent(this, AlphaTest.class); + if (keyword.equals(items[38])) intent = new Intent(this, BitmapFontTest.class); + + startActivity(intent); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/InputTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/InputTest.java index 1f95014bb..8e10dd63f 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/InputTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/InputTest.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class InputTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( false ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.InputTest() ); +public class InputTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(false); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.InputTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/LagTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/LagTest.java index 125a1851d..0be2f6680 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/LagTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/LagTest.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import javax.microedition.khronos.egl.EGLConfig; @@ -26,42 +24,34 @@ import android.util.Log; import android.view.Window; import android.view.WindowManager; -public class LagTest extends Activity implements Renderer -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - requestWindowFeature(Window.FEATURE_NO_TITLE); - getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN ); - GLSurfaceView view = new GLSurfaceView( this ); - view.setRenderer( this ); - setContentView( view ); +public class LagTest extends Activity implements Renderer { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + requestWindowFeature(Window.FEATURE_NO_TITLE); + getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); + GLSurfaceView view = new GLSurfaceView(this); + view.setRenderer(this); + setContentView(view); } long startTime = 0; int frames; - - @Override - public void onDrawFrame(GL10 gl) - { + + @Override public void onDrawFrame (GL10 gl) { frames++; - if( System.nanoTime() - startTime > 1000000000 ) - { - Log.d( "Lag Test", "fps: " + frames ); + if (System.nanoTime() - startTime > 1000000000) { + Log.d("Lag Test", "fps: " + frames); startTime = System.nanoTime(); frames = 0; } } - @Override - public void onSurfaceChanged(GL10 gl, int width, int height) { + @Override public void onSurfaceChanged (GL10 gl, int width, int height) { // TODO Auto-generated method stub - + } - @Override - public void onSurfaceCreated(GL10 gl, EGLConfig config) - { + @Override public void onSurfaceCreated (GL10 gl, EGLConfig config) { startTime = System.nanoTime(); frames = 0; } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/LifeCycleTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/LifeCycleTest.java index 99cd7658c..a56ee45cf 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/LifeCycleTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/LifeCycleTest.java @@ -1,32 +1,28 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ -package com.badlogic.gdx; -import com.badlogic.gdx.backends.android.AndroidApplication; +package com.badlogic.gdx; import android.os.Bundle; -public class LifeCycleTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); +import com.badlogic.gdx.backends.android.AndroidApplication; + +public class LifeCycleTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); this.initialize(false); com.badlogic.gdx.tests.LifeCycleTest test = new com.badlogic.gdx.tests.LifeCycleTest(); - this.setApplicationListener( test ); - this.getGraphics().setRenderListener( test ); + this.setApplicationListener(test); + this.getGraphics().setRenderListener(test); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/MD5Test.java b/tests/gdx-tests-android/src/com/badlogic/gdx/MD5Test.java index b969453db..c68606c4f 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/MD5Test.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/MD5Test.java @@ -1,17 +1,16 @@ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class MD5Test extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); -// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); - initialize( false ); - - getGraphics().setRenderListener( new com.badlogic.gdx.tests.MD5Test() ); - } +public class MD5Test extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); +// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); + initialize(false); + + getGraphics().setRenderListener(new com.badlogic.gdx.tests.MD5Test()); + } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/ManagedTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/ManagedTest.java index 8465b74f9..8159d35f0 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/ManagedTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/ManagedTest.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class ManagedTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( false ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.ManagedTest() ); +public class ManagedTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(false); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.ManagedTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/MeshRendererTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/MeshRendererTest.java index 75c4ef962..5d4d9e437 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/MeshRendererTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/MeshRendererTest.java @@ -1,32 +1,28 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ -package com.badlogic.gdx; -import com.badlogic.gdx.backends.android.AndroidApplication; +package com.badlogic.gdx; import android.content.pm.ActivityInfo; import android.os.Bundle; -public class MeshRendererTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE ); +import com.badlogic.gdx.backends.android.AndroidApplication; + +public class MeshRendererTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); initialize(false); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.MeshTest() ); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.MeshTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/MeshShaderTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/MeshShaderTest.java index e913901cf..e2696de03 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/MeshShaderTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/MeshShaderTest.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class MeshShaderTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( true ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.MeshShaderTest() ); +public class MeshShaderTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(true); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.MeshShaderTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/MicroBenchmarks.java b/tests/gdx-tests-android/src/com/badlogic/gdx/MicroBenchmarks.java index c5c04db96..e6afd1c7b 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/MicroBenchmarks.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/MicroBenchmarks.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx; import java.nio.ByteBuffer; @@ -13,109 +14,96 @@ import android.widget.TextView; import com.badlogic.gdx.utils.BufferUtils; -public class MicroBenchmarks extends Activity -{ +public class MicroBenchmarks extends Activity { final int TRIES = 5; long start = 0; ScrollView sv; - TextView tv; - Thread testThread = new Thread( new Runnable( ) { - - @Override - public void run() - { - ByteBuffer buffer = ByteBuffer.allocateDirect( 1024*1024 * Float.SIZE / 8 ); - buffer.order(ByteOrder.nativeOrder()); + TextView tv; + Thread testThread = new Thread(new Runnable() { + + @Override public void run () { + ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 1024 * Float.SIZE / 8); + buffer.order(ByteOrder.nativeOrder()); FloatBuffer floatBuffer = buffer.asFloatBuffer(); IntBuffer intBuffer = buffer.asIntBuffer(); - - float[] floatArray = new float[1024*1024]; - int[] intArray = new int[1024*1024]; - + + float[] floatArray = new float[1024 * 1024]; + int[] intArray = new int[1024 * 1024]; + // single put tic(); - for( int tries = 0; tries < TRIES; tries++ ) - { - for( int i = 0; i < floatArray.length; i++ ) - floatBuffer.put( floatArray[i] ); + for (int tries = 0; tries < TRIES; tries++) { + for (int i = 0; i < floatArray.length; i++) + floatBuffer.put(floatArray[i]); floatBuffer.clear(); } - toc( "single put" ); + toc("single put"); // single indexed put tic(); - for( int tries = 0; tries < TRIES; tries++ ) - { - for( int i = 0; i < floatArray.length; i++ ) - floatBuffer.put( i, floatArray[i] ); + for (int tries = 0; tries < TRIES; tries++) { + for (int i = 0; i < floatArray.length; i++) + floatBuffer.put(i, floatArray[i]); floatBuffer.clear(); } - toc( "single indexed put" ); - + toc("single indexed put"); + // bulk put tic(); - for( int tries = 0; tries < TRIES; tries++ ) - { - floatBuffer.put( floatArray ); + for (int tries = 0; tries < TRIES; tries++) { + floatBuffer.put(floatArray); floatBuffer.clear(); } - toc( "vector put" ); - + toc("vector put"); + // convert bulk put tic(); - for( int tries = 0; tries < TRIES; tries++ ) - { - for( int i = 0; i < floatArray.length; i++ ) + for (int tries = 0; tries < TRIES; tries++) { + for (int i = 0; i < floatArray.length; i++) intArray[i] = Float.floatToIntBits(floatArray[i]); intBuffer.put(intArray); intBuffer.clear(); } - toc( "convert bulk put" ); - + toc("convert bulk put"); + // jni bulk put tic(); - for( int tries = 0; tries < TRIES; tries++ ) - { - BufferUtils.copy( floatArray, floatBuffer, floatArray.length, 0 ); + for (int tries = 0; tries < TRIES; tries++) { + BufferUtils.copy(floatArray, floatBuffer, floatArray.length, 0); floatBuffer.clear(); } - toc( "jni bulk put" ); + toc("jni bulk put"); } - - }); - - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - - tv = new TextView( this ); - sv = new ScrollView( this ); - sv.addView( tv ); - setContentView( sv ); + + }); + + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + + tv = new TextView(this); + sv = new ScrollView(this); + sv.addView(tv); + setContentView(sv); testThread.start(); } - private void tic( ) - { + private void tic () { start = System.nanoTime(); } - - private void toc( final String info ) - { - final float time = (System.nanoTime()-start)/1000000000.0f; - - tv.post( new Runnable() { - - @Override - public void run() - { - StringBuilder buff = new StringBuilder( tv.getText() ); - buff.append( info ).append( ", " ).append(time).append( " secs\n" ); - tv.setText( buff.toString() ); + + private void toc (final String info) { + final float time = (System.nanoTime() - start) / 1000000000.0f; + + tv.post(new Runnable() { + + @Override public void run () { + StringBuilder buff = new StringBuilder(tv.getText()); + buff.append(info).append(", ").append(time).append(" secs\n"); + tv.setText(buff.toString()); } - } ); + }); - Log.d( "MicroBenchmarks", info + ", " + time ); + Log.d("MicroBenchmarks", info + ", " + time); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/Mpg123Test.java b/tests/gdx-tests-android/src/com/badlogic/gdx/Mpg123Test.java index b57df9121..64d4543f9 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/Mpg123Test.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/Mpg123Test.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class Mpg123Test extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { +public class Mpg123Test extends AndroidApplication { + public void onCreate (Bundle bundle) { super.onCreate(bundle); initialize(false); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.Mpg123Test() ); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.Mpg123Test()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/MultitouchTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/MultitouchTest.java index 9922c78f1..56247d950 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/MultitouchTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/MultitouchTest.java @@ -1,15 +1,14 @@ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class MultitouchTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); +public class MultitouchTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); initialize(false); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.MultitouchTest() ); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.MultitouchTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/ObjTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/ObjTest.java index c5db5a056..34b13fc67 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/ObjTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/ObjTest.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class ObjTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( false ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.ObjTest() ); +public class ObjTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(false); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.ObjTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/PerformanceTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/PerformanceTest.java index ac0d3e912..3c7bf0701 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/PerformanceTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/PerformanceTest.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class PerformanceTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( false ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.PerformanceTest() ); +public class PerformanceTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(false); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.PerformanceTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/Pong.java b/tests/gdx-tests-android/src/com/badlogic/gdx/Pong.java index a4e256a12..0547167e4 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/Pong.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/Pong.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class Pong extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( false ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.Pong() ); +public class Pong extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(false); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.Pong()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/ResourcesTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/ResourcesTest.java index f5d3df611..7aa8a08d4 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/ResourcesTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/ResourcesTest.java @@ -1,71 +1,60 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; import com.badlogic.gdx.graphics.Font; +import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.ImmediateModeRenderer; import com.badlogic.gdx.graphics.SpriteBatch; -import com.badlogic.gdx.graphics.Font.FontStyle; -public class ResourcesTest extends AndroidApplication implements RenderListener -{ +public class ResourcesTest extends AndroidApplication implements RenderListener { Font font; SpriteBatch batch; ImmediateModeRenderer renderer; - - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( false ); - getGraphics().setRenderListener( this ); + + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(false); + getGraphics().setRenderListener(this); } - @Override - public void dispose( ) - { + @Override public void dispose () { font.dispose(); - batch.dispose(); + batch.dispose(); } - @Override - public void render( ) - { - if( font != null ) - { + @Override public void render () { + if (font != null) { font.dispose(); batch.dispose(); } - - font = Gdx.app.getGraphics().newFont( "Arial", 12, FontStyle.Plain ); - batch = new SpriteBatch( ); - renderer = new ImmediateModeRenderer( ); + + font = Gdx.app.getGraphics().newFont("Arial", 12, FontStyle.Plain); + batch = new SpriteBatch(); + renderer = new ImmediateModeRenderer(); } - @Override - public void surfaceChanged( int width, int height) { + @Override public void surfaceChanged (int width, int height) { // TODO Auto-generated method stub - + } - @Override - public void surfaceCreated() { + @Override public void surfaceCreated () { // TODO Auto-generated method stub - + } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/SimpleTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/SimpleTest.java index fc003c6be..4a11e8696 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/SimpleTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/SimpleTest.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.content.pm.ActivityInfo; @@ -20,13 +18,11 @@ import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class SimpleTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE ); +public class SimpleTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); initialize(false); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.SimpleTest() ); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.SimpleTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/SoundTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/SoundTest.java index a4725fff8..0d9c079d1 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/SoundTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/SoundTest.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class SoundTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( false ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.SoundTest() ); +public class SoundTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(false); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.SoundTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/SpriteBatchRotationTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/SpriteBatchRotationTest.java index a0dd7f505..ee05249d3 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/SpriteBatchRotationTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/SpriteBatchRotationTest.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class SpriteBatchRotationTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); +public class SpriteBatchRotationTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); initialize(false); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.SpriteBatchRotationTest() ); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.SpriteBatchRotationTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/SpriteBatchShaderTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/SpriteBatchShaderTest.java index 23d9f3e43..cca37b9f7 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/SpriteBatchShaderTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/SpriteBatchShaderTest.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class SpriteBatchShaderTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( true ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.SpriteBatchShaderTest() ); +public class SpriteBatchShaderTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(true); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.SpriteBatchShaderTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/SpriteBatchTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/SpriteBatchTest.java index 1dc527667..9738e8318 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/SpriteBatchTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/SpriteBatchTest.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class SpriteBatchTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( false ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.SpriteBatchTest() ); +public class SpriteBatchTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(false); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.SpriteBatchTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/StageTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/StageTest.java index a3eb69903..60a24adbf 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/StageTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/StageTest.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class StageTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( false ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.StageTest() ); +public class StageTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(false); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.StageTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/TerrainTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/TerrainTest.java index 8b4026daf..b54e66fd8 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/TerrainTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/TerrainTest.java @@ -1,15 +1,14 @@ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class TerrainTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( false ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.TerrainTest( ) ); +public class TerrainTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(false); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.TerrainTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/TextTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/TextTest.java index f8d5fe290..753f4430f 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/TextTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/TextTest.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class TextTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( false ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.TextTest() ); +public class TextTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(false); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.TextTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/VertexArrayTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/VertexArrayTest.java index 3a4f8c691..4cccaffa0 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/VertexArrayTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/VertexArrayTest.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class VertexArrayTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( false ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.VertexArrayTest() ); +public class VertexArrayTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(false); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.VertexArrayTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/VertexBufferObjectTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/VertexBufferObjectTest.java index 4c1c15ee4..e862ca3c9 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/VertexBufferObjectTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/VertexBufferObjectTest.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class VertexBufferObjectTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( false ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.VertexBufferObjectTest() ); +public class VertexBufferObjectTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(false); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.VertexBufferObjectTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/VorbisTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/VorbisTest.java index 143c994d5..ca6b7671d 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/VorbisTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/VorbisTest.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 mzechner * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class VorbisTest extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( false ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.VorbisTest() ); +public class VorbisTest extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(false); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.VorbisTest()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/WaterRipples.java b/tests/gdx-tests-android/src/com/badlogic/gdx/WaterRipples.java index 976708b46..2c4ae0ff5 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/WaterRipples.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/WaterRipples.java @@ -1,15 +1,14 @@ + package com.badlogic.gdx; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class WaterRipples extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( false ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.WaterRipples() ); +public class WaterRipples extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(false); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.WaterRipples()); } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/WindowedTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/WindowedTest.java index 0b8b72edc..428d4650f 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/WindowedTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/WindowedTest.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx; import javax.microedition.khronos.opengles.GL10; @@ -14,85 +15,73 @@ import android.widget.LinearLayout; import com.badlogic.gdx.backends.android.AndroidApplication; import com.badlogic.gdx.graphics.Color; -public class WindowedTest extends AndroidApplication implements RenderListener -{ - Color color = new Color( 1, 1, 1, 1 ); - - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - - Button b1 = new Button( this ); - b1.setText( "Change Color" ); - b1.setLayoutParams( new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT ) ); - Button b2 = new Button( this ); - b2.setText( "New Window" ); - b2.setLayoutParams( new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT ) ); - View view = initializeForView( false, 16 ); - - LinearLayout layout = new LinearLayout( this ); - layout.setOrientation( LinearLayout.VERTICAL ); - layout.addView( b1 ); - layout.addView( b2 ); - layout.addView( view, new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT ) ); - +public class WindowedTest extends AndroidApplication implements RenderListener { + Color color = new Color(1, 1, 1, 1); + + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + + Button b1 = new Button(this); + b1.setText("Change Color"); + b1.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); + Button b2 = new Button(this); + b2.setText("New Window"); + b2.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); + View view = initializeForView(false, 16); + + LinearLayout layout = new LinearLayout(this); + layout.setOrientation(LinearLayout.VERTICAL); + layout.addView(b1); + layout.addView(b2); + layout.addView(view, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); + getGraphics().setRenderListener(this); - setContentView( layout ); - - b1.setOnClickListener( new OnClickListener() { + setContentView(layout); + + b1.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View arg0) { - color.set( (float)Math.random(), (float)Math.random(), (float)Math.random(), 1 ); + @Override public void onClick (View arg0) { + color.set((float)Math.random(), (float)Math.random(), (float)Math.random(), 1); } - + }); - b2.setOnClickListener( new OnClickListener() { + b2.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent( WindowedTest.this, WindowedTest.class ); - WindowedTest.this.startActivity( intent ); - } + @Override public void onClick (View v) { + Intent intent = new Intent(WindowedTest.this, WindowedTest.class); + WindowedTest.this.startActivity(intent); + } }); } - - public void onPause( ) - { - super.onPause( ); + + public void onPause () { + super.onPause(); } - - @Override - public void onDestroy( ) - { + + @Override public void onDestroy () { super.onDestroy(); - Log.w( "WindowedTest", "destroying" ); + Log.w("WindowedTest", "destroying"); } - @Override - public void surfaceCreated() { + @Override public void surfaceCreated () { // TODO Auto-generated method stub - + } - @Override - public void surfaceChanged(int width, int height) { + @Override public void surfaceChanged (int width, int height) { // TODO Auto-generated method stub - + } - @Override - public void render() - { - Gdx.graphics.getGL10().glClearColor( color.r, color.g, color.g, color.a ); - Gdx.graphics.getGL10().glClear( GL10.GL_COLOR_BUFFER_BIT ); - + @Override public void render () { + Gdx.graphics.getGL10().glClearColor(color.r, color.g, color.g, color.a); + Gdx.graphics.getGL10().glClear(GL10.GL_COLOR_BUFFER_BIT); + } - @Override - public void dispose() { + @Override public void dispose () { // TODO Auto-generated method stub - + } } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/box2d/TestCollection.java b/tests/gdx-tests-android/src/com/badlogic/gdx/box2d/TestCollection.java index cb20903f5..bd1e2c569 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/box2d/TestCollection.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/box2d/TestCollection.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.box2d; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class TestCollection extends AndroidApplication -{ - public void onCreate( Bundle bundle ) - { - super.onCreate( bundle ); - initialize( false ); - getGraphics().setRenderListener( new com.badlogic.gdx.tests.box2d.TestCollection() ); +public class TestCollection extends AndroidApplication { + public void onCreate (Bundle bundle) { + super.onCreate(bundle); + initialize(false); + getGraphics().setRenderListener(new com.badlogic.gdx.tests.box2d.TestCollection()); } } diff --git a/tests/gdx-tests-applet/src/com/badlogic/gdx/SimpleTestApplet.java b/tests/gdx-tests-applet/src/com/badlogic/gdx/SimpleTestApplet.java index 7e986b880..0cd979bdf 100644 --- a/tests/gdx-tests-applet/src/com/badlogic/gdx/SimpleTestApplet.java +++ b/tests/gdx-tests-applet/src/com/badlogic/gdx/SimpleTestApplet.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import java.applet.Applet; @@ -27,14 +25,12 @@ import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; -public class SimpleTestApplet extends Applet implements RenderListener, InputListener -{ +public class SimpleTestApplet extends Applet implements RenderListener, InputListener { private static final long serialVersionUID = 2795113572615488100L; - public void init() - { - new AppletApplication( this, false, false ); - Gdx.graphics.setRenderListener( this ); + public void init () { + new AppletApplication(this, false, false); + Gdx.graphics.setRenderListener(this); } PerspectiveCamera cam; @@ -42,105 +38,89 @@ public class SimpleTestApplet extends Applet implements RenderListener, InputLis Texture texture; float angleY = 0; float angleX = 0; - float[] lightColor = { 1, 1, 1, 0 }; - float[] lightPosition = { 2, 5, 10, 0 }; + float[] lightColor = {1, 1, 1, 0}; + float[] lightPosition = {2, 5, 10, 0}; float touchStartX = 0; float touchStartY = 0; - + long frameStart; int frames = 0; - @Override - public void surfaceCreated( ) - { - if( mesh == null ) - { - Gdx.input.addInputListener( this ); - - mesh = ModelLoader.loadObj( Gdx.files.readFile( "data/cube.obj", FileType.Internal ), true); - texture = Gdx.graphics.newTexture( Gdx.files.getFileHandle( "data/badlogic.jpd", FileType.Internal), TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); - + @Override public void surfaceCreated () { + if (mesh == null) { + Gdx.input.addInputListener(this); + + mesh = ModelLoader.loadObj(Gdx.files.readFile("data/cube.obj", FileType.Internal), true); + texture = Gdx.graphics.newTexture(Gdx.files.getFileHandle("data/badlogic.jpd", FileType.Internal), TextureFilter.MipMap, + TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); + cam = new PerspectiveCamera(); - cam.getPosition().set( 2, 2, 2 ); - cam.getDirection().set( -1, -1, -1 ); + cam.getPosition().set(2, 2, 2); + cam.getDirection().set(-1, -1, -1); } frameStart = System.nanoTime(); } - @Override - public void surfaceChanged(int width, int height) - { - + @Override public void surfaceChanged (int width, int height) { + } - - @Override - public void render( ) - { + + @Override public void render () { GL10 gl = Gdx.graphics.getGL10(); - - gl.glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - gl.glClear( GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT ); - gl.glEnable( GL10.GL_DEPTH_TEST ); - gl.glEnable( GL10.GL_LIGHTING ); - gl.glEnable( GL10.GL_COLOR_MATERIAL ); - gl.glEnable( GL10.GL_TEXTURE_2D ); - - cam.setMatrices( ); - - gl.glEnable( GL10.GL_LIGHT0 ); - gl.glLightfv( GL10.GL_LIGHT0, GL10.GL_DIFFUSE, lightColor, 0 ); - gl.glLightfv( GL10.GL_LIGHT0, GL10.GL_POSITION, lightPosition, 0 ); - - gl.glRotatef(angleY, 0, 1, 0); - gl.glRotatef(angleX, 1, 0, 0 ); + + gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); + gl.glEnable(GL10.GL_DEPTH_TEST); + gl.glEnable(GL10.GL_LIGHTING); + gl.glEnable(GL10.GL_COLOR_MATERIAL); + gl.glEnable(GL10.GL_TEXTURE_2D); + + cam.setMatrices(); + + gl.glEnable(GL10.GL_LIGHT0); + gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_DIFFUSE, lightColor, 0); + gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, lightPosition, 0); + + gl.glRotatef(angleY, 0, 1, 0); + gl.glRotatef(angleX, 1, 0, 0); texture.bind(); - mesh.render( GL10.GL_TRIANGLES ); - - if( System.nanoTime() - frameStart > 1000000000 ) - { - Gdx.app.log( "Obj Test", "fps: " + frames ); + mesh.render(GL10.GL_TRIANGLES); + + if (System.nanoTime() - frameStart > 1000000000) { + Gdx.app.log("Obj Test", "fps: " + frames); frames = 0; frameStart = System.nanoTime(); } - + frames++; } - @Override - public void dispose( ) - { - - } - + @Override public void dispose () { + + } - @Override - public boolean keyDown(int keycode) { + @Override public boolean keyDown (int keycode) { // TODO Auto-generated method stub return false; } - @Override - public boolean keyTyped(char character) { + @Override public boolean keyTyped (char character) { // TODO Auto-generated method stub return false; } - @Override - public boolean keyUp(int keycode) { + @Override public boolean keyUp (int keycode) { // TODO Auto-generated method stub return false; } - @Override - public boolean touchDown(int x, int y, int pointer) { + @Override public boolean touchDown (int x, int y, int pointer) { touchStartX = x; touchStartY = y; return false; } - @Override - public boolean touchDragged(int x, int y, int pointer) - { + @Override public boolean touchDragged (int x, int y, int pointer) { angleY += (x - touchStartX); angleX += (y - touchStartY); touchStartX = x; @@ -148,8 +128,7 @@ public class SimpleTestApplet extends Applet implements RenderListener, InputLis return false; } - @Override - public boolean touchUp(int x, int y, int pointer) { + @Override public boolean touchUp (int x, int y, int pointer) { // TODO Auto-generated method stub return false; } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/AlphaTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/AlphaTest.java index 0cec80f27..e1d410c33 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/AlphaTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/AlphaTest.java @@ -1,13 +1,11 @@ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class AlphaTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Alpha Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.AlphaTest() ); +public class AlphaTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Alpha Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.AlphaTest()); } } - diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/AudioDeviceTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/AudioDeviceTest.java index a25d282f7..39a37f05e 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/AudioDeviceTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/AudioDeviceTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class AudioDeviceTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "AudioDevice Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.AudioDeviceTest() ); +public class AudioDeviceTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("AudioDevice Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.AudioDeviceTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/AudioRecorderTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/AudioRecorderTest.java index d3615ca72..43d2f98fa 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/AudioRecorderTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/AudioRecorderTest.java @@ -1,28 +1,24 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class AudioRecorderTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "AudioRecorder Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.AudioRecorderTest() ); +public class AudioRecorderTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("AudioRecorder Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.AudioRecorderTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/BitmapFontTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/BitmapFontTest.java index f96f8d506..b86bd7597 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/BitmapFontTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/BitmapFontTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class BitmapFontTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "BitmapFont Test", 480, 320, false); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.BitmapFontTest() ); +public class BitmapFontTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("BitmapFont Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.BitmapFontTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/Box2DTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/Box2DTest.java index a67b8645e..0aef8fb32 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/Box2DTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/Box2DTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class Box2DTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Box2D Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.Box2DTest() ); +public class Box2DTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Box2D Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.Box2DTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/DualThreadTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/DualThreadTest.java index cd090a5cf..c59331a1e 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/DualThreadTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/DualThreadTest.java @@ -1,14 +1,13 @@ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class DualThreadTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Dual Thread Test", 480, 320, false ); +public class DualThreadTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Dual Thread Test", 480, 320, false); com.badlogic.gdx.tests.DualThreadTest test = new com.badlogic.gdx.tests.DualThreadTest(); - app.setApplicationListener( test ); - app.getGraphics().setRenderListener( test ); + app.setApplicationListener(test); + app.getGraphics().setRenderListener(test); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/FillrateTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/FillrateTest.java index 56f8b9371..1b01cff4c 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/FillrateTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/FillrateTest.java @@ -1,12 +1,11 @@ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class FillrateTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Fillrate Test", 480, 420, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.FillrateTest() ); +public class FillrateTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Fillrate Test", 480, 420, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.FillrateTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/FixedPointMeshTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/FixedPointMeshTest.java index bca9efddd..d970b6e75 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/FixedPointMeshTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/FixedPointMeshTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class FixedPointMeshTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Fixed Point MeshRenderer Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.FixedPointMeshTest() ); +public class FixedPointMeshTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Fixed Point MeshRenderer Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.FixedPointMeshTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/FixedPointTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/FixedPointTest.java index 5461b6897..72a5c1a2a 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/FixedPointTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/FixedPointTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class FixedPointTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Fixed Point Test", 480, 320, false); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.FixedPointTest() ); +public class FixedPointTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Fixed Point Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.FixedPointTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/FloatTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/FloatTest.java index ff952875a..796c3b49c 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/FloatTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/FloatTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class FloatTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "BitmapFont Test", 480, 320, false); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.BitmapFontTest() ); +public class FloatTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("BitmapFont Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.BitmapFontTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/FrameBufferTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/FrameBufferTest.java index fc89e44f1..fd8fde546 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/FrameBufferTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/FrameBufferTest.java @@ -1,28 +1,24 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class FrameBufferTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "FrameBuffer Test", 480, 320, true ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.FrameBufferTest() ); +public class FrameBufferTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("FrameBuffer Test", 480, 320, true); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.FrameBufferTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/ImmediateModeRendererTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/ImmediateModeRendererTest.java index ab18c054d..db57f36bd 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/ImmediateModeRendererTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/ImmediateModeRendererTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class ImmediateModeRendererTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Immediate Mode Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.ImmediateModeRendererTest() ); +public class ImmediateModeRendererTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Immediate Mode Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.ImmediateModeRendererTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/InputTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/InputTest.java index 01f5b126f..0a5503d38 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/InputTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/InputTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class InputTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Key Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.InputTest() ); +public class InputTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Key Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.InputTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/LifeCycleTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/LifeCycleTest.java index b67326eb7..0b961f7e5 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/LifeCycleTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/LifeCycleTest.java @@ -1,36 +1,31 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; /** - * A simple test to demonstrate the life cycle of an application and a - * RenderListener. + * A simple test to demonstrate the life cycle of an application and a RenderListener. * * @author mzechner - * + * */ -public class LifeCycleTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Life Cycle Test", 480, 320, false ); - com.badlogic.gdx.tests.LifeCycleTest test = new com.badlogic.gdx.tests.LifeCycleTest( ); - app.setApplicationListener( test ); - app.getGraphics().setRenderListener( test ); +public class LifeCycleTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Life Cycle Test", 480, 320, false); + com.badlogic.gdx.tests.LifeCycleTest test = new com.badlogic.gdx.tests.LifeCycleTest(); + app.setApplicationListener(test); + app.getGraphics().setRenderListener(test); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/MD5Test.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/MD5Test.java index 97c33e3ab..cb4c80a09 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/MD5Test.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/MD5Test.java @@ -1,14 +1,13 @@ + package com.badlogic.gdx.tests.desktop; import java.io.FileNotFoundException; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class MD5Test -{ - public static void main( String[] argv ) throws FileNotFoundException - { - JoglApplication app = new JoglApplication( "MD5 Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.MD5Test() ); +public class MD5Test { + public static void main (String[] argv) throws FileNotFoundException { + JoglApplication app = new JoglApplication("MD5 Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.MD5Test()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/ManagedTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/ManagedTest.java index d72f931d1..341b972f8 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/ManagedTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/ManagedTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class ManagedTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Managed Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.ManagedTest() ); +public class ManagedTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Managed Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.ManagedTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/MeshMultitextureTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/MeshMultitextureTest.java index 5a7b76925..1776f2a12 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/MeshMultitextureTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/MeshMultitextureTest.java @@ -1,12 +1,11 @@ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class MeshMultitextureTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Mesh Multitexture Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.MeshMultitextureTest() ); +public class MeshMultitextureTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Mesh Multitexture Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.MeshMultitextureTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/MeshShaderTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/MeshShaderTest.java index 37ae67a59..df6a8c87f 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/MeshShaderTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/MeshShaderTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class MeshShaderTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Mesh Test", 480, 320, true ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.MeshShaderTest() ); +public class MeshShaderTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Mesh Test", 480, 320, true); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.MeshShaderTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/MeshTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/MeshTest.java index a41571f3b..f99d1c477 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/MeshTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/MeshTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class MeshTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Mesh Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.MeshTest() ); +public class MeshTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Mesh Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.MeshTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/MicroBenchmarks.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/MicroBenchmarks.java index 8c0db998f..c8ff725cd 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/MicroBenchmarks.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/MicroBenchmarks.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.tests.desktop; import java.nio.ByteBuffer; @@ -6,73 +7,66 @@ import java.nio.FloatBuffer; import com.badlogic.gdx.utils.BufferUtils; -public class MicroBenchmarks -{ +public class MicroBenchmarks { static long start; - - public static void main( String[] argv ) - { - ByteBuffer byteBuffer = ByteBuffer.allocateDirect( 1024*1024 * Float.SIZE / 8 ); - byteBuffer.order( ByteOrder.nativeOrder() ); + + public static void main (String[] argv) { + ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024 * 1024 * Float.SIZE / 8); + byteBuffer.order(ByteOrder.nativeOrder()); FloatBuffer buffer = byteBuffer.asFloatBuffer(); - - float[] array = new float[1024*1024]; - + + float[] array = new float[1024 * 1024]; + // single put tic(); - for( int tries = 0; tries < 1000; tries++ ) - { - for( int i = 0; i < array.length; i++ ) - buffer.put( array[i] ); + for (int tries = 0; tries < 1000; tries++) { + for (int i = 0; i < array.length; i++) + buffer.put(array[i]); buffer.clear(); } - toc( "single put" ); + toc("single put"); // single indexed put tic(); - for( int tries = 0; tries < 1000; tries++ ) - { - for( int i = 0; i < array.length; i++ ) - buffer.put( i, array[i] ); + for (int tries = 0; tries < 1000; tries++) { + for (int i = 0; i < array.length; i++) + buffer.put(i, array[i]); buffer.clear(); } - toc( "single indexed put" ); - + toc("single indexed put"); + // bulk put tic(); - for( int tries = 0; tries < 1000; tries++ ) - { - buffer.put( array ); + for (int tries = 0; tries < 1000; tries++) { + buffer.put(array); buffer.clear(); } - toc( "vector put" ); - + toc("vector put"); + // jni bulk put tic(); - for( int tries = 0; tries < 1000; tries++ ) - BufferUtils.copy( array, buffer, array.length, 0 ); - toc( "jni put" ); - + for (int tries = 0; tries < 1000; tries++) + BufferUtils.copy(array, buffer, array.length, 0); + toc("jni put"); + // jni test - byteBuffer = ByteBuffer.allocateDirect( 4 * Float.SIZE / 8 ); + byteBuffer = ByteBuffer.allocateDirect(4 * Float.SIZE / 8); byteBuffer.order(ByteOrder.nativeOrder()); buffer = byteBuffer.asFloatBuffer(); - - array = new float[] { 0, 1, 2, 3 }; - BufferUtils.copy( array, buffer, 4, 0 ); - System.out.println( buffer.get()); - System.out.println( buffer.get()); - System.out.println( buffer.get()); - System.out.println( buffer.get()); + + array = new float[] {0, 1, 2, 3}; + BufferUtils.copy(array, buffer, 4, 0); + System.out.println(buffer.get()); + System.out.println(buffer.get()); + System.out.println(buffer.get()); + System.out.println(buffer.get()); } - - private static void tic( ) - { + + private static void tic () { start = System.nanoTime(); } - - private static void toc( String info ) - { - System.out.println( "MicroBenchmarks: " + info + ", " + (System.nanoTime()-start)/1000000000.0f ); + + private static void toc (String info) { + System.out.println("MicroBenchmarks: " + info + ", " + (System.nanoTime() - start) / 1000000000.0f); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/Mpg123Test.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/Mpg123Test.java index 92ab71d62..cec7009c8 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/Mpg123Test.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/Mpg123Test.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class Mpg123Test -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Mpg123 Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.Mpg123Test() ); +public class Mpg123Test { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Mpg123 Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.Mpg123Test()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/MultitouchTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/MultitouchTest.java index f98cf34d7..574a2a0f1 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/MultitouchTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/MultitouchTest.java @@ -1,12 +1,11 @@ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class MultitouchTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Multitouch Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.MultitouchTest() ); +public class MultitouchTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Multitouch Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.MultitouchTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/ObjTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/ObjTest.java index 7d99758bc..95f5241d8 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/ObjTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/ObjTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class ObjTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Obj Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.ObjTest() ); +public class ObjTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Obj Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.ObjTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/PerformanceTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/PerformanceTest.java index 772de7dcf..e00961529 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/PerformanceTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/PerformanceTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class PerformanceTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Performance Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.PerformanceTest() ); +public class PerformanceTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Performance Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.PerformanceTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/Pong.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/Pong.java index 3d2fded2c..272b880e2 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/Pong.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/Pong.java @@ -1,35 +1,30 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; /** - * A simple Pong remake showing how easy it is to quickly - * prototype a game with libgdx. + * A simple Pong remake showing how easy it is to quickly prototype a game with libgdx. * * @author mzechner - * + * */ -public class Pong -{ - public static void main( String[] argv ) - { +public class Pong { + public static void main (String[] argv) { // we create a new JoglApplication and register a new Pong instances as the RenderListener - JoglApplication app = new JoglApplication( "Pong", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.Pong() ); + JoglApplication app = new JoglApplication("Pong", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.Pong()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SimpleAudioRecorder.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SimpleAudioRecorder.java index 6a996f913..47cfd456e 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SimpleAudioRecorder.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SimpleAudioRecorder.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import javax.sound.sampled.LineUnavailableException; @@ -22,22 +20,16 @@ import com.badlogic.gdx.audio.AudioRecorder; import com.badlogic.gdx.backends.desktop.JoglAudioDevice; import com.badlogic.gdx.backends.desktop.JoglAudioRecorder; +public class SimpleAudioRecorder { + public static void main (String[] argv) throws LineUnavailableException { + AudioDevice device = new JoglAudioDevice(true); + AudioRecorder recorder = new JoglAudioRecorder(44100, true); + + short[] samples = new short[1024]; -public class SimpleAudioRecorder -{ - public static void main( String[] argv ) throws LineUnavailableException - { - AudioDevice device = new JoglAudioDevice( true ); - AudioRecorder recorder = new JoglAudioRecorder( 44100, true ); - - short[] samples = new short[1024]; - - while( true ) - { - recorder.read( samples, 0, samples.length ); - device.writeSamples(samples, 0, samples.length ); - } + while (true) { + recorder.read(samples, 0, samples.length); + device.writeSamples(samples, 0, samples.length); + } } } - - diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SimpleTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SimpleTest.java index 422028d0f..fec4b458b 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SimpleTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SimpleTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class SimpleTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Simple Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.SimpleTest() ); - } +public class SimpleTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Simple Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.SimpleTest()); + } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SkipTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SkipTest.java index d42b53f35..928c4106c 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SkipTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SkipTest.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import java.nio.ShortBuffer; @@ -20,30 +18,26 @@ import java.nio.ShortBuffer; import com.badlogic.gdx.audio.analysis.AudioTools; import com.badlogic.gdx.audio.io.Mpg123Decoder; -public class SkipTest -{ - public static void main( String[] argv ) - { - Mpg123Decoder decoder = new Mpg123Decoder( "data/threeofaperfectpair.mp3" ); - ShortBuffer samples = AudioTools.allocateShortBuffer( 512, decoder.getNumChannels() ); +public class SkipTest { + public static void main (String[] argv) { + Mpg123Decoder decoder = new Mpg123Decoder("data/threeofaperfectpair.mp3"); + ShortBuffer samples = AudioTools.allocateShortBuffer(512, decoder.getNumChannels()); int skipSamples = decoder.getRate() / 25; - int i = 0; - - while( decoder.readSamples( samples ) > 0 ) - { + int i = 0; + + while (decoder.readSamples(samples) > 0) { i++; - } + } decoder.dispose(); - System.out.println( i + " fetches"); - - i = 0; - decoder = new Mpg123Decoder( "data/threeofaperfectpair.mp3" ); - while( decoder.readSamples( samples ) > 0 ) - { - decoder.skipSamples( (skipSamples - 512) * decoder.getNumChannels() ); - + System.out.println(i + " fetches"); + + i = 0; + decoder = new Mpg123Decoder("data/threeofaperfectpair.mp3"); + while (decoder.readSamples(samples) > 0) { + decoder.skipSamples((skipSamples - 512) * decoder.getNumChannels()); + i++; } - decoder.dispose(); + decoder.dispose(); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SoundTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SoundTest.java index 1f8211214..f43a921e3 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SoundTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SoundTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class SoundTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Sound Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.SoundTest() ); +public class SoundTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Sound Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.SoundTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SpriteBatchRotationTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SpriteBatchRotationTest.java index b0f3d582c..96c23e7f9 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SpriteBatchRotationTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SpriteBatchRotationTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class SpriteBatchRotationTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "SpriteBatch Rotation Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.SpriteBatchRotationTest() ); +public class SpriteBatchRotationTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("SpriteBatch Rotation Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.SpriteBatchRotationTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SpriteBatchShaderTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SpriteBatchShaderTest.java index ca66df30c..a3ae18588 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SpriteBatchShaderTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SpriteBatchShaderTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class SpriteBatchShaderTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "SpriteBatch Shader Test", 480, 320, true ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.SpriteBatchShaderTest() ); +public class SpriteBatchShaderTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("SpriteBatch Shader Test", 480, 320, true); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.SpriteBatchShaderTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SpriteBatchTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SpriteBatchTest.java index 7aeb17fc6..8089dd9af 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SpriteBatchTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/SpriteBatchTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class SpriteBatchTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "SpriteBatch Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.SpriteBatchTest() ); +public class SpriteBatchTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("SpriteBatch Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.SpriteBatchTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/StageTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/StageTest.java index c9de9b5bf..ff021f48e 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/StageTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/StageTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class StageTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Stage Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.StageTest() ); +public class StageTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Stage Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.StageTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/TerrainTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/TerrainTest.java index 952fcfc7b..dab809a1c 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/TerrainTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/TerrainTest.java @@ -1,12 +1,12 @@ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; public class TerrainTest { - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Terrain Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.TerrainTest() ); + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Terrain Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.TerrainTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/TextTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/TextTest.java index 10f48938d..5becec38b 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/TextTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/TextTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class TextTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Text Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.TextTest() ); - } +public class TextTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Text Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.TextTest()); + } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/TextureRenderTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/TextureRenderTest.java index 20e5f53c9..fc2b88d72 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/TextureRenderTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/TextureRenderTest.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import java.util.ArrayList; @@ -30,147 +28,135 @@ import com.badlogic.gdx.graphics.VertexAttributes; public class TextureRenderTest implements RenderListener { - private OrthographicCamera camera; - private Mesh mesh; - private Texture texture; - - private ArrayList rects = new ArrayList(); - - - @Override - public void surfaceCreated( ) { - camera = new OrthographicCamera(); - camera.setViewport(480, 320); - camera.getPosition().set(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0); - - - texture = Gdx.graphics.newTexture(Gdx.files.getFileHandle("data/badlogic.jpg", Files.FileType.Internal), Texture.TextureFilter.Linear, Texture.TextureFilter.Linear, Texture.TextureWrap.ClampToEdge, Texture.TextureWrap.ClampToEdge); - - - float invTexWidth = 1.0f / texture.getWidth(); - float invTexHeight = 1.0f / texture.getHeight(); - - rects = createRects(); + private OrthographicCamera camera; + private Mesh mesh; + private Texture texture; - this.mesh = new Mesh( true, false, 4 * rects.size(), 12, - new VertexAttribute(VertexAttributes.Usage.Position, 2, "a_position"), - new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoord")); + private ArrayList rects = new ArrayList(); + @Override public void surfaceCreated () { + camera = new OrthographicCamera(); + camera.setViewport(480, 320); + camera.getPosition().set(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0); - final float[] vertices = new float[rects.size() * 16]; - int index = 0; + texture = Gdx.graphics.newTexture(Gdx.files.getFileHandle("data/badlogic.jpg", Files.FileType.Internal), + Texture.TextureFilter.Linear, Texture.TextureFilter.Linear, Texture.TextureWrap.ClampToEdge, + Texture.TextureWrap.ClampToEdge); - for (int i = 0; i < rects.size(); i++) { - SimpleRect rect = rects.get(i); + float invTexWidth = 1.0f / texture.getWidth(); + float invTexHeight = 1.0f / texture.getHeight(); + rects = createRects(); - float u = rect.x * invTexWidth; - float v = rect.y * invTexHeight; - float u2 = (rect.x + rect.width) * invTexWidth; - float v2 = (rect.y + rect.height) * invTexHeight; + this.mesh = new Mesh(true, false, 4 * rects.size(), 12, new VertexAttribute(VertexAttributes.Usage.Position, 2, + "a_position"), new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoord")); - float w = rect.width / 2; - float h = rect.height / 2; + final float[] vertices = new float[rects.size() * 16]; + int index = 0; - vertices[index++] = -w; - vertices[index++] = -h; - vertices[index++] = u; - vertices[index++] = v2; + for (int i = 0; i < rects.size(); i++) { + SimpleRect rect = rects.get(i); - vertices[index++] = w; - vertices[index++] = -h; - vertices[index++] = u2; - vertices[index++] = v2; + float u = rect.x * invTexWidth; + float v = rect.y * invTexHeight; + float u2 = (rect.x + rect.width) * invTexWidth; + float v2 = (rect.y + rect.height) * invTexHeight; - vertices[index++] = w; - vertices[index++] = h; - vertices[index++] = u2; - vertices[index++] = v; + float w = rect.width / 2; + float h = rect.height / 2; - vertices[index++] = -w; - vertices[index++] = h; - vertices[index++] = u; - vertices[index++] = v; + vertices[index++] = -w; + vertices[index++] = -h; + vertices[index++] = u; + vertices[index++] = v2; + vertices[index++] = w; + vertices[index++] = -h; + vertices[index++] = u2; + vertices[index++] = v2; - } - this.mesh.setVertices(vertices); - this.mesh.setIndices(new short[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}); + vertices[index++] = w; + vertices[index++] = h; + vertices[index++] = u2; + vertices[index++] = v; - } + vertices[index++] = -w; + vertices[index++] = h; + vertices[index++] = u; + vertices[index++] = v; - @Override - public void surfaceChanged(int width, int height) { + } + this.mesh.setVertices(vertices); + this.mesh.setIndices(new short[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}); - } + } - @Override - public void render( ) { + @Override public void surfaceChanged (int width, int height) { - GL10 gl = Gdx.graphics.getGL10(); - gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); - gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - gl.glEnable(GL10.GL_TEXTURE_2D); + } - camera.update(); + @Override public void render () { - gl.glMatrixMode(GL10.GL_PROJECTION); - gl.glLoadMatrixf(camera.getCombinedMatrix().val, 0); - gl.glMatrixMode(GL10.GL_MODELVIEW); + GL10 gl = Gdx.graphics.getGL10(); + gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + gl.glEnable(GL10.GL_TEXTURE_2D); - gl.glEnable(GL10.GL_BLEND); - gl.glBlendFunc(GL10.GL_ONE, GL10.GL_ONE); + camera.update(); - gl.glLoadIdentity(); + gl.glMatrixMode(GL10.GL_PROJECTION); + gl.glLoadMatrixf(camera.getCombinedMatrix().val, 0); + gl.glMatrixMode(GL10.GL_MODELVIEW); + gl.glEnable(GL10.GL_BLEND); + gl.glBlendFunc(GL10.GL_ONE, GL10.GL_ONE); - texture.bind(); + gl.glLoadIdentity(); - for (int i = 0; i < rects.size(); i++) { - SimpleRect rect = rects.get(i); + texture.bind(); - gl.glPushMatrix(); - gl.glTranslatef(rect.index * 100 + 50, 100, 0F); - mesh.render(GL10.GL_TRIANGLE_FAN, rect.index * 4, 4); - gl.glPopMatrix(); + for (int i = 0; i < rects.size(); i++) { + SimpleRect rect = rects.get(i); - } + gl.glPushMatrix(); + gl.glTranslatef(rect.index * 100 + 50, 100, 0F); + mesh.render(GL10.GL_TRIANGLE_FAN, rect.index * 4, 4); + gl.glPopMatrix(); - } + } - @Override - public void dispose( ) { + } - } + @Override public void dispose () { - private ArrayList createRects() { - ArrayList l = new ArrayList(); - l.add(new SimpleRect(0, 0, 0, 50, 50)); - l.add(new SimpleRect(1, 50, 0, 50, 50)); - l.add(new SimpleRect(2, 100, 0, 50, 50)); - return l; - } + } + private ArrayList createRects () { + ArrayList l = new ArrayList(); + l.add(new SimpleRect(0, 0, 0, 50, 50)); + l.add(new SimpleRect(1, 50, 0, 50, 50)); + l.add(new SimpleRect(2, 100, 0, 50, 50)); + return l; + } - private static class SimpleRect { - public int index; - public float x; - public float y; - public float height; - public float width; + private static class SimpleRect { + public int index; + public float x; + public float y; + public float height; + public float width; - private SimpleRect(int index, float x, float y, float width, float height) { - this.index = index; - this.x = x; - this.y = y; - this.height = height; - this.width = width; - } - } + private SimpleRect (int index, float x, float y, float width, float height) { + this.index = index; + this.x = x; + this.y = y; + this.height = height; + this.width = width; + } + } - public static void main( String[] argv ) - { - new JoglApplication("TextureRender Test", 480, 320, false ); - Gdx.graphics.setRenderListener( new TextureRenderTest() ); - } + public static void main (String[] argv) { + new JoglApplication("TextureRender Test", 480, 320, false); + Gdx.graphics.setRenderListener(new TextureRenderTest()); + } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/UITest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/UITest.java index a68e3bcfa..f77272676 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/UITest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/UITest.java @@ -1,12 +1,11 @@ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class UITest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "UI Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.UITest() ); +public class UITest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("UI Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.UITest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/VertexArrayTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/VertexArrayTest.java index f0151733f..cdb0cdfcc 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/VertexArrayTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/VertexArrayTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class VertexArrayTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "VA Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.VertexArrayTest() ); +public class VertexArrayTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("VA Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.VertexArrayTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/VertexBufferObjectTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/VertexBufferObjectTest.java index cd68cb9df..b6ff1ae12 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/VertexBufferObjectTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/VertexBufferObjectTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class VertexBufferObjectTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "VBO Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.VertexBufferObjectTest() ); +public class VertexBufferObjectTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("VBO Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.VertexBufferObjectTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/VorbisTest.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/VorbisTest.java index 2b83c0e11..73dca4492 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/VorbisTest.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/VorbisTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class VorbisTest -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Vorbis test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.VorbisTest() ); +public class VorbisTest { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Vorbis test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.VorbisTest()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/WaterRipples.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/WaterRipples.java index 8f37ec82d..578a777f0 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/WaterRipples.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/WaterRipples.java @@ -1,12 +1,11 @@ + package com.badlogic.gdx.tests.desktop; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class WaterRipples -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Water Ripples", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.WaterRipples() ); +public class WaterRipples { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Water Ripples", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.WaterRipples()); } } diff --git a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/box2d/TestCollection.java b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/box2d/TestCollection.java index 172d07f57..07ea43312 100644 --- a/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/box2d/TestCollection.java +++ b/tests/gdx-tests-desktop/src/com/badlogic/gdx/tests/desktop/box2d/TestCollection.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.desktop.box2d; import com.badlogic.gdx.backends.desktop.JoglApplication; -public class TestCollection -{ - public static void main( String[] argv ) - { - JoglApplication app = new JoglApplication( "Simple Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.box2d.TestCollection( ) ); +public class TestCollection { + public static void main (String[] argv) { + JoglApplication app = new JoglApplication("Simple Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.box2d.TestCollection()); } } diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/AlphaTest.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/AlphaTest.java index 8fe9886ec..024e88791 100644 --- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/AlphaTest.java +++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/AlphaTest.java @@ -1,12 +1,11 @@ + package com.badlogic.gdx.tests.lwjgl; import com.badlogic.gdx.backends.desktop.LwjglApplication; -public class AlphaTest -{ - public static void main( String[] argv ) - { - LwjglApplication app = new LwjglApplication( "Alpha Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.AlphaTest() ); +public class AlphaTest { + public static void main (String[] argv) { + LwjglApplication app = new LwjglApplication("Alpha Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.AlphaTest()); } } diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/BitmapFontTest.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/BitmapFontTest.java index ddb863cb4..fabfe0be1 100644 --- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/BitmapFontTest.java +++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/BitmapFontTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.lwjgl; import com.badlogic.gdx.backends.desktop.LwjglApplication; -public class BitmapFontTest -{ - public static void main( String[] argv ) - { - LwjglApplication app = new LwjglApplication( "BitmapFont Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.BitmapFontTest() ); - } +public class BitmapFontTest { + public static void main (String[] argv) { + LwjglApplication app = new LwjglApplication("BitmapFont Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.BitmapFontTest()); + } } diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/FrameBufferTest.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/FrameBufferTest.java index a1368761a..bb6112d32 100644 --- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/FrameBufferTest.java +++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/FrameBufferTest.java @@ -1,28 +1,24 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.lwjgl; import com.badlogic.gdx.backends.desktop.LwjglApplication; -public class FrameBufferTest -{ - public static void main( String[] argv ) - { - LwjglApplication app = new LwjglApplication( "FrameBuffer Test", 480, 320, true ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.FrameBufferTest() ); +public class FrameBufferTest { + public static void main (String[] argv) { + LwjglApplication app = new LwjglApplication("FrameBuffer Test", 480, 320, true); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.FrameBufferTest()); } } diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/MD5Test.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/MD5Test.java index df5eb7183..41719a286 100644 --- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/MD5Test.java +++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/MD5Test.java @@ -1,12 +1,11 @@ + package com.badlogic.gdx.tests.lwjgl; import com.badlogic.gdx.backends.desktop.LwjglApplication; -public class MD5Test -{ - public static void main( String[] argv ) - { - LwjglApplication app = new LwjglApplication( "MD5 Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.MD5Test() ); +public class MD5Test { + public static void main (String[] argv) { + LwjglApplication app = new LwjglApplication("MD5 Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.MD5Test()); } } diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/MeshShaderTest.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/MeshShaderTest.java index 155b77c8b..3e3ff0774 100644 --- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/MeshShaderTest.java +++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/MeshShaderTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.lwjgl; import com.badlogic.gdx.backends.desktop.LwjglApplication; -public class MeshShaderTest -{ - public static void main( String[] argv ) - { - LwjglApplication app = new LwjglApplication( "Mesh Test", 480, 320, true ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.MeshShaderTest() ); +public class MeshShaderTest { + public static void main (String[] argv) { + LwjglApplication app = new LwjglApplication("Mesh Test", 480, 320, true); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.MeshShaderTest()); } } diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/MeshTest.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/MeshTest.java index 04868f2a7..d5cc80b3a 100644 --- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/MeshTest.java +++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/MeshTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.lwjgl; import com.badlogic.gdx.backends.desktop.LwjglApplication; -public class MeshTest -{ - public static void main( String[] argv ) - { - LwjglApplication app = new LwjglApplication( "Mesh Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.MeshTest() ); +public class MeshTest { + public static void main (String[] argv) { + LwjglApplication app = new LwjglApplication("Mesh Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.MeshTest()); } } diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/ObjTest.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/ObjTest.java index cf07bc317..e81169d9b 100644 --- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/ObjTest.java +++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/ObjTest.java @@ -1,12 +1,11 @@ + package com.badlogic.gdx.tests.lwjgl; import com.badlogic.gdx.backends.desktop.LwjglApplication; -public class ObjTest -{ - public static void main( String[] argv ) - { - LwjglApplication app = new LwjglApplication( "Obj Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.ObjTest() ); +public class ObjTest { + public static void main (String[] argv) { + LwjglApplication app = new LwjglApplication("Obj Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.ObjTest()); } } diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/Pong.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/Pong.java index 43ea05409..b354a28ac 100644 --- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/Pong.java +++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/Pong.java @@ -1,12 +1,11 @@ + package com.badlogic.gdx.tests.lwjgl; import com.badlogic.gdx.backends.desktop.LwjglApplication; -public class Pong -{ - public static void main( String[] argv ) - { - LwjglApplication app = new LwjglApplication( "Pong", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.Pong() ); +public class Pong { + public static void main (String[] argv) { + LwjglApplication app = new LwjglApplication("Pong", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.Pong()); } } diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/SimpleTest.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/SimpleTest.java index 77290ef8a..dc2256a6a 100644 --- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/SimpleTest.java +++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/SimpleTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.lwjgl; import com.badlogic.gdx.backends.desktop.LwjglApplication; -public class SimpleTest -{ - public static void main( String[] argv ) - { - LwjglApplication app = new LwjglApplication( "Simple Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.SimpleTest() ); - } +public class SimpleTest { + public static void main (String[] argv) { + LwjglApplication app = new LwjglApplication("Simple Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.SimpleTest()); + } } diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/SpriteBatchRotationTest.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/SpriteBatchRotationTest.java index aadc26c30..4e51a6321 100644 --- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/SpriteBatchRotationTest.java +++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/SpriteBatchRotationTest.java @@ -1,12 +1,11 @@ + package com.badlogic.gdx.tests.lwjgl; import com.badlogic.gdx.backends.desktop.LwjglApplication; -public class SpriteBatchRotationTest -{ - public static void main( String[] argv ) - { - LwjglApplication app = new LwjglApplication( "SpriteBatch Rotation Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.SpriteBatchRotationTest() ); +public class SpriteBatchRotationTest { + public static void main (String[] argv) { + LwjglApplication app = new LwjglApplication("SpriteBatch Rotation Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.SpriteBatchRotationTest()); } } diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/SpriteBatchShaderTest.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/SpriteBatchShaderTest.java index 69c896ae0..9412b4219 100644 --- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/SpriteBatchShaderTest.java +++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/SpriteBatchShaderTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.lwjgl; import com.badlogic.gdx.backends.desktop.LwjglApplication; -public class SpriteBatchShaderTest -{ - public static void main( String[] argv ) - { - LwjglApplication app = new LwjglApplication( "SpriteBatch Shader Test", 480, 320, true ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.SpriteBatchShaderTest() ); +public class SpriteBatchShaderTest { + public static void main (String[] argv) { + LwjglApplication app = new LwjglApplication("SpriteBatch Shader Test", 480, 320, true); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.SpriteBatchShaderTest()); } } diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/SpriteBatchTest.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/SpriteBatchTest.java index d7cba3639..051f347e8 100644 --- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/SpriteBatchTest.java +++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/SpriteBatchTest.java @@ -1,12 +1,11 @@ + package com.badlogic.gdx.tests.lwjgl; import com.badlogic.gdx.backends.desktop.LwjglApplication; -public class SpriteBatchTest -{ - public static void main( String[] argv ) - { - LwjglApplication app = new LwjglApplication( "SpriteBatch Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.SpriteBatchTest() ); +public class SpriteBatchTest { + public static void main (String[] argv) { + LwjglApplication app = new LwjglApplication("SpriteBatch Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.SpriteBatchTest()); } -} \ No newline at end of file +} diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/StageTest.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/StageTest.java index 9f2bae251..6ed7995de 100644 --- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/StageTest.java +++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/StageTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.lwjgl; import com.badlogic.gdx.backends.desktop.LwjglApplication; -public class StageTest -{ - public static void main( String[] argv ) - { - LwjglApplication app = new LwjglApplication( "Stage Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.StageTest() ); +public class StageTest { + public static void main (String[] argv) { + LwjglApplication app = new LwjglApplication("Stage Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.StageTest()); } } diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/TerrainTest.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/TerrainTest.java index ffaead4e8..7894ddf0c 100644 --- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/TerrainTest.java +++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/TerrainTest.java @@ -1,12 +1,11 @@ + package com.badlogic.gdx.tests.lwjgl; import com.badlogic.gdx.backends.desktop.LwjglApplication; -public class TerrainTest -{ - public static void main( String[] argv ) - { - LwjglApplication app = new LwjglApplication( "Terrain Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.TerrainTest() ); +public class TerrainTest { + public static void main (String[] argv) { + LwjglApplication app = new LwjglApplication("Terrain Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.TerrainTest()); } } diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/TextTest.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/TextTest.java index ab13ea2a7..2d1ca19fd 100644 --- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/TextTest.java +++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/TextTest.java @@ -1,12 +1,11 @@ + package com.badlogic.gdx.tests.lwjgl; import com.badlogic.gdx.backends.desktop.LwjglApplication; -public class TextTest -{ - public static void main( String[] argv ) - { - LwjglApplication app = new LwjglApplication( "Text Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.TextTest() ); +public class TextTest { + public static void main (String[] argv) { + LwjglApplication app = new LwjglApplication("Text Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.TextTest()); } } diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/UITest.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/UITest.java index 929c5a80e..caee9a71a 100644 --- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/UITest.java +++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/UITest.java @@ -1,12 +1,11 @@ + package com.badlogic.gdx.tests.lwjgl; import com.badlogic.gdx.backends.desktop.LwjglApplication; -public class UITest -{ - public static void main( String[] argv ) - { - LwjglApplication app = new LwjglApplication( "UI Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.UITest() ); +public class UITest { + public static void main (String[] argv) { + LwjglApplication app = new LwjglApplication("UI Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.UITest()); } } diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/VertexArrayTest.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/VertexArrayTest.java index b3f2cfd1a..b1efc7143 100644 --- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/VertexArrayTest.java +++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/VertexArrayTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.lwjgl; import com.badlogic.gdx.backends.desktop.LwjglApplication; -public class VertexArrayTest -{ - public static void main( String[] argv ) - { - LwjglApplication app = new LwjglApplication( "VA Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.VertexArrayTest() ); +public class VertexArrayTest { + public static void main (String[] argv) { + LwjglApplication app = new LwjglApplication("VA Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.VertexArrayTest()); } } diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/VertexBufferObjectTest.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/VertexBufferObjectTest.java index e8ad7225e..44fcfa943 100644 --- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/VertexBufferObjectTest.java +++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/VertexBufferObjectTest.java @@ -1,27 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.lwjgl; import com.badlogic.gdx.backends.desktop.LwjglApplication; -public class VertexBufferObjectTest -{ - public static void main( String[] argv ) - { - LwjglApplication app = new LwjglApplication( "VBO Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.VertexBufferObjectTest() ); +public class VertexBufferObjectTest { + public static void main (String[] argv) { + LwjglApplication app = new LwjglApplication("VBO Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.VertexBufferObjectTest()); } } diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/WaterRipples.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/WaterRipples.java index 11ffa426c..610e3287f 100644 --- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/WaterRipples.java +++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/WaterRipples.java @@ -1,12 +1,11 @@ + package com.badlogic.gdx.tests.lwjgl; import com.badlogic.gdx.backends.desktop.LwjglApplication; -public class WaterRipples -{ - public static void main( String[] argv ) - { - LwjglApplication app = new LwjglApplication( "Water Ripples", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.WaterRipples() ); +public class WaterRipples { + public static void main (String[] argv) { + LwjglApplication app = new LwjglApplication("Water Ripples", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.WaterRipples()); } } diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/box2d/TestCollection.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/box2d/TestCollection.java index 15fa67283..b84671b02 100644 --- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/box2d/TestCollection.java +++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/box2d/TestCollection.java @@ -1,28 +1,23 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.lwjgl.box2d; import com.badlogic.gdx.backends.desktop.LwjglApplication; - -public class TestCollection -{ - public static void main( String[] argv ) - { - LwjglApplication app = new LwjglApplication( "Simple Test", 480, 320, false ); - app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.box2d.TestCollection( ) ); +public class TestCollection { + public static void main (String[] argv) { + LwjglApplication app = new LwjglApplication("Simple Test", 480, 320, false); + app.getGraphics().setRenderListener(new com.badlogic.gdx.tests.box2d.TestCollection()); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/AlphaTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/AlphaTest.java index 870f6a76d..3dd6600a9 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/AlphaTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/AlphaTest.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -5,49 +6,41 @@ import com.badlogic.gdx.RenderListener; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Pixmap; +import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.SpriteBatch; import com.badlogic.gdx.graphics.Texture; -import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; -public class AlphaTest implements RenderListener -{ +public class AlphaTest implements RenderListener { SpriteBatch batch; Texture texture; - - @Override - public void dispose() - { - + + @Override public void dispose () { + } - @Override - public void render() { - Gdx.graphics.getGL10().glClear( GL10.GL_COLOR_BUFFER_BIT ); - + @Override public void render () { + Gdx.graphics.getGL10().glClear(GL10.GL_COLOR_BUFFER_BIT); + batch.begin(); -// batch.disableBlending(); - batch.draw( texture, 0, 0, 256, 256, 0, 0, 256, 256, Color.WHITE, false, false ); +// batch.disableBlending(); + batch.draw(texture, 0, 0, 256, 256, 0, 0, 256, 256, Color.WHITE, false, false); batch.end(); } - @Override - public void surfaceChanged(int width, int height) { + @Override public void surfaceChanged (int width, int height) { // TODO Auto-generated method stub - + } - @Override - public void surfaceCreated() - { - Pixmap pixmap = Gdx.graphics.newPixmap( 256, 256, Format.RGBA8888 ); - pixmap.setColor( 1, 0, 0, 0.7f ); + @Override public void surfaceCreated () { + Pixmap pixmap = Gdx.graphics.newPixmap(256, 256, Format.RGBA8888); + pixmap.setColor(1, 0, 0, 0.7f); pixmap.fill(); - - texture = Gdx.graphics.newUnmanagedTexture( pixmap, TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); + + texture = Gdx.graphics.newUnmanagedTexture(pixmap, TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, + TextureWrap.ClampToEdge); batch = new SpriteBatch(); } } - - diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/AudioDeviceTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/AudioDeviceTest.java index 1522640a0..17e791a33 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/AudioDeviceTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/AudioDeviceTest.java @@ -1,31 +1,27 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.RenderListener; import com.badlogic.gdx.audio.AudioDevice; -public class AudioDeviceTest implements RenderListener -{ +public class AudioDeviceTest implements RenderListener { Thread thread; boolean stop = false; - - @Override - public void dispose() { + + @Override public void dispose () { stop = true; try { thread.join(); @@ -35,47 +31,38 @@ public class AudioDeviceTest implements RenderListener } } - @Override - public void render() { + @Override public void render () { // TODO Auto-generated method stub - + } - @Override - public void surfaceChanged(int width, int height) { + @Override public void surfaceChanged (int width, int height) { // TODO Auto-generated method stub - + } - @Override - public void surfaceCreated() - { - if( thread == null ) - { - final AudioDevice device = Gdx.app.getAudio().newAudioDevice( false ); - thread = new Thread( new Runnable() { - @Override - public void run() - { + @Override public void surfaceCreated () { + if (thread == null) { + final AudioDevice device = Gdx.app.getAudio().newAudioDevice(false); + thread = new Thread(new Runnable() { + @Override public void run () { final float frequency = 440; - float increment = (float)(2*Math.PI) * frequency / 44100; // angular increment for each sample - float angle = 0; - float samples[] = new float[1024]; - - while( !stop ) - { - for( int i = 0; i < samples.length; i+=2 ) - { - samples[i] = 0.5f * (float)Math.sin( angle ); - samples[i+1] = 2 * samples[i]; - angle += increment; - } - - device.writeSamples( samples, 0, samples.length ); - } - - device.dispose(); - } + float increment = (float)(2 * Math.PI) * frequency / 44100; // angular increment for each sample + float angle = 0; + float samples[] = new float[1024]; + + while (!stop) { + for (int i = 0; i < samples.length; i += 2) { + samples[i] = 0.5f * (float)Math.sin(angle); + samples[i + 1] = 2 * samples[i]; + angle += increment; + } + + device.writeSamples(samples, 0, samples.length); + } + + device.dispose(); + } }); thread.start(); } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/AudioRecorderTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/AudioRecorderTest.java index ddb95cf8b..c38501b02 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/AudioRecorderTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/AudioRecorderTest.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.ApplicationListener; @@ -23,81 +21,65 @@ import com.badlogic.gdx.audio.AudioRecorder; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.ImmediateModeRenderer; -public class AudioRecorderTest implements RenderListener, ApplicationListener -{ - short[] samples = new short[1024*4]; +public class AudioRecorderTest implements RenderListener, ApplicationListener { + short[] samples = new short[1024 * 4]; AudioDevice device; AudioRecorder recorder; ImmediateModeRenderer renderer; - - @Override - public void dispose() - { - + + @Override public void dispose () { + } - @Override - public void render() - { + @Override public void render () { GL10 gl = Gdx.graphics.getGL10(); - gl.glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - gl.glClear( GL10.GL_COLOR_BUFFER_BIT ); - -// float incX = 2.0f / samples.length; -// float x = -1; -// renderer.begin( GL10.GL_LINE_STRIP ); -// for( int i = 0; i < samples.length/100; i++, x+=incX ) -// renderer.vertex( x, samples[i] / (float)Short.MAX_VALUE, 0 ); -// renderer.end(); + gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + +// float incX = 2.0f / samples.length; +// float x = -1; +// renderer.begin( GL10.GL_LINE_STRIP ); +// for( int i = 0; i < samples.length/100; i++, x+=incX ) +// renderer.vertex( x, samples[i] / (float)Short.MAX_VALUE, 0 ); +// renderer.end(); } - @Override - public void surfaceChanged( int width, int height) - { - + @Override public void surfaceChanged (int width, int height) { + } - @Override - public void surfaceCreated() - { + @Override public void surfaceCreated () { device = Gdx.audio.newAudioDevice(true); - recorder = Gdx.audio.newAudioRecoder( 44100, true ); - renderer = new ImmediateModeRenderer( ); - - Thread t = new Thread( new Runnable() { - - @Override - public void run() { - while( true ) - { - recorder.read( samples, 0, samples.length ); - device.writeSamples( samples, 0, samples.length ); - } - } + recorder = Gdx.audio.newAudioRecoder(44100, true); + renderer = new ImmediateModeRenderer(); + + Thread t = new Thread(new Runnable() { + + @Override public void run () { + while (true) { + recorder.read(samples, 0, samples.length); + device.writeSamples(samples, 0, samples.length); + } + } }); - t.setDaemon( true ); + t.setDaemon(true); t.start(); - - Gdx.app.setApplicationListener( this ); + + Gdx.app.setApplicationListener(this); } - @Override - public void destroy() { + @Override public void destroy () { // TODO Auto-generated method stub - + } - @Override - public void pause() - { + @Override public void pause () { device.dispose(); recorder.dispose(); } - @Override - public void resume() - { + @Override public void resume () { device = Gdx.audio.newAudioDevice(true); - recorder = Gdx.audio.newAudioRecoder( 44100, true ); - } + recorder = Gdx.audio.newAudioRecoder(44100, true); + } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/BitmapFontTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/BitmapFontTest.java index 8f207c0e9..cfc2a1724 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/BitmapFontTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/BitmapFontTest.java @@ -11,7 +11,6 @@ import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Sprite; import com.badlogic.gdx.graphics.SpriteBatch; -import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; @@ -40,11 +39,11 @@ public class BitmapFontTest implements RenderListener { return false; } }); - cache1 = font.newCache( ); - cache2 = font.newCache( ); - cache3 = font.newCache( ); - cache4 = font.newCache( ); - + cache1 = font.newCache(); + cache2 = font.newCache(); + cache3 = font.newCache(); + cache4 = font.newCache(); + font.cacheText(cache1, "(cached)", 10, 76, Color.WHITE); String text = "Sphinx of black quartz,\njudge my vow."; diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/Box2DTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/Box2DTest.java index 8b490310e..6748f80eb 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/Box2DTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/Box2DTest.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.util.ArrayList; @@ -22,14 +20,15 @@ import com.badlogic.gdx.InputListener; import com.badlogic.gdx.RenderListener; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Font; +import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.ImmediateModeRenderer; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.SpriteBatch; -import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; +import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.Contact; import com.badlogic.gdx.physics.box2d.Fixture; import com.badlogic.gdx.physics.box2d.FixtureDef; @@ -37,341 +36,302 @@ import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.QueryCallback; import com.badlogic.gdx.physics.box2d.World; import com.badlogic.gdx.physics.box2d.WorldManifold; -import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.joints.MouseJoint; import com.badlogic.gdx.physics.box2d.joints.MouseJointDef; -public class Box2DTest implements RenderListener, InputListener -{ +public class Box2DTest implements RenderListener, InputListener { /** the camera **/ private OrthographicCamera camera; - + /** the immediate mode renderer to output our debug drawings **/ private ImmediateModeRenderer renderer; - + /** a spritebatch and a font for text rendering **/ private SpriteBatch batch; private Font font; - + /** our box2D world **/ - private World world; - + private World world; + /** our boxes **/ - private ArrayList boxes = new ArrayList( ); - + private ArrayList boxes = new ArrayList(); + /** our ground box **/ private Body groundBody; - + /** our mouse joint **/ private MouseJoint mouseJoint = null; - + /** a hit body **/ private Body hitBody = null; - - @Override - public void surfaceCreated() - { - // setup the camera. In Box2D we operate on a + @Override public void surfaceCreated () { + // setup the camera. In Box2D we operate on a // meter scale, pixels won't do it. So we use // an orthographic camera with a viewport of // 48 meters in width and 32 meters in height. - // We also position the camera so that it + // We also position the camera so that it // looks at (0,16) (that's where the middle of the // screen will be located). camera = new OrthographicCamera(); - camera.setViewport( 48, 32 ); - camera.getPosition().set( 0, 16, 0 ); - + camera.setViewport(48, 32); + camera.getPosition().set(0, 16, 0); + // next we setup the immediate mode renderer renderer = new ImmediateModeRenderer(); - + // next we create a SpriteBatch and a font batch = new SpriteBatch(); - font = Gdx.graphics.newFont( "Arial", 12, FontStyle.Plain ); - + font = Gdx.graphics.newFont("Arial", 12, FontStyle.Plain); + // next we create out physics world. - createPhysicsWorld( ); - + createPhysicsWorld(); + // finally we register ourselfs as an InputListener so we // can manipulate our world - Gdx.input.addInputListener( this ); + Gdx.input.addInputListener(this); } - - private void createPhysicsWorld( ) - { + + private void createPhysicsWorld () { // we instantiate a new World with a proper gravity vector - // and tell it to sleep when possible. - world = new World( new Vector2( 0, -10 ), true ); - + // and tell it to sleep when possible. + world = new World(new Vector2(0, -10), true); + // next we create a static ground platform. This platform // is not moveable and will not react to any influences from // outside. It will however influence other bodies. First we // create a PolygonShape that holds the form of the platform. // it will be 100 meters wide and 2 meters high, centered // around the origin - PolygonShape groundPoly = new PolygonShape( ); - groundPoly.setAsBox( 50, 1 ); - + PolygonShape groundPoly = new PolygonShape(); + groundPoly.setAsBox(50, 1); + // next we create the body for the ground platform. It's // simply a static body. BodyDef groundBodyDef = new BodyDef(); groundBodyDef.type = BodyType.StaticBody; - groundBody = world.createBody( groundBodyDef ); - + groundBody = world.createBody(groundBodyDef); + // finally we add a fixture to the body using the polygon // defined above. Note that we have to dispose PolygonShapes // and CircleShapes once they are no longer used. This is the // only time you have to care explicitely for memomry managment. - FixtureDef fixtureDef = new FixtureDef( ); + FixtureDef fixtureDef = new FixtureDef(); fixtureDef.shape = groundPoly; fixtureDef.filter.groupIndex = 0; - groundBody.createFixture( fixtureDef ); + groundBody.createFixture(fixtureDef); groundPoly.dispose(); - - createBoxes( ); + + createBoxes(); } - - private void createBoxes( ) - { + + private void createBoxes () { // next we create 50 boxes at random locations above the ground // body. First we create a nice polygon representing a box 2 meters // wide and high. - PolygonShape boxPoly = new PolygonShape( ); - boxPoly.setAsBox( 1, 1 ); - + PolygonShape boxPoly = new PolygonShape(); + boxPoly.setAsBox(1, 1); + // next we create the 50 box bodies using the PolygonShape we just // defined. This process is similar to the one we used for the ground // body. Note that we reuse the polygon for each body fixture. - for( int i = 0; i < 20; i++ ) - { - // Create the BodyDef, set a random position above the + for (int i = 0; i < 20; i++) { + // Create the BodyDef, set a random position above the // ground and create a new body - BodyDef boxBodyDef = new BodyDef( ); + BodyDef boxBodyDef = new BodyDef(); boxBodyDef.type = BodyType.DynamicBody; boxBodyDef.position.x = -24 + (float)(Math.random() * 48); - boxBodyDef.position.y = 10 + (float)(Math.random() * 100); - Body boxBody = world.createBody( boxBodyDef ); - + boxBodyDef.position.y = 10 + (float)(Math.random() * 100); + Body boxBody = world.createBody(boxBodyDef); + // add the boxPoly shape as a fixture - FixtureDef fixtureDef = new FixtureDef( ); - fixtureDef.shape = boxPoly; - boxBody.createFixture( fixtureDef ); - + FixtureDef fixtureDef = new FixtureDef(); + fixtureDef.shape = boxPoly; + boxBody.createFixture(fixtureDef); + // add the box to our list of boxes - boxes.add( boxBody ); + boxes.add(boxBody); } - + // we are done, all that's left is disposing the boxPoly boxPoly.dispose(); } - - @Override - public void render() - { + + @Override public void render () { // first we update the world. For simplicity // we use the delta time provided by the Graphics // instance. Normally you'll want to fix the time // step. long start = System.nanoTime(); - world.step( Gdx.graphics.getDeltaTime(), 3, 3 ); + world.step(Gdx.graphics.getDeltaTime(), 3, 3); float updateTime = (System.nanoTime() - start) / 1000000000.0f; - + // next we clear the color buffer and set the camera // matrices GL10 gl = Gdx.graphics.getGL10(); - gl.glClear( GL10.GL_COLOR_BUFFER_BIT ); - camera.setMatrices( ); - + gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + camera.setMatrices(); + // next we render the ground body - renderBox( gl, groundBody, 50, 1 ); - + renderBox(gl, groundBody, 50, 1); + // next we render each box via the ImmediateModeRenderer // we instantiated previously - for( int i = 0; i < boxes.size(); i++ ) - { + for (int i = 0; i < boxes.size(); i++) { Body box = boxes.get(i); - renderBox( gl, box, 1, 1 ); + renderBox(gl, box, 1, 1); } - + // finally we render all contact points - gl.glPointSize( 4 ); - renderer.begin( GL10.GL_POINTS ); - for( int i = 0; i < world.getContactCount(); i++ ) - { + gl.glPointSize(4); + renderer.begin(GL10.GL_POINTS); + for (int i = 0; i < world.getContactCount(); i++) { Contact contact = world.getContactList().get(i); // we only render the contact if it actually touches - if( contact.isTouching() ) - { + if (contact.isTouching()) { // get the world manifold from which we get the // contact points. A manifold can have 0, 1 or 2 - // contact points. + // contact points. WorldManifold manifold = contact.GetWorldManifold(); int numContactPoints = manifold.getNumberOfContactPoints(); - for( int j = 0; j < numContactPoints; j++ ) - { + for (int j = 0; j < numContactPoints; j++) { Vector2 point = manifold.getPoints()[j]; - renderer.color( 0, 1, 0, 1 ); - renderer.vertex( point.x, point.y, 0 ); + renderer.color(0, 1, 0, 1); + renderer.vertex(point.x, point.y, 0); } } } renderer.end(); gl.glPointSize(1); - + // finally we render the time it took to update the world batch.begin(); - batch.drawText( font, "fps: " + Gdx.graphics.getFramesPerSecond() + " update time: " + updateTime, 0, Gdx.graphics.getHeight(), Color.RED ); + batch.drawText(font, "fps: " + Gdx.graphics.getFramesPerSecond() + " update time: " + updateTime, 0, + Gdx.graphics.getHeight(), Color.RED); batch.end(); } - - private void renderBox( GL10 gl, Body body, float halfWidth, float halfHeight ) - { + + private void renderBox (GL10 gl, Body body, float halfWidth, float halfHeight) { // push the current matrix and // get the bodies center and angle in world coordinates gl.glPushMatrix(); Vector2 pos = body.getWorldCenter(); float angle = body.getAngle(); - + // set the translation and rotation matrix - gl.glTranslatef(pos.x, pos.y, 0 ); - gl.glRotatef( (float)Math.toDegrees(angle), 0, 0, 1 ); - + gl.glTranslatef(pos.x, pos.y, 0); + gl.glRotatef((float)Math.toDegrees(angle), 0, 0, 1); + // render the box - renderer.begin( GL10.GL_LINE_STRIP ); - renderer.color( 1, 1, 1, 1 ); - renderer.vertex( -halfWidth, -halfHeight, 0 ); - renderer.color( 1, 1, 1, 1 ); - renderer.vertex( -halfWidth, halfHeight, 0 ); - renderer.color( 1, 1, 1, 1 ); - renderer.vertex( halfWidth, halfHeight, 0 ); - renderer.color( 1, 1, 1, 1 ); - renderer.vertex( halfWidth, -halfHeight, 0 ); - renderer.color( 1, 1, 1, 1 ); - renderer.vertex( -halfWidth, -halfHeight, 0 ); + renderer.begin(GL10.GL_LINE_STRIP); + renderer.color(1, 1, 1, 1); + renderer.vertex(-halfWidth, -halfHeight, 0); + renderer.color(1, 1, 1, 1); + renderer.vertex(-halfWidth, halfHeight, 0); + renderer.color(1, 1, 1, 1); + renderer.vertex(halfWidth, halfHeight, 0); + renderer.color(1, 1, 1, 1); + renderer.vertex(halfWidth, -halfHeight, 0); + renderer.color(1, 1, 1, 1); + renderer.vertex(-halfWidth, -halfHeight, 0); renderer.end(); - + // pop the matrix - gl.glPopMatrix(); + gl.glPopMatrix(); } - + /** we instantiate this vector and the callback here so we don't irritate the GC **/ - Vector2 testPoint = new Vector2( ); - QueryCallback callback = new QueryCallback() { - @Override - public boolean reportFixture(Fixture fixture) - { + Vector2 testPoint = new Vector2(); + QueryCallback callback = new QueryCallback() { + @Override public boolean reportFixture (Fixture fixture) { // if the hit fixture's body is the ground body // we ignore it - if( fixture.getBody() == groundBody ) - return true; - + if (fixture.getBody() == groundBody) return true; + // if the hit point is inside the fixture of the body // we report it - if( fixture.testPoint( testPoint ) ) - { + if (fixture.testPoint(testPoint)) { hitBody = fixture.getBody(); return false; - } - else + } else return true; } }; - - @Override - public boolean touchDown(int x, int y, int pointer) - { + + @Override public boolean touchDown (int x, int y, int pointer) { // translate the mouse coordinates to world coordinates - camera.getScreenToWorld( x, y, testPoint ); - // ask the world which bodies are within the given + camera.getScreenToWorld(x, y, testPoint); + // ask the world which bodies are within the given // bounding box around the mouse pointer hitBody = null; - world.QueryAABB( callback, testPoint.x - 0.1f, testPoint.y - 0.1f, testPoint.x + 0.1f, testPoint.y + 0.1f ); - + world.QueryAABB(callback, testPoint.x - 0.1f, testPoint.y - 0.1f, testPoint.x + 0.1f, testPoint.y + 0.1f); + // if we hit something we create a new mouse joint - // and attach it to the hit body. - if( hitBody != null ) - { + // and attach it to the hit body. + if (hitBody != null) { MouseJointDef def = new MouseJointDef(); def.bodyA = groundBody; def.bodyB = hitBody; def.collideConnected = true; - def.target.set( testPoint ); + def.target.set(testPoint); def.maxForce = 1000.0f * hitBody.getMass(); - - mouseJoint = (MouseJoint)world.createJoint( def ); + + mouseJoint = (MouseJoint)world.createJoint(def); hitBody.setAwake(true); - } - else - { - for( Body box: boxes ) - world.destroyBody( box ); + } else { + for (Body box : boxes) + world.destroyBody(box); boxes.clear(); createBoxes(); } - + return false; } /** another temporary vector **/ - Vector2 target = new Vector2( ); - @Override - public boolean touchDragged(int x, int y, int pointer) - { + Vector2 target = new Vector2(); + + @Override public boolean touchDragged (int x, int y, int pointer) { // if a mouse joint exists we simply update // the target of the joint based on the new // mouse coordinates - if( mouseJoint != null ) - { - camera.getScreenToWorld( x, y, target ); - mouseJoint.setTarget( target ); + if (mouseJoint != null) { + camera.getScreenToWorld(x, y, target); + mouseJoint.setTarget(target); } - return false; + return false; } - @Override - public boolean touchUp(int x, int y, int pointer) - { + @Override public boolean touchUp (int x, int y, int pointer) { // if a mouse joint exists we simply destroy it - if( mouseJoint != null ) - { + if (mouseJoint != null) { world.destroyJoint(mouseJoint); mouseJoint = null; } return false; } - //--------------------------------------------------------------- - // STUBS FOR UNIMPLEMENTED INTERFACE METHODS, NOTHING TO SEE HERE + // --------------------------------------------------------------- + // STUBS FOR UNIMPLEMENTED INTERFACE METHODS, NOTHING TO SEE HERE // MOVE ALONG - //--------------------------------------------------------------- - @Override - public void surfaceChanged( int width, int height) - { - + // --------------------------------------------------------------- + @Override public void surfaceChanged (int width, int height) { + } - - @Override - public void dispose( ) - { + + @Override public void dispose () { world.dispose(); } - @Override - public boolean keyDown(int keycode) - { + @Override public boolean keyDown (int keycode) { return false; } - @Override - public boolean keyTyped(char character) - { + @Override public boolean keyTyped (char character) { return false; } - @Override - public boolean keyUp(int keycode) - { + @Override public boolean keyUp (int keycode) { return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/DualThreadTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/DualThreadTest.java index c3ad48e1a..2fbcfc36a 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/DualThreadTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/DualThreadTest.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.tests; import com.badlogic.gdx.ApplicationListener; @@ -6,99 +7,75 @@ import com.badlogic.gdx.InputListener; import com.badlogic.gdx.RenderListener; import com.badlogic.gdx.utils.PauseableThread; -public class DualThreadTest implements ApplicationListener, RenderListener, InputListener -{ +public class DualThreadTest implements ApplicationListener, RenderListener, InputListener { PauseableThread gameLoop; - - @Override - public void surfaceCreated() - { - Gdx.input.addInputListener( this ); - - if( gameLoop == null ) - { - gameLoop = new PauseableThread( new Runnable() { - - @Override - public void run() { - System.out.println( "working my ass off! " + System.nanoTime() ); + + @Override public void surfaceCreated () { + Gdx.input.addInputListener(this); + + if (gameLoop == null) { + gameLoop = new PauseableThread(new Runnable() { + + @Override public void run () { + System.out.println("working my ass off! " + System.nanoTime()); } - + }); gameLoop.start(); } } - - @Override - public void destroy() - { + + @Override public void destroy () { gameLoop.stopThread(); } - @Override - public void pause() - { + @Override public void pause () { gameLoop.onPause(); } - @Override - public void resume() - { + @Override public void resume () { gameLoop.onResume(); } - @Override - public void dispose() - { - + @Override public void dispose () { + } - @Override - public void render() - { - + @Override public void render () { + } - @Override - public void surfaceChanged(int width, int height) - { - + @Override public void surfaceChanged (int width, int height) { + } - @Override - public boolean keyDown(int keycode) { + @Override public boolean keyDown (int keycode) { // TODO Auto-generated method stub return false; } - @Override - public boolean keyTyped(char character) { + @Override public boolean keyTyped (char character) { // TODO Auto-generated method stub return false; } - @Override - public boolean keyUp(int keycode) { + @Override public boolean keyUp (int keycode) { // TODO Auto-generated method stub return false; } - @Override - public boolean touchDown(int x, int y, int pointer) { + @Override public boolean touchDown (int x, int y, int pointer) { // TODO Auto-generated method stub return false; } - @Override - public boolean touchDragged(int x, int y, int pointer) { + @Override public boolean touchDragged (int x, int y, int pointer) { // TODO Auto-generated method stub return false; } - @Override - public boolean touchUp(int x, int y, int pointer) - { - if( gameLoop.isPaused() ) + @Override public boolean touchUp (int x, int y, int pointer) { + if (gameLoop.isPaused()) gameLoop.onResume(); else gameLoop.onPause(); diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/FFTTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/FFTTest.java index 8b192ad8f..40c218d16 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/FFTTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/FFTTest.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.nio.FloatBuffer; @@ -23,84 +21,73 @@ import com.badlogic.gdx.audio.analysis.AudioTools; import com.badlogic.gdx.audio.analysis.FFT; import com.badlogic.gdx.audio.analysis.KissFFT; -public class FFTTest -{ +public class FFTTest { static int SAMPLES = 256; - - public static void main( String[] argv ) - { + + public static void main (String[] argv) { float[] samples = new float[SAMPLES]; - ShortBuffer shortSamples = AudioTools.allocateShortBuffer( SAMPLES, 1 ); - -// createFlat( samples, shortSamples ); + ShortBuffer shortSamples = AudioTools.allocateShortBuffer(SAMPLES, 1); + +// createFlat( samples, shortSamples ); createSine(samples, shortSamples); - analyse( samples, shortSamples ); + analyse(samples, shortSamples); } - - private static void analyse( float samples[], ShortBuffer shortSamples ) - { - FFT fft = new FFT( SAMPLES, 44100 ); - KissFFT kfft = new KissFFT( SAMPLES ); - fft.forward( samples ); + + private static void analyse (float samples[], ShortBuffer shortSamples) { + FFT fft = new FFT(SAMPLES, 44100); + KissFFT kfft = new KissFFT(SAMPLES); + fft.forward(samples); float[] spectrum = fft.getSpectrum(); - FloatBuffer floatSpectrum = AudioTools.allocateFloatBuffer( SAMPLES / 2 + 1, 1 ); - - System.out.println(Arrays.toString( spectrum ) ); - - System.out.print( "[" ); - kfft.spectrum( shortSamples, floatSpectrum); - for( int i = 0; i < SAMPLES / 2 + 1; i++ ) - System.out.print( floatSpectrum.get( i ) + ", " ); - System.out.println( "]" ); - - System.out.println( sum( samples ) / SAMPLES ); -// System.out.println( sum( spectrum ) ); -// System.out.println( sum( floatSpectrum )); + FloatBuffer floatSpectrum = AudioTools.allocateFloatBuffer(SAMPLES / 2 + 1, 1); + + System.out.println(Arrays.toString(spectrum)); + + System.out.print("["); + kfft.spectrum(shortSamples, floatSpectrum); + for (int i = 0; i < SAMPLES / 2 + 1; i++) + System.out.print(floatSpectrum.get(i) + ", "); + System.out.println("]"); + + System.out.println(sum(samples) / SAMPLES); +// System.out.println( sum( spectrum ) ); +// System.out.println( sum( floatSpectrum )); kfft.dispose(); - } - - private static float sum( float samples[] ) - { + } + + private static float sum (float samples[]) { float sum = 0; - for( int i = 1; i < samples.length; i++) - sum+=samples[i]; + for (int i = 1; i < samples.length; i++) + sum += samples[i]; return sum; } - - @SuppressWarnings("unused") - private static float sum( FloatBuffer buffer ) - { + + @SuppressWarnings("unused") private static float sum (FloatBuffer buffer) { float sum = 0; - for( int i = 1; i < SAMPLES / 2 + 1; i++ ) + for (int i = 1; i < SAMPLES / 2 + 1; i++) sum += buffer.get(i) * 2 / SAMPLES; return sum; } - - @SuppressWarnings("unused") - private static void createFlat( float samples[], ShortBuffer shortSamples ) - { - for( int i = 0; i < samples.length; i++ ) - { + + @SuppressWarnings("unused") private static void createFlat (float samples[], ShortBuffer shortSamples) { + for (int i = 0; i < samples.length; i++) { samples[i] = 1; - shortSamples.put( Short.MAX_VALUE ); + shortSamples.put(Short.MAX_VALUE); } } - - private static void createSine( float samples[], ShortBuffer shortSamples ) - { + + private static void createSine (float samples[], ShortBuffer shortSamples) { final float frequency = 44100 / (SAMPLES / 2); - float increment = (float)(2*Math.PI) * frequency / 44100; // angular increment for each sample - float angle = 0; - final float frequency2 = 44100 / (SAMPLES / 2) * 4; - float increment2 = (float)(2*Math.PI) * frequency2 / 44100; - float angle2 = 0; - - for( int i = 0; i < samples.length; i++ ) - { - samples[i] = Math.max(0, Math.min((float)Math.sin( angle ) + (float)Math.sin(angle2), 1)); - shortSamples.put( (short)(Short.MAX_VALUE * samples[i]) ); - angle += increment; - angle2 += increment2; - } + float increment = (float)(2 * Math.PI) * frequency / 44100; // angular increment for each sample + float angle = 0; + final float frequency2 = 44100 / (SAMPLES / 2) * 4; + float increment2 = (float)(2 * Math.PI) * frequency2 / 44100; + float angle2 = 0; + + for (int i = 0; i < samples.length; i++) { + samples[i] = Math.max(0, Math.min((float)Math.sin(angle) + (float)Math.sin(angle2), 1)); + shortSamples.put((short)(Short.MAX_VALUE * samples[i])); + angle += increment; + angle2 += increment2; + } } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/FillrateTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/FillrateTest.java index 0d63718d8..000cbcf70 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/FillrateTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/FillrateTest.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Files.FileType; @@ -12,157 +13,134 @@ import com.badlogic.gdx.graphics.Texture.TextureWrap; import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.VertexAttributes; -public class FillrateTest implements RenderListener, InputListener -{ +public class FillrateTest implements RenderListener, InputListener { Texture texture; Mesh mesh; int numFills = 1; long lastOut = System.nanoTime(); - + int mode = 0; float mean = 0; float frames = 0; - @Override - public void surfaceCreated() - { - if( texture == null ) - { - Gdx.input.addInputListener( this ); - texture = Gdx.graphics.newTexture( Gdx.files.getFileHandle( "data/badlogicsmall.jpg", FileType.Internal ), - TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); - - mesh = new Mesh( true, false, 4, 6, new VertexAttribute( VertexAttributes.Usage.Position, 2, "a_pos" ), - new VertexAttribute( VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoords" ) ); - - float[] vertices = new float[4*4]; - + @Override public void surfaceCreated () { + if (texture == null) { + Gdx.input.addInputListener(this); + texture = Gdx.graphics.newTexture(Gdx.files.getFileHandle("data/badlogicsmall.jpg", FileType.Internal), + TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); + + mesh = new Mesh(true, false, 4, 6, new VertexAttribute(VertexAttributes.Usage.Position, 2, "a_pos"), + new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoords")); + + float[] vertices = new float[4 * 4]; + int idx = 0; vertices[idx++] = -1; vertices[idx++] = -1; vertices[idx++] = 0; vertices[idx++] = 0; - + vertices[idx++] = -1; vertices[idx++] = 1; vertices[idx++] = 0; vertices[idx++] = 1; - + vertices[idx++] = 1; vertices[idx++] = 1; vertices[idx++] = 1; vertices[idx++] = 1; - + vertices[idx++] = 1; vertices[idx++] = -1; vertices[idx++] = 1; vertices[idx++] = 0; - - short[] indices = { 0, 1, 2, 2, 3, 0 }; - mesh.setVertices( vertices ); - mesh.setIndices( indices ); + + short[] indices = {0, 1, 2, 2, 3, 0}; + mesh.setVertices(vertices); + mesh.setIndices(indices); } } - @Override - public void surfaceChanged(int width, int height) { + @Override public void surfaceChanged (int width, int height) { // TODO Auto-generated method stub - + } - @Override - public void render() - { - Gdx.graphics.getGL10().glClear( GL10.GL_COLOR_BUFFER_BIT ); - - if( mode == 3 ) - { - Gdx.graphics.getGL10().glDisable( GL10.GL_BLEND ); - Gdx.graphics.getGL10().glEnable( GL10.GL_ALPHA_TEST ); + @Override public void render () { + Gdx.graphics.getGL10().glClear(GL10.GL_COLOR_BUFFER_BIT); + + if (mode == 3) { + Gdx.graphics.getGL10().glDisable(GL10.GL_BLEND); + Gdx.graphics.getGL10().glEnable(GL10.GL_ALPHA_TEST); } - - if( mode == 2 ) - { - Gdx.graphics.getGL10().glEnable( GL10.GL_BLEND ); - Gdx.graphics.getGL10().glBlendFunc( GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA ); + + if (mode == 2) { + Gdx.graphics.getGL10().glEnable(GL10.GL_BLEND); + Gdx.graphics.getGL10().glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); } - - if( mode >= 1) - { - Gdx.graphics.getGL10().glEnable( GL10.GL_TEXTURE_2D ); + + if (mode >= 1) { + Gdx.graphics.getGL10().glEnable(GL10.GL_TEXTURE_2D); texture.bind(); } - - if( mode == 0 ) - { - Gdx.graphics.getGL10().glDisable( GL10.GL_BLEND ); - Gdx.graphics.getGL10().glDisable( GL10.GL_ALPHA_TEST ); - Gdx.graphics.getGL10().glDisable( GL10.GL_TEXTURE_2D ); + + if (mode == 0) { + Gdx.graphics.getGL10().glDisable(GL10.GL_BLEND); + Gdx.graphics.getGL10().glDisable(GL10.GL_ALPHA_TEST); + Gdx.graphics.getGL10().glDisable(GL10.GL_TEXTURE_2D); } - - Gdx.graphics.getGL10().glColor4f( 1, 1, 1, 0.01f ); - - for( int i = 0; i < numFills; i++ ) - mesh.render( GL10.GL_TRIANGLES ); - + + Gdx.graphics.getGL10().glColor4f(1, 1, 1, 0.01f); + + for (int i = 0; i < numFills; i++) + mesh.render(GL10.GL_TRIANGLES); + mean += numFills; frames++; - - if( Gdx.graphics.getDeltaTime() < 1 / 60f ) - numFills++; - - if( System.nanoTime() - lastOut >= 1000000000 ) - { - Gdx.app.log( "FillrateTest", "fills: " + mean / frames + ", fps: " + frames + ", mode" + mode ); + + if (Gdx.graphics.getDeltaTime() < 1 / 60f) numFills++; + + if (System.nanoTime() - lastOut >= 1000000000) { + Gdx.app.log("FillrateTest", "fills: " + mean / frames + ", fps: " + frames + ", mode" + mode); mean = 0; frames = 0; lastOut = System.nanoTime(); - if( Gdx.graphics.getFramesPerSecond() < 60 ) - numFills--; + if (Gdx.graphics.getFramesPerSecond() < 60) numFills--; } } - @Override - public void dispose() - { - + @Override public void dispose () { + } - @Override - public boolean keyDown(int keycode) { + @Override public boolean keyDown (int keycode) { // TODO Auto-generated method stub return false; } - @Override - public boolean keyUp(int keycode) { + @Override public boolean keyUp (int keycode) { // TODO Auto-generated method stub return false; } - @Override - public boolean keyTyped(char character) { + @Override public boolean keyTyped (char character) { // TODO Auto-generated method stub return false; } - @Override - public boolean touchDown(int x, int y, int pointer) { + @Override public boolean touchDown (int x, int y, int pointer) { // TODO Auto-generated method stub return false; } - @Override - public boolean touchUp(int x, int y, int pointer) { + @Override public boolean touchUp (int x, int y, int pointer) { mode++; - if( mode > 3 ) - mode = 0; + if (mode > 3) mode = 0; numFills = 0; return false; } - @Override - public boolean touchDragged(int x, int y, int pointer) { + @Override public boolean touchDragged (int x, int y, int pointer) { // TODO Auto-generated method stub return false; } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/FixedPointMeshTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/FixedPointMeshTest.java index 5c50a6fda..0f3a07e34 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/FixedPointMeshTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/FixedPointMeshTest.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -28,25 +26,21 @@ import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.VertexAttributes.Usage; /** - * Demonstrates the use of a {@link MeshRenderer} and a {@link Mesh} to - * render fixed point vertex data. + * Demonstrates the use of a {@link MeshRenderer} and a {@link Mesh} to render fixed point vertex data. * * @author mzechner - * + * */ -public class FixedPointMeshTest implements RenderListener -{ +public class FixedPointMeshTest implements RenderListener { /** the MeshRenderer **/ Mesh mesh; /** the Texture **/ Texture texture; - + /** * Called when the RenderListener is disposed. */ - @Override - public void dispose() - { + @Override public void dispose () { texture.dispose(); mesh.dispose(); } @@ -54,96 +48,84 @@ public class FixedPointMeshTest implements RenderListener /** * Called when the RenderListener needs to draw a new frame. */ - @Override - public void render() - { + @Override public void render () { // // setup the OpenGL Viewport and clear the // framebuffer with a light gray color. // GL10 gl = Gdx.graphics.getGL10(); - gl.glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - gl.glClearColor( 0.7f, 0.7f, 0.7f, 1 ); - gl.glClear( GL10.GL_COLOR_BUFFER_BIT ); - + gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + gl.glClearColor(0.7f, 0.7f, 0.7f, 1); + gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + // // Enable texturing, bind the texture and render the mesh // - gl.glEnable(GL10.GL_TEXTURE_2D ); + gl.glEnable(GL10.GL_TEXTURE_2D); texture.bind(); - mesh.render( GL10.GL_TRIANGLES, 0, 3); + mesh.render(GL10.GL_TRIANGLES, 0, 3); } /** - * Called when the OpenGL surface is created. We setup - * our MeshRenderer and Texture here. + * Called when the OpenGL surface is created. We setup our MeshRenderer and Texture here. */ - @Override - public void surfaceCreated() - { - if( texture != null ) - { + @Override public void surfaceCreated () { + if (texture != null) { texture.dispose(); mesh.dispose(); } - + // - // We first have to create a Mesh to hold - // our vertex data. The mesh is composed of 3 vertices + // We first have to create a Mesh to hold + // our vertex data. The mesh is composed of 3 vertices // forming a triangle. Each vertex has a 3 component position - // a 4 component color and a 2 component texture coordinate. - // Additionally we use indices, in this case 3. Note that for + // a 4 component color and a 2 component texture coordinate. + // Additionally we use indices, in this case 3. Note that for // this example indices are a bit of overkill. // - mesh = new Mesh( true, true, 3, 3, - new VertexAttribute( Usage.Position, 3, "a_position" ), - new VertexAttribute( Usage.Color, 4, "a_color" ), - new VertexAttribute( Usage.TextureCoordinates, 2, "a_texCoords" ) ); - + mesh = new Mesh(true, true, 3, 3, new VertexAttribute(Usage.Position, 3, "a_position"), new VertexAttribute(Usage.Color, 4, + "a_color"), new VertexAttribute(Usage.TextureCoordinates, 2, "a_texCoords")); + // // Set the actual vertex data. Note that we use floats here. The // MeshRenderer.setVertices() method will convert the floats to fixed // point for use. - // - mesh.setVertices( new int[] { fp(-0.5f), fp(-0.5f), fp(0), fp(1), fp(0), fp(0), fp(1), fp(0), fp(0), - fp(0.5f), fp(-0.5f), fp(0), fp(0), fp(1), fp(0), fp(1), fp(1), fp(0), - fp(0.0f), fp(0.5f), fp(0), fp(0), fp(0), fp(1), fp(1), fp(0.5f), fp(1)} ); + // + mesh + .setVertices(new int[] {fp(-0.5f), fp(-0.5f), fp(0), fp(1), fp(0), fp(0), fp(1), fp(0), fp(0), fp(0.5f), fp(-0.5f), + fp(0), fp(0), fp(1), fp(0), fp(1), fp(1), fp(0), fp(0.0f), fp(0.5f), fp(0), fp(0), fp(0), fp(1), fp(1), fp(0.5f), + fp(1)}); // // we also set the vertex indices. // - mesh.setIndices( new short[] { 0, 1, 2 } ); - - + mesh.setIndices(new short[] {0, 1, 2}); + // // Create a small Pixmap and draw some lines to it. // - Pixmap pixmap = Gdx.graphics.newPixmap(256, 256, Format.RGBA8888 ); - pixmap.setColor(1, 1, 1, 1 ); + Pixmap pixmap = Gdx.graphics.newPixmap(256, 256, Format.RGBA8888); + pixmap.setColor(1, 1, 1, 1); pixmap.fill(); - pixmap.setColor(0, 0, 0, 1 ); + pixmap.setColor(0, 0, 0, 1); pixmap.drawLine(0, 0, 256, 256); pixmap.drawLine(256, 0, 0, 256); - + // // Create a texture from the Pixmap we just drew. // - texture = Gdx.graphics.newUnmanagedTexture( pixmap, TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); + texture = Gdx.graphics.newUnmanagedTexture(pixmap, TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, + TextureWrap.ClampToEdge); } /** * Called when the surface dimensions changed. */ - @Override - public void surfaceChanged(int width, int height) - { - + @Override public void surfaceChanged (int width, int height) { + } - - - private static int fp( float val ) - { - return (int)(val * 65536); + private static int fp (float val) { + return (int)(val * 65536); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/FixedPointTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/FixedPointTest.java index 78df1f745..b452b5d47 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/FixedPointTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/FixedPointTest.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.nio.ByteBuffer; @@ -23,122 +21,103 @@ import com.badlogic.gdx.Gdx; import com.badlogic.gdx.RenderListener; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Pixmap; -import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.Pixmap.Format; +import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; -public class FixedPointTest implements RenderListener -{ +public class FixedPointTest implements RenderListener { Texture tex; Texture tex2; IntBuffer vertices; - final int BYTES_PER_VERTEX = (4+3+2+2)*4; + final int BYTES_PER_VERTEX = (4 + 3 + 2 + 2) * 4; float angle = 0; float angleIncrement = 0.1f; - - @Override - public void dispose() - { - + + @Override public void dispose () { + } - @Override - public void render() - { + @Override public void render () { GL10 gl = Gdx.graphics.getGL10(); - gl.glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - gl.glClearColor( 0.7f, 0.7f, 0.7f, 1 ); - gl.glClear( GL10.GL_COLOR_BUFFER_BIT ); - gl.glMatrixMode( GL10.GL_MODELVIEW ); + gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + gl.glClearColor(0.7f, 0.7f, 0.7f, 1); + gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); - gl.glRotatef( angle, 0, 0, 1 ); - angle+=angleIncrement; - gl.glEnable(GL10.GL_TEXTURE_2D); - - gl.glEnableClientState(GL10.GL_COLOR_ARRAY); + gl.glRotatef(angle, 0, 0, 1); + angle += angleIncrement; + gl.glEnable(GL10.GL_TEXTURE_2D); + + gl.glEnableClientState(GL10.GL_COLOR_ARRAY); vertices.position(0); - gl.glColorPointer(4, GL10.GL_FIXED, BYTES_PER_VERTEX, vertices ); - + gl.glColorPointer(4, GL10.GL_FIXED, BYTES_PER_VERTEX, vertices); + gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); - gl.glClientActiveTexture( GL10.GL_TEXTURE0 ); - gl.glActiveTexture( GL10.GL_TEXTURE0 ); + gl.glClientActiveTexture(GL10.GL_TEXTURE0); + gl.glActiveTexture(GL10.GL_TEXTURE0); tex.bind(); - vertices.position(4); - gl.glTexCoordPointer( 2, GL10.GL_FIXED, BYTES_PER_VERTEX, vertices ); - - gl.glClientActiveTexture( GL10.GL_TEXTURE1 ); - gl.glActiveTexture( GL10.GL_TEXTURE1 ); + vertices.position(4); + gl.glTexCoordPointer(2, GL10.GL_FIXED, BYTES_PER_VERTEX, vertices); + + gl.glClientActiveTexture(GL10.GL_TEXTURE1); + gl.glActiveTexture(GL10.GL_TEXTURE1); tex2.bind(); - vertices.position(6); - gl.glTexCoordPointer( 2, GL10.GL_FIXED, BYTES_PER_VERTEX, vertices ); - + vertices.position(6); + gl.glTexCoordPointer(2, GL10.GL_FIXED, BYTES_PER_VERTEX, vertices); + gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); vertices.position(8); - gl.glVertexPointer( 3, GL10.GL_FIXED, BYTES_PER_VERTEX, vertices ); - - gl.glDrawArrays( GL10.GL_TRIANGLES, 0, 3); + gl.glVertexPointer(3, GL10.GL_FIXED, BYTES_PER_VERTEX, vertices); + + gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3); } - @Override - public void surfaceCreated() - { - if( tex != null ) - { + @Override public void surfaceCreated () { + if (tex != null) { tex.dispose(); tex2.dispose(); } - - ByteBuffer buffer = ByteBuffer.allocateDirect( BYTES_PER_VERTEX * 3 ); + + ByteBuffer buffer = ByteBuffer.allocateDirect(BYTES_PER_VERTEX * 3); buffer.order(ByteOrder.nativeOrder()); - vertices = buffer.asIntBuffer(); - - int[] verts = { - fp(1), fp(0), fp(0), fp(1), - fp(0), fp(1), - fp(0), fp(1), - fp(-0.5f), fp(-0.5f), fp(0), - - fp(0), fp(1), fp(0), fp(1), - fp(1), fp(1), - fp(1), fp(1), - fp(0.5f), fp(-0.5f), fp(0), - - fp(0), fp(0), fp(1), fp(1), - fp(0.5f), fp(0), - fp(0.5f), fp(0), - fp(0), fp(0.5f), fp(0), - }; + vertices = buffer.asIntBuffer(); + + int[] verts = {fp(1), fp(0), fp(0), fp(1), fp(0), fp(1), fp(0), fp(1), fp(-0.5f), fp(-0.5f), fp(0), + + fp(0), fp(1), fp(0), fp(1), fp(1), fp(1), fp(1), fp(1), fp(0.5f), fp(-0.5f), fp(0), + + fp(0), fp(0), fp(1), fp(1), fp(0.5f), fp(0), fp(0.5f), fp(0), fp(0), fp(0.5f), fp(0),}; vertices.put(verts); - vertices.flip(); - - Pixmap pixmap = Gdx.graphics.newPixmap(256, 256, Format.RGBA8888 ); - pixmap.setColor(1, 1, 1, 1 ); + vertices.flip(); + + Pixmap pixmap = Gdx.graphics.newPixmap(256, 256, Format.RGBA8888); + pixmap.setColor(1, 1, 1, 1); pixmap.fill(); - pixmap.setColor(0, 0, 0, 1 ); + pixmap.setColor(0, 0, 0, 1); pixmap.drawLine(0, 0, 256, 256); - pixmap.drawLine(256, 0, 0, 256); - tex = Gdx.graphics.newUnmanagedTexture( pixmap, TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); - - pixmap = Gdx.graphics.newPixmap( 256, 256, Format.RGBA8888 ); - pixmap.setColor( 1, 1, 1, 1 ); + pixmap.drawLine(256, 0, 0, 256); + tex = Gdx.graphics.newUnmanagedTexture(pixmap, TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, + TextureWrap.ClampToEdge); + + pixmap = Gdx.graphics.newPixmap(256, 256, Format.RGBA8888); + pixmap.setColor(1, 1, 1, 1); pixmap.fill(); - pixmap.setColor( 0, 0, 0, 1 ); - pixmap.drawLine( 128, 0, 128, 256 ); - tex2 = Gdx.graphics.newUnmanagedTexture( pixmap, TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); - - Gdx.graphics.getGL10().glDisable( GL10.GL_TEXTURE_2D ); + pixmap.setColor(0, 0, 0, 1); + pixmap.drawLine(128, 0, 128, 256); + tex2 = Gdx.graphics.newUnmanagedTexture(pixmap, TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, + TextureWrap.ClampToEdge); + + Gdx.graphics.getGL10().glDisable(GL10.GL_TEXTURE_2D); } - @Override - public void surfaceChanged(int width, int height) { + @Override public void surfaceChanged (int width, int height) { // TODO Auto-generated method stub - + } - - private static int fp( float value ) - { + + private static int fp (float value) { return (int)(value * 65536); } - + } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/FloatTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/FloatTest.java index 1f726e2b6..cea919108 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/FloatTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/FloatTest.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.nio.ByteBuffer; @@ -23,116 +21,98 @@ import com.badlogic.gdx.Gdx; import com.badlogic.gdx.RenderListener; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Pixmap; -import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.Pixmap.Format; +import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; -public class FloatTest implements RenderListener -{ +public class FloatTest implements RenderListener { Texture tex; Texture tex2; FloatBuffer vertices; - final int BYTES_PER_VERTEX = (4+3+2+2)*4; + final int BYTES_PER_VERTEX = (4 + 3 + 2 + 2) * 4; float angle = 0; float angleIncrement = 0.1f; - - @Override - public void dispose() - { + + @Override public void dispose () { tex.dispose(); tex2.dispose(); } - @Override - public void render() - { + @Override public void render () { GL10 gl = Gdx.graphics.getGL10(); - gl.glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - gl.glClearColor( 0.7f, 0.7f, 0.7f, 1 ); - gl.glClear( GL10.GL_COLOR_BUFFER_BIT ); - gl.glMatrixMode( GL10.GL_MODELVIEW ); + gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + gl.glClearColor(0.7f, 0.7f, 0.7f, 1); + gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); - gl.glRotatef( angle, 0, 0, 1 ); - angle+=angleIncrement; - gl.glEnable(GL10.GL_TEXTURE_2D); - - gl.glEnableClientState(GL10.GL_COLOR_ARRAY); + gl.glRotatef(angle, 0, 0, 1); + angle += angleIncrement; + gl.glEnable(GL10.GL_TEXTURE_2D); + + gl.glEnableClientState(GL10.GL_COLOR_ARRAY); vertices.position(0); - gl.glColorPointer(4, GL10.GL_FLOAT, BYTES_PER_VERTEX, vertices ); - + gl.glColorPointer(4, GL10.GL_FLOAT, BYTES_PER_VERTEX, vertices); + gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); - gl.glClientActiveTexture( GL10.GL_TEXTURE0 ); - gl.glActiveTexture( GL10.GL_TEXTURE0 ); + gl.glClientActiveTexture(GL10.GL_TEXTURE0); + gl.glActiveTexture(GL10.GL_TEXTURE0); tex.bind(); - vertices.position(4); - gl.glTexCoordPointer( 2, GL10.GL_FLOAT, BYTES_PER_VERTEX, vertices ); - - gl.glClientActiveTexture( GL10.GL_TEXTURE1 ); - gl.glActiveTexture( GL10.GL_TEXTURE1 ); + vertices.position(4); + gl.glTexCoordPointer(2, GL10.GL_FLOAT, BYTES_PER_VERTEX, vertices); + + gl.glClientActiveTexture(GL10.GL_TEXTURE1); + gl.glActiveTexture(GL10.GL_TEXTURE1); tex2.bind(); - vertices.position(6); - gl.glTexCoordPointer( 2, GL10.GL_FLOAT, BYTES_PER_VERTEX, vertices ); - + vertices.position(6); + gl.glTexCoordPointer(2, GL10.GL_FLOAT, BYTES_PER_VERTEX, vertices); + gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); vertices.position(8); - gl.glVertexPointer( 3, GL10.GL_FLOAT, BYTES_PER_VERTEX, vertices ); - - gl.glDrawArrays( GL10.GL_TRIANGLES, 0, 3); + gl.glVertexPointer(3, GL10.GL_FLOAT, BYTES_PER_VERTEX, vertices); + + gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3); } - @Override - public void surfaceCreated() - { - if( tex != null ) - { + @Override public void surfaceCreated () { + if (tex != null) { tex.dispose(); tex2.dispose(); } - - ByteBuffer buffer = ByteBuffer.allocateDirect( BYTES_PER_VERTEX * 3 ); + + ByteBuffer buffer = ByteBuffer.allocateDirect(BYTES_PER_VERTEX * 3); buffer.order(ByteOrder.nativeOrder()); - vertices = buffer.asFloatBuffer(); - - float[] verts = { - 1, 0, 0, 1, - 0, 1, - 0, 1, - -0.5f, -0.5f, 0, - - 0, 1, 0, 1, - 1, 1, - 1, 1, - 0.5f, -0.5f, 0, - - 0, 0, 1, 1, - 0.5f, 0, - 0.5f, 0, - 0, 0.5f, 0, - }; + vertices = buffer.asFloatBuffer(); + + float[] verts = {1, 0, 0, 1, 0, 1, 0, 1, -0.5f, -0.5f, 0, + + 0, 1, 0, 1, 1, 1, 1, 1, 0.5f, -0.5f, 0, + + 0, 0, 1, 1, 0.5f, 0, 0.5f, 0, 0, 0.5f, 0,}; vertices.put(verts); - vertices.flip(); - - Pixmap pixmap = Gdx.graphics.newPixmap(256, 256, Format.RGBA8888 ); - pixmap.setColor(1, 1, 1, 1 ); + vertices.flip(); + + Pixmap pixmap = Gdx.graphics.newPixmap(256, 256, Format.RGBA8888); + pixmap.setColor(1, 1, 1, 1); pixmap.fill(); - pixmap.setColor(0, 0, 0, 1 ); + pixmap.setColor(0, 0, 0, 1); pixmap.drawLine(0, 0, 256, 256); - pixmap.drawLine(256, 0, 0, 256); - tex = Gdx.graphics.newUnmanagedTexture( pixmap, TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); - - pixmap = Gdx.graphics.newPixmap( 256, 256, Format.RGBA8888 ); - pixmap.setColor( 1, 1, 1, 1 ); + pixmap.drawLine(256, 0, 0, 256); + tex = Gdx.graphics.newUnmanagedTexture(pixmap, TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, + TextureWrap.ClampToEdge); + + pixmap = Gdx.graphics.newPixmap(256, 256, Format.RGBA8888); + pixmap.setColor(1, 1, 1, 1); pixmap.fill(); - pixmap.setColor( 0, 0, 0, 1 ); - pixmap.drawLine( 128, 0, 128, 256 ); - tex2 = Gdx.graphics.newUnmanagedTexture( pixmap, TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); + pixmap.setColor(0, 0, 0, 1); + pixmap.drawLine(128, 0, 128, 256); + tex2 = Gdx.graphics.newUnmanagedTexture(pixmap, TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, + TextureWrap.ClampToEdge); } - @Override - public void surfaceChanged(int width, int height) { + @Override public void surfaceChanged (int width, int height) { // TODO Auto-generated method stub - + } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/FrameBufferTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/FrameBufferTest.java index 058d266dc..e89d74ea2 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/FrameBufferTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/FrameBufferTest.java @@ -1,134 +1,108 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; +import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Graphics; import com.badlogic.gdx.RenderListener; -import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.FrameBuffer; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Mesh; +import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.ShaderProgram; import com.badlogic.gdx.graphics.SpriteBatch; import com.badlogic.gdx.graphics.Texture; -import com.badlogic.gdx.graphics.VertexAttribute; -import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; +import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.VertexAttributes.Usage; -public class FrameBufferTest implements RenderListener -{ +public class FrameBufferTest implements RenderListener { FrameBuffer frameBuffer; - Mesh mesh; - ShaderProgram meshShader; - Texture texture; + Mesh mesh; + ShaderProgram meshShader; + Texture texture; SpriteBatch spriteBatch; - - @Override - public void dispose() - { - + + @Override public void dispose () { + } - @Override - public void render() - { + @Override public void render () { frameBuffer.begin(); - Gdx.graphics.getGL20().glViewport( 0, 0, frameBuffer.getWidth(), frameBuffer.getHeight() ); - Gdx.graphics.getGL20().glClearColor( 0f, 1f, 0f, 1 ); - Gdx.graphics.getGL20().glClear( GL20.GL_COLOR_BUFFER_BIT ); - Gdx.graphics.getGL20().glEnable( GL20.GL_TEXTURE_2D ); - texture.bind(); + Gdx.graphics.getGL20().glViewport(0, 0, frameBuffer.getWidth(), frameBuffer.getHeight()); + Gdx.graphics.getGL20().glClearColor(0f, 1f, 0f, 1); + Gdx.graphics.getGL20().glClear(GL20.GL_COLOR_BUFFER_BIT); + Gdx.graphics.getGL20().glEnable(GL20.GL_TEXTURE_2D); + texture.bind(); meshShader.begin(); - meshShader.setUniformi( "u_texture", 0 ); + meshShader.setUniformi("u_texture", 0); mesh.render(meshShader, GL20.GL_TRIANGLES); meshShader.end(); - frameBuffer.end(); - - Gdx.graphics.getGL20().glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - Gdx.graphics.getGL20().glClearColor( 0.2f, 0.2f, 0.2f, 1 ); - Gdx.graphics.getGL20().glClear( GL20.GL_COLOR_BUFFER_BIT ); - + frameBuffer.end(); + + Gdx.graphics.getGL20().glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + Gdx.graphics.getGL20().glClearColor(0.2f, 0.2f, 0.2f, 1); + Gdx.graphics.getGL20().glClear(GL20.GL_COLOR_BUFFER_BIT); + spriteBatch.begin(); - spriteBatch.draw( frameBuffer.getColorBufferTexture(), 0, 0, 256, 256, 0, 0, frameBuffer.getColorBufferTexture().getWidth(), frameBuffer.getColorBufferTexture().getHeight(), Color.WHITE, false, true ); + spriteBatch.draw(frameBuffer.getColorBufferTexture(), 0, 0, 256, 256, 0, 0, frameBuffer.getColorBufferTexture().getWidth(), + frameBuffer.getColorBufferTexture().getHeight(), Color.WHITE, false, true); spriteBatch.end(); } - @Override - public void surfaceChanged(int width, int height) - { - + @Override public void surfaceChanged (int width, int height) { + } - @Override - public void surfaceCreated() - { - if( mesh == null ) - { - mesh = new Mesh( true, false, 3, 0, - new VertexAttribute( Usage.Position, 3, "a_Position" ), - new VertexAttribute( Usage.ColorPacked, 4, "a_Color" ), - new VertexAttribute( Usage.TextureCoordinates, 2, "a_texCoords" ) ); + @Override public void surfaceCreated () { + if (mesh == null) { + mesh = new Mesh(true, false, 3, 0, new VertexAttribute(Usage.Position, 3, "a_Position"), new VertexAttribute( + Usage.ColorPacked, 4, "a_Color"), new VertexAttribute(Usage.TextureCoordinates, 2, "a_texCoords")); float c1 = Color.toFloatBits(255, 0, 0, 255); - float c2 = Color.toFloatBits(255, 0, 0, 255);; - float c3 = Color.toFloatBits(0, 0, 255, 255);; - - mesh.setVertices( new float[] { -0.5f, -0.5f, 0, c1, 0, 0, - 0.5f, -0.5f, 0, c2, 1, 0, - 0, 0.5f, 0, c3, 0.5f, 1 } ); - - texture = Gdx.graphics.newTexture( Gdx.files.getFileHandle( "data/badlogic.jpg", FileType.Internal), TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); - - spriteBatch = new SpriteBatch( ); - frameBuffer = new FrameBuffer( Format.RGB565, 128, 128, true ); + float c2 = Color.toFloatBits(255, 0, 0, 255); + ; + float c3 = Color.toFloatBits(0, 0, 255, 255); + ; + + mesh.setVertices(new float[] {-0.5f, -0.5f, 0, c1, 0, 0, 0.5f, -0.5f, 0, c2, 1, 0, 0, 0.5f, 0, c3, 0.5f, 1}); + + texture = Gdx.graphics.newTexture(Gdx.files.getFileHandle("data/badlogic.jpg", FileType.Internal), TextureFilter.MipMap, + TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); + + spriteBatch = new SpriteBatch(); + frameBuffer = new FrameBuffer(Format.RGB565, 128, 128, true); createShader(Gdx.graphics); } } - - private void createShader( Graphics graphics ) - { - String vertexShader = "attribute vec4 a_Position; \n" + - "attribute vec4 a_Color;\n" + - "attribute vec2 a_texCoords;\n" + - "varying vec4 v_Color;" + - "varying vec2 v_texCoords; \n" + - - "void main() \n" + - "{ \n" + - " v_Color = a_Color;" + - " v_texCoords = a_texCoords;\n" + - " gl_Position = a_Position; \n" + - "} \n"; - String fragmentShader = "precision mediump float;\n" + - "varying vec4 v_Color;\n" + - "varying vec2 v_texCoords; \n" + - "uniform sampler2D u_texture;\n" + - - "void main() \n" + - "{ \n" + - " gl_FragColor = v_Color * texture2D(u_texture, v_texCoords);\n" + - "}"; - - meshShader = new ShaderProgram( vertexShader, fragmentShader ); - if( meshShader.isCompiled() == false ) - throw new IllegalStateException( meshShader.getLog() ); + + private void createShader (Graphics graphics) { + String vertexShader = "attribute vec4 a_Position; \n" + "attribute vec4 a_Color;\n" + "attribute vec2 a_texCoords;\n" + + "varying vec4 v_Color;" + "varying vec2 v_texCoords; \n" + + + "void main() \n" + "{ \n" + " v_Color = a_Color;" + + " v_texCoords = a_texCoords;\n" + " gl_Position = a_Position; \n" + "} \n"; + String fragmentShader = "precision mediump float;\n" + "varying vec4 v_Color;\n" + "varying vec2 v_texCoords; \n" + + "uniform sampler2D u_texture;\n" + + + "void main() \n" + "{ \n" + + " gl_FragColor = v_Color * texture2D(u_texture, v_texCoords);\n" + "}"; + + meshShader = new ShaderProgram(vertexShader, fragmentShader); + if (meshShader.isCompiled() == false) throw new IllegalStateException(meshShader.getLog()); } - } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/ImmediateModeRendererTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/ImmediateModeRendererTest.java index 7c8830ad0..f875be48a 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/ImmediateModeRendererTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/ImmediateModeRendererTest.java @@ -1,72 +1,61 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; +import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.RenderListener; -import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.ImmediateModeRenderer; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; -public class ImmediateModeRendererTest implements RenderListener -{ +public class ImmediateModeRendererTest implements RenderListener { ImmediateModeRenderer renderer; Texture texture; - - @Override - public void dispose( ) - { + + @Override public void dispose () { texture.dispose(); } - @Override - public void render( ) - { - Gdx.graphics.getGL10().glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - Gdx.graphics.getGL10().glEnable( GL10.GL_TEXTURE_2D ); + @Override public void render () { + Gdx.graphics.getGL10().glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + Gdx.graphics.getGL10().glEnable(GL10.GL_TEXTURE_2D); texture.bind(); - renderer.begin( GL10.GL_TRIANGLES ); - renderer.texCoord( 0, 0); - renderer.color( 1, 0, 0, 1 ); - renderer.vertex( -0.5f, -0.5f, 0 ); - renderer.texCoord( 1, 0); - renderer.color( 0, 1, 0, 1 ); - renderer.vertex( 0.5f, -0.5f, 0 ); - renderer.texCoord( 0.5f, 1); - renderer.color( 0, 0, 1, 1 ); - renderer.vertex( 0f, 0.5f, 0 ); + renderer.begin(GL10.GL_TRIANGLES); + renderer.texCoord(0, 0); + renderer.color(1, 0, 0, 1); + renderer.vertex(-0.5f, -0.5f, 0); + renderer.texCoord(1, 0); + renderer.color(0, 1, 0, 1); + renderer.vertex(0.5f, -0.5f, 0); + renderer.texCoord(0.5f, 1); + renderer.color(0, 0, 1, 1); + renderer.vertex(0f, 0.5f, 0); renderer.end(); } - @Override - public void surfaceChanged(int width, int height) - { - + @Override public void surfaceChanged (int width, int height) { + } - @Override - public void surfaceCreated( ) - { - renderer = new ImmediateModeRenderer( ); - - texture = Gdx.graphics.newTexture( Gdx.files.getFileHandle( "data/badlogic.jpg", FileType.Internal), TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); + @Override public void surfaceCreated () { + renderer = new ImmediateModeRenderer(); + + texture = Gdx.graphics.newTexture(Gdx.files.getFileHandle("data/badlogic.jpg", FileType.Internal), TextureFilter.MipMap, + TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); } - } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/InputTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/InputTest.java index 892cbdb41..2ed4f758f 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/InputTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/InputTest.java @@ -1,87 +1,70 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputListener; import com.badlogic.gdx.RenderListener; -public class InputTest implements RenderListener, InputListener -{ - @Override - public void dispose() { +public class InputTest implements RenderListener, InputListener { + @Override public void dispose () { // TODO Auto-generated method stub - + } - @Override - public void render() { + @Override public void render () { // TODO Auto-generated method stub - + } - @Override - public void surfaceChanged(int width, int height) { + @Override public void surfaceChanged (int width, int height) { // TODO Auto-generated method stub - + } - @Override - public void surfaceCreated() { - Gdx.input.addInputListener( this ); + @Override public void surfaceCreated () { + Gdx.input.addInputListener(this); } - @Override - public boolean keyDown(int keycode) - { - Gdx.app.log( "Input Test", "key down: " + keycode ); + @Override public boolean keyDown (int keycode) { + Gdx.app.log("Input Test", "key down: " + keycode); return false; } - @Override - public boolean keyTyped(char character) { - Gdx.app.log( "Input Test", "key typed: '" + character + "'" ); + @Override public boolean keyTyped (char character) { + Gdx.app.log("Input Test", "key typed: '" + character + "'"); return false; } - @Override - public boolean keyUp(int keycode) - { - Gdx.app.log( "Input Test", "key up: " + keycode ); + @Override public boolean keyUp (int keycode) { + Gdx.app.log("Input Test", "key up: " + keycode); return false; } - @Override - public boolean touchDown(int x, int y, int pointer) - { - Gdx.app.log( "Input Test", "touch down: " + x + ", " + y ); + @Override public boolean touchDown (int x, int y, int pointer) { + Gdx.app.log("Input Test", "touch down: " + x + ", " + y); return false; } - @Override - public boolean touchDragged(int x, int y, int pointer) { - Gdx.app.log( "Input Test", "touch dragged: " + x + ", " + y ); + @Override public boolean touchDragged (int x, int y, int pointer) { + Gdx.app.log("Input Test", "touch dragged: " + x + ", " + y); return false; } - @Override - public boolean touchUp(int x, int y, int pointer) { - Gdx.app.log( "Input Test", "touch up: " + x + ", " + y ); + @Override public boolean touchUp (int x, int y, int pointer) { + Gdx.app.log("Input Test", "touch up: " + x + ", " + y); return false; } - } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/LifeCycleTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/LifeCycleTest.java index 3b9b00541..0685f83d7 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/LifeCycleTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/LifeCycleTest.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.ApplicationListener; @@ -21,56 +19,42 @@ import com.badlogic.gdx.RenderListener; import com.badlogic.gdx.graphics.GL10; /** - * A simple test to demonstrate the life cycle of an application and a - * RenderListener. + * A simple test to demonstrate the life cycle of an application and a RenderListener. * * @author mzechner - * + * */ -public class LifeCycleTest implements ApplicationListener, RenderListener -{ +public class LifeCycleTest implements ApplicationListener, RenderListener { - @Override - public void destroy() - { - Gdx.app.log( "Test", "Thread=" + Thread.currentThread().getId() + ", app destroyed" ); + @Override public void destroy () { + Gdx.app.log("Test", "Thread=" + Thread.currentThread().getId() + ", app destroyed"); } - @Override - public void pause() - { - Gdx.app.log( "Test", "Thread=" + Thread.currentThread().getId() + ", app paused" ); + @Override public void pause () { + Gdx.app.log("Test", "Thread=" + Thread.currentThread().getId() + ", app paused"); } - @Override - public void resume() - { - Gdx.app.log( "Test", "Thread=" + Thread.currentThread().getId() + ", app resumed" ); + @Override public void resume () { + Gdx.app.log("Test", "Thread=" + Thread.currentThread().getId() + ", app resumed"); } - @Override - public void dispose() - { - Gdx.app.log( "Test", "Thread=" + Thread.currentThread().getId() + ", renderer disposed" ); + @Override public void dispose () { + Gdx.app.log("Test", "Thread=" + Thread.currentThread().getId() + ", renderer disposed"); } - @Override - public void render() - { - Gdx.graphics.getGL10().glClear( GL10.GL_COLOR_BUFFER_BIT ); + @Override public void render () { + Gdx.graphics.getGL10().glClear(GL10.GL_COLOR_BUFFER_BIT); } - @Override - public void surfaceChanged( int width, int height) - { - Gdx.app.log( "Test", "Thread=" + Thread.currentThread().getId() + ", renderer surface changed: " + Gdx.graphics.getWidth() + "x" + Gdx.graphics.getHeight() ); + @Override public void surfaceChanged (int width, int height) { + Gdx.app.log("Test", "Thread=" + Thread.currentThread().getId() + ", renderer surface changed: " + Gdx.graphics.getWidth() + + "x" + Gdx.graphics.getHeight()); } - @Override - public void surfaceCreated() - { - Gdx.app.log( "Test", "Thread=" + Thread.currentThread().getId() + ", renderer surface created: " + Gdx.graphics.getWidth() + "x" + Gdx.graphics.getHeight() ); - System.out.println(Gdx.graphics.getGL10().glGetString( GL10.GL_VERSION ) ); + @Override public void surfaceCreated () { + Gdx.app.log("Test", "Thread=" + Thread.currentThread().getId() + ", renderer surface created: " + Gdx.graphics.getWidth() + + "x" + Gdx.graphics.getHeight()); + System.out.println(Gdx.graphics.getGL10().glGetString(GL10.GL_VERSION)); } - + } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/MD5Test.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/MD5Test.java index db0688936..2ebef9036 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/MD5Test.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/MD5Test.java @@ -1,15 +1,16 @@ + package com.badlogic.gdx.tests; +import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputListener; import com.badlogic.gdx.RenderListener; -import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Font; +import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.SpriteBatch; -import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.loaders.md5.MD5Animation; import com.badlogic.gdx.graphics.loaders.md5.MD5AnimationInfo; import com.badlogic.gdx.graphics.loaders.md5.MD5Joints; @@ -17,153 +18,134 @@ import com.badlogic.gdx.graphics.loaders.md5.MD5Loader; import com.badlogic.gdx.graphics.loaders.md5.MD5Model; import com.badlogic.gdx.graphics.loaders.md5.MD5Renderer; -public class MD5Test implements RenderListener, InputListener -{ +public class MD5Test implements RenderListener, InputListener { PerspectiveCamera camera; MD5Model model; MD5Animation anim; MD5AnimationInfo animInfo; - MD5Joints skeleton; - MD5Renderer renderer; + MD5Joints skeleton; + MD5Renderer renderer; SpriteBatch batch; Font font; - - @Override - public void surfaceCreated() - { - if( model == null ) - { - - Gdx.app.log( "MD5 Test", "created" ); - model = MD5Loader.loadModel( Gdx.files.readFile( "data/zfat.md5mesh", FileType.Internal) ); - anim = MD5Loader.loadAnimation( Gdx.files.readFile( "data/walk1.md5anim", FileType.Internal ) ); + @Override public void surfaceCreated () { + if (model == null) { + + Gdx.app.log("MD5 Test", "created"); + model = MD5Loader.loadModel(Gdx.files.readFile("data/zfat.md5mesh", FileType.Internal)); + anim = MD5Loader.loadAnimation(Gdx.files.readFile("data/walk1.md5anim", FileType.Internal)); skeleton = new MD5Joints(); skeleton.joints = new float[anim.frames[0].joints.length]; - animInfo = new MD5AnimationInfo( anim.frames.length, anim.secondsPerFrame ); - renderer = new MD5Renderer( model, true ); - renderer.setSkeleton( model.baseSkeleton ); - - - // long start = System.nanoTime(); - // for( int i = 0; i < 100000; i++ ) - // renderer.setSkeleton( model.baseSkeleton ); - // app.log( "MD5 Test", "took: " + (System.nanoTime() - start ) / 1000000000.0 ); - - + animInfo = new MD5AnimationInfo(anim.frames.length, anim.secondsPerFrame); + renderer = new MD5Renderer(model, true); + renderer.setSkeleton(model.baseSkeleton); + + // long start = System.nanoTime(); + // for( int i = 0; i < 100000; i++ ) + // renderer.setSkeleton( model.baseSkeleton ); + // app.log( "MD5 Test", "took: " + (System.nanoTime() - start ) / 1000000000.0 ); + camera = new PerspectiveCamera(); - camera.getPosition().set( 0, 25, 100 ); + camera.getPosition().set(0, 25, 100); camera.setFov(60); - camera.setNear( 1 ); - camera.setFar( 1000 ); - camera.setViewport( Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - - batch = new SpriteBatch( ); - font = Gdx.graphics.newFont( "Arial", 12, FontStyle.Plain ); - Gdx.graphics.getGL10().glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - Gdx.input.addInputListener( this ); + camera.setNear(1); + camera.setFar(1000); + camera.setViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + + batch = new SpriteBatch(); + font = Gdx.graphics.newFont("Arial", 12, FontStyle.Plain); + Gdx.graphics.getGL10().glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + Gdx.input.addInputListener(this); } } - @Override - public void surfaceChanged(int width, int height) - { - + @Override public void surfaceChanged (int width, int height) { + } - float angle = 0; - - @Override - @SuppressWarnings("unused") - public void render() - { + float angle = 0; + + @Override @SuppressWarnings("unused") public void render () { GL10 gl = Gdx.graphics.getGL10(); - gl.glClear( GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT ); - - camera.setMatrices( ); - angle+=Gdx.graphics.getDeltaTime() * 20; - animInfo.update( Gdx.graphics.getDeltaTime() ); - - gl.glEnable( GL10.GL_DEPTH_TEST ); -// gl.glPolygonMode( GL10.GL_FRONT_AND_BACK, GL10.GL_LINE ); - - long start = 0; + gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); + + camera.setMatrices(); + angle += Gdx.graphics.getDeltaTime() * 20; + animInfo.update(Gdx.graphics.getDeltaTime()); + + gl.glEnable(GL10.GL_DEPTH_TEST); +// gl.glPolygonMode( GL10.GL_FRONT_AND_BACK, GL10.GL_LINE ); + + long start = 0; float renderTime = 0; float skinTime = 0; - - for( int z = 0; z < 50; z += 50 ) - { + + for (int z = 0; z < 50; z += 50) { gl.glLoadIdentity(); - gl.glTranslatef( 0, 0, -z ); - gl.glRotatef( angle, 0, 1, 0 ); - gl.glRotatef(-90, 1, 0, 0 ); - + gl.glTranslatef(0, 0, -z); + gl.glRotatef(angle, 0, 1, 0); + gl.glRotatef(-90, 1, 0, 0); + start = System.nanoTime(); - MD5Animation.interpolate(anim.frames[animInfo.getCurrentFrame()], anim.frames[animInfo.getNextFrame()], skeleton, animInfo.getInterpolation() ); - renderer.setSkeleton( skeleton ); - skinTime = (System.nanoTime() - start ) / 1000000000.0f; - + MD5Animation.interpolate(anim.frames[animInfo.getCurrentFrame()], anim.frames[animInfo.getNextFrame()], skeleton, + animInfo.getInterpolation()); + renderer.setSkeleton(skeleton); + skinTime = (System.nanoTime() - start) / 1000000000.0f; + start = System.nanoTime(); renderer.render(); - renderTime = (System.nanoTime()-start) / 1000000000.0f; + renderTime = (System.nanoTime() - start) / 1000000000.0f; } - - gl.glDisable( GL10.GL_DEPTH_TEST ); -// gl.glPolygonMode( GL10.GL_FRONT_AND_BACK, GL10.GL_FILL ); + + gl.glDisable(GL10.GL_DEPTH_TEST); +// gl.glPolygonMode( GL10.GL_FRONT_AND_BACK, GL10.GL_FILL ); batch.begin(); - batch.drawText( font, "fps: " + Gdx.graphics.getFramesPerSecond() + (renderer.isJniUsed()?", jni":", java"), 10, 20, Color.WHITE ); + batch.drawText(font, "fps: " + Gdx.graphics.getFramesPerSecond() + (renderer.isJniUsed() ? ", jni" : ", java"), 10, 20, + Color.WHITE); batch.end(); } - @Override - public void dispose() { + @Override public void dispose () { batch.dispose(); renderer.dispose(); font.dispose(); - + batch = null; renderer = null; font = null; - + System.gc(); - + Gdx.input.removeInputListener(this); } - @Override - public boolean keyDown(int keycode) { + @Override public boolean keyDown (int keycode) { // TODO Auto-generated method stub return false; } - @Override - public boolean keyTyped(char character) { + @Override public boolean keyTyped (char character) { // TODO Auto-generated method stub return false; } - @Override - public boolean keyUp(int keycode) { + @Override public boolean keyUp (int keycode) { // TODO Auto-generated method stub return false; } - @Override - public boolean touchDown(int x, int y, int pointer) { + @Override public boolean touchDown (int x, int y, int pointer) { // TODO Auto-generated method stub return false; } - @Override - public boolean touchDragged(int x, int y, int pointer) { + @Override public boolean touchDragged (int x, int y, int pointer) { // TODO Auto-generated method stub return false; } - @Override - public boolean touchUp(int x, int y, int pointer) - { - renderer.setUseJni( !renderer.isJniUsed() ); + @Override public boolean touchUp (int x, int y, int pointer) { + renderer.setUseJni(!renderer.isJniUsed()); return false; } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/ManagedTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/ManagedTest.java index d56c93061..e4f4bc1e9 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/ManagedTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/ManagedTest.java @@ -1,79 +1,62 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; +import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.RenderListener; -import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.Texture; -import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; +import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.VertexAttributes.Usage; -public class ManagedTest implements RenderListener -{ +public class ManagedTest implements RenderListener { Mesh mesh; Texture texture; - @Override - public void surfaceCreated() - { - if( mesh == null ) - { - mesh = new Mesh( true, false, 4, 4, - new VertexAttribute( Usage.Position, 2, "a_position" ), - new VertexAttribute( Usage.TextureCoordinates, 2, "a_texCoord" ) ); - mesh.setVertices( new float[] { -0.5f, -0.5f, 0, 0, - 0.5f, -0.5f, 1, 0, - 0.5f, 0.5f, 1, 1, - -0.5f, 0.5f, 0, 1 - }); - mesh.setIndices( new short[] { 0, 1, 2, 3 } ); - - texture = Gdx.graphics.newTexture( Gdx.files.getFileHandle( "data/badlogic.jpg", FileType.Internal), TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); + @Override public void surfaceCreated () { + if (mesh == null) { + mesh = new Mesh(true, false, 4, 4, new VertexAttribute(Usage.Position, 2, "a_position"), new VertexAttribute( + Usage.TextureCoordinates, 2, "a_texCoord")); + mesh.setVertices(new float[] {-0.5f, -0.5f, 0, 0, 0.5f, -0.5f, 1, 0, 0.5f, 0.5f, 1, 1, -0.5f, 0.5f, 0, 1}); + mesh.setIndices(new short[] {0, 1, 2, 3}); + + texture = Gdx.graphics.newTexture(Gdx.files.getFileHandle("data/badlogic.jpg", FileType.Internal), TextureFilter.MipMap, + TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); } } - - @Override - public void render() - { + + @Override public void render () { GL10 gl = Gdx.graphics.getGL10(); - gl.glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - gl.glClearColor( 0.7f, 0.7f, 0.7f, 1 ); - gl.glClear( GL10.GL_COLOR_BUFFER_BIT ); - - gl.glEnable(GL10.GL_TEXTURE_2D ); + gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + gl.glClearColor(0.7f, 0.7f, 0.7f, 1); + gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + + gl.glEnable(GL10.GL_TEXTURE_2D); texture.bind(); - mesh.render( GL10.GL_TRIANGLE_FAN ); + mesh.render(GL10.GL_TRIANGLE_FAN); } - - @Override - public void dispose( ) - { - + + @Override public void dispose () { + } - @Override - public void surfaceChanged( int width, int height) - { - + @Override public void surfaceChanged (int width, int height) { + } - - + } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/MeshMultitextureTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/MeshMultitextureTest.java index ccc350390..5d952c38d 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/MeshMultitextureTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/MeshMultitextureTest.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -5,82 +6,65 @@ import com.badlogic.gdx.RenderListener; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.Pixmap; -import com.badlogic.gdx.graphics.Texture; -import com.badlogic.gdx.graphics.VertexAttribute; -import com.badlogic.gdx.graphics.VertexAttributes; import com.badlogic.gdx.graphics.Pixmap.Format; +import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; +import com.badlogic.gdx.graphics.VertexAttribute; +import com.badlogic.gdx.graphics.VertexAttributes; -public class MeshMultitextureTest implements RenderListener -{ +public class MeshMultitextureTest implements RenderListener { Texture tex1; Texture tex2; Mesh mesh; - - @Override - public void dispose() { + + @Override public void dispose () { // TODO Auto-generated method stub - + } - @Override - public void render() - { + @Override public void render () { GL10 gl = Gdx.graphics.getGL10(); - gl.glEnable( GL10.GL_TEXTURE_2D ); - gl.glActiveTexture( GL10.GL_TEXTURE0 ); + gl.glEnable(GL10.GL_TEXTURE_2D); + gl.glActiveTexture(GL10.GL_TEXTURE0); tex1.bind(); - gl.glActiveTexture( GL10.GL_TEXTURE1 ); + gl.glActiveTexture(GL10.GL_TEXTURE1); tex2.bind(); - mesh.render( GL10.GL_TRIANGLES ); + mesh.render(GL10.GL_TRIANGLES); } - @Override - public void surfaceChanged(int width, int height) - { - + @Override public void surfaceChanged (int width, int height) { + } - @Override - public void surfaceCreated() - { - Pixmap pixmap = Gdx.graphics.newPixmap(256, 256, Format.RGBA8888 ); - pixmap.setColor(1, 1, 1, 1 ); + @Override public void surfaceCreated () { + Pixmap pixmap = Gdx.graphics.newPixmap(256, 256, Format.RGBA8888); + pixmap.setColor(1, 1, 1, 1); pixmap.fill(); - pixmap.setColor(0, 0, 0, 1 ); + pixmap.setColor(0, 0, 0, 1); pixmap.drawLine(0, 0, 256, 256); - pixmap.drawLine(256, 0, 0, 256); - tex1 = Gdx.graphics.newUnmanagedTexture( pixmap, TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); - - pixmap = Gdx.graphics.newPixmap( 256, 256, Format.RGBA8888 ); - pixmap.setColor( 1, 1, 1, 1 ); + pixmap.drawLine(256, 0, 0, 256); + tex1 = Gdx.graphics.newUnmanagedTexture(pixmap, TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, + TextureWrap.ClampToEdge); + + pixmap = Gdx.graphics.newPixmap(256, 256, Format.RGBA8888); + pixmap.setColor(1, 1, 1, 1); pixmap.fill(); - pixmap.setColor( 0, 0, 0, 1 ); - pixmap.drawLine( 128, 0, 128, 256 ); - tex2 = Gdx.graphics.newUnmanagedTexture( pixmap, TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); - - mesh = new Mesh( true, false, 3, 0, new VertexAttribute( VertexAttributes.Usage.Color, 4, "a_Color" ), - new VertexAttribute( VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoords1" ), - new VertexAttribute( VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoords2" ), - new VertexAttribute( VertexAttributes.Usage.Position, 3, "a_Position" ) ); - - mesh.setVertices( new float[] { - 1, 0, 0, 1, - 0, 1, - 0, 1, - -0.5f, -0.5f, 0, - - 0, 1, 0, 1, - 1, 1, - 1, 1, - 0.5f, -0.5f, 0, - - 0, 0, 1, 1, - 0.5f, 0, - 0.5f, 0, - 0, 0.5f, 0, - }); + pixmap.setColor(0, 0, 0, 1); + pixmap.drawLine(128, 0, 128, 256); + tex2 = Gdx.graphics.newUnmanagedTexture(pixmap, TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, + TextureWrap.ClampToEdge); + + mesh = new Mesh(true, false, 3, 0, new VertexAttribute(VertexAttributes.Usage.Color, 4, "a_Color"), new VertexAttribute( + VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoords1"), new VertexAttribute( + VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoords2"), new VertexAttribute(VertexAttributes.Usage.Position, 3, + "a_Position")); + + mesh.setVertices(new float[] {1, 0, 0, 1, 0, 1, 0, 1, -0.5f, -0.5f, 0, + + 0, 1, 0, 1, 1, 1, 1, 1, 0.5f, -0.5f, 0, + + 0, 0, 1, 1, 0.5f, 0, 0.5f, 0, 0, 0.5f, 0,}); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/MeshShaderTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/MeshShaderTest.java index 530909cb1..bae4f0f08 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/MeshShaderTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/MeshShaderTest.java @@ -1,134 +1,107 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; +import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.RenderListener; -import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Font; +import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.ShaderProgram; import com.badlogic.gdx.graphics.SpriteBatch; import com.badlogic.gdx.graphics.Texture; -import com.badlogic.gdx.graphics.VertexAttribute; -import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; +import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; -public class MeshShaderTest implements RenderListener -{ +public class MeshShaderTest implements RenderListener { SpriteBatch spriteBatch; Font font; ShaderProgram shader; - Mesh mesh; + Mesh mesh; Texture texture; Matrix4 matrix = new Matrix4(); - @Override - public void surfaceCreated( ) - { - if( shader == null ) - { - String vertexShader = "attribute vec4 a_position; \n" + - "attribute vec4 a_color;\n" + - "attribute vec2 a_texCoords;\n" + - "uniform mat4 u_worldView;\n" + - "varying vec4 v_color;" + - "varying vec2 v_texCoords;" + - "void main() \n" + - "{ \n" + - " v_color = vec4(a_color.x, a_color.y, a_color.z, 1); \n" + - " v_texCoords = a_texCoords; \n" + - " gl_Position = u_worldView * a_position; \n" + - "} \n"; - String fragmentShader = "precision mediump float;\n" + - "varying vec4 v_color;\n" + - "varying vec2 v_texCoords;\n" + - "uniform sampler2D u_texture;\n" + - "void main() \n" + - "{ \n" + - " gl_FragColor = v_color * texture2D(u_texture, v_texCoords);\n" + - "}"; - - shader = new ShaderProgram( vertexShader, fragmentShader ); - if( shader.isCompiled() == false ) - { - Gdx.app.log( "ShaderTest", shader.getLog() ); + @Override public void surfaceCreated () { + if (shader == null) { + String vertexShader = "attribute vec4 a_position; \n" + "attribute vec4 a_color;\n" + "attribute vec2 a_texCoords;\n" + + "uniform mat4 u_worldView;\n" + "varying vec4 v_color;" + "varying vec2 v_texCoords;" + + "void main() \n" + "{ \n" + + " v_color = vec4(a_color.x, a_color.y, a_color.z, 1); \n" + " v_texCoords = a_texCoords; \n" + + " gl_Position = u_worldView * a_position; \n" + "} \n"; + String fragmentShader = "precision mediump float;\n" + "varying vec4 v_color;\n" + "varying vec2 v_texCoords;\n" + + "uniform sampler2D u_texture;\n" + "void main() \n" + + "{ \n" + + " gl_FragColor = v_color * texture2D(u_texture, v_texCoords);\n" + "}"; + + shader = new ShaderProgram(vertexShader, fragmentShader); + if (shader.isCompiled() == false) { + Gdx.app.log("ShaderTest", shader.getLog()); System.exit(0); } - - mesh = new Mesh( true, false, 3, 3, - new VertexAttribute( Usage.Position, 3, "a_position" ), - new VertexAttribute( Usage.Color, 4, "a_color" ), - new VertexAttribute( Usage.TextureCoordinates, 2, "a_texCoords" ) ); - - mesh.setVertices( new float[] { -0.5f, -0.5f, 0, 1, 0, 0, 1, 0, 0, - 0.5f, -0.5f, 0, 0, 1, 0, 1, 1, 0, - 0, 0.5f, 0, 0, 0, 1, 1, 0.5f, 1 } ); - mesh.setIndices( new short[] { 0, 1, 2 } ); - - texture = Gdx.graphics.newTexture( Gdx.files.getFileHandle( "data/badlogic.jpg", FileType.Internal), TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); - - spriteBatch = new SpriteBatch( ); - font = Gdx.graphics.newFont( "Arial", 12, FontStyle.Plain ); + + mesh = new Mesh(true, false, 3, 3, new VertexAttribute(Usage.Position, 3, "a_position"), new VertexAttribute( + Usage.Color, 4, "a_color"), new VertexAttribute(Usage.TextureCoordinates, 2, "a_texCoords")); + + mesh.setVertices(new float[] {-0.5f, -0.5f, 0, 1, 0, 0, 1, 0, 0, 0.5f, -0.5f, 0, 0, 1, 0, 1, 1, 0, 0, 0.5f, 0, 0, 0, 1, + 1, 0.5f, 1}); + mesh.setIndices(new short[] {0, 1, 2}); + + texture = Gdx.graphics.newTexture(Gdx.files.getFileHandle("data/badlogic.jpg", FileType.Internal), TextureFilter.MipMap, + TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); + + spriteBatch = new SpriteBatch(); + font = Gdx.graphics.newFont("Arial", 12, FontStyle.Plain); } } - Vector3 axis = new Vector3( 0, 0, 1 ); + Vector3 axis = new Vector3(0, 0, 1); float angle = 0; - - @Override - public void render( ) - { + + @Override public void render () { angle += Gdx.graphics.getDeltaTime() * 45; - matrix.setToRotation( axis, angle ); - - Gdx.graphics.getGL20().glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - Gdx.graphics.getGL20().glClearColor( 0.2f, 0.2f, 0.2f, 1 ); - Gdx.graphics.getGL20().glClear( GL20.GL_COLOR_BUFFER_BIT ); - Gdx.graphics.getGL20().glEnable( GL20.GL_TEXTURE_2D ); + matrix.setToRotation(axis, angle); + + Gdx.graphics.getGL20().glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + Gdx.graphics.getGL20().glClearColor(0.2f, 0.2f, 0.2f, 1); + Gdx.graphics.getGL20().glClear(GL20.GL_COLOR_BUFFER_BIT); + Gdx.graphics.getGL20().glEnable(GL20.GL_TEXTURE_2D); texture.bind(); - shader.begin(); - shader.setUniformMatrix( "u_worldView", matrix ); - shader.setUniformi( "u_texture", 0 ); - mesh.render( shader, GL10.GL_TRIANGLES ); + shader.begin(); + shader.setUniformMatrix("u_worldView", matrix); + shader.setUniformi("u_texture", 0); + mesh.render(shader, GL10.GL_TRIANGLES); shader.end(); - + spriteBatch.begin(); - spriteBatch.drawText( font, "This is a test", 100, 100, Color.RED ); + spriteBatch.drawText(font, "This is a test", 100, 100, Color.RED); spriteBatch.end(); } - - @Override - public void surfaceChanged( int width, int height) - { - + + @Override public void surfaceChanged (int width, int height) { + } - - @Override - public void dispose( ) - { - Gdx.app.log( "MeshShaderTEst", "disposed" ); + + @Override public void dispose () { + Gdx.app.log("MeshShaderTEst", "disposed"); } - } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/MeshTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/MeshTest.java index 471a39647..08fa74daa 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/MeshTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/MeshTest.java @@ -1,75 +1,62 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; +import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.RenderListener; -import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.Texture; -import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; +import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.VertexAttributes.Usage; -public class MeshTest implements RenderListener -{ +public class MeshTest implements RenderListener { Mesh mesh; Texture texture; - - @Override - public void dispose( ) { + + @Override public void dispose () { // TODO Auto-generated method stub - + } - @Override - public void render( ) - { - Gdx.graphics.getGL10().glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - Gdx.graphics.getGL10().glEnable( GL10.GL_TEXTURE_2D ); + @Override public void render () { + Gdx.graphics.getGL10().glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + Gdx.graphics.getGL10().glEnable(GL10.GL_TEXTURE_2D); texture.bind(); - mesh.render( GL10.GL_TRIANGLES, 0, 3 ); + mesh.render(GL10.GL_TRIANGLES, 0, 3); } - @Override - public void surfaceChanged( int width, int height) { + @Override public void surfaceChanged (int width, int height) { // TODO Auto-generated method stub - + } - @Override - public void surfaceCreated( ) - { - if( mesh == null ) - { - mesh = new Mesh( true, false, 3, 3, - new VertexAttribute( Usage.Position, 3, "a_position" ), - new VertexAttribute( Usage.ColorPacked, 4, "a_color" ), - new VertexAttribute( Usage.TextureCoordinates, 2, "a_texCoords" ) ); - - mesh.setVertices( new float[] { -0.5f, -0.5f, 0, Color.toFloatBits(255, 0, 0, 255), 0, 0, - 0.5f, -0.5f, 0, Color.toFloatBits(0, 255, 0, 255), 1, 0, - 0, 0.5f, 0, Color.toFloatBits( 0, 0, 255, 255 ), 0.5f, 1 } ); - mesh.setIndices( new short[] { 0, 1, 2 } ); - + @Override public void surfaceCreated () { + if (mesh == null) { + mesh = new Mesh(true, false, 3, 3, new VertexAttribute(Usage.Position, 3, "a_position"), new VertexAttribute( + Usage.ColorPacked, 4, "a_color"), new VertexAttribute(Usage.TextureCoordinates, 2, "a_texCoords")); + + mesh.setVertices(new float[] {-0.5f, -0.5f, 0, Color.toFloatBits(255, 0, 0, 255), 0, 0, 0.5f, -0.5f, 0, + Color.toFloatBits(0, 255, 0, 255), 1, 0, 0, 0.5f, 0, Color.toFloatBits(0, 0, 255, 255), 0.5f, 1}); + mesh.setIndices(new short[] {0, 1, 2}); - texture = Gdx.graphics.newTexture( Gdx.files.getFileHandle( "data/badlogic.jpg", FileType.Internal), TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); + texture = Gdx.graphics.newTexture(Gdx.files.getFileHandle("data/badlogic.jpg", FileType.Internal), TextureFilter.MipMap, + TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/Mpg123Test.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/Mpg123Test.java index 9047e83d6..d8a5c26eb 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/Mpg123Test.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/Mpg123Test.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.nio.FloatBuffer; @@ -25,61 +23,54 @@ import com.badlogic.gdx.audio.analysis.AudioTools; import com.badlogic.gdx.audio.analysis.KissFFT; import com.badlogic.gdx.audio.io.Mpg123Decoder; -public class Mpg123Test implements RenderListener -{ +public class Mpg123Test implements RenderListener { - @Override - public void dispose( ) { + @Override public void dispose () { // TODO Auto-generated method stub } - @Override - public void render( ) - { + @Override public void render () { } - @Override - public void surfaceChanged( int width, int height) { + @Override public void surfaceChanged (int width, int height) { // TODO Auto-generated method stub } - @Override - public void surfaceCreated( ) - { -// Thread thread = new Thread( new Runnable() { + @Override public void surfaceCreated () { +// Thread thread = new Thread( new Runnable() { // -// public void run( ) -// { - String file = null; - if( Gdx.app.getType() == ApplicationType.Android ) - file = "/sdcard/audio/schism.mp3"; - else - file = "data/threeofaperfectpair.mp3"; - - Mpg123Decoder decoder = new Mpg123Decoder( file ); - ShortBuffer stereoSamples = AudioTools.allocateShortBuffer( 1024, decoder.getNumChannels() ); - ShortBuffer monoSamples = AudioTools.allocateShortBuffer( 1024, 1 ); - FloatBuffer spectrum = AudioTools.allocateFloatBuffer( 1024 / 2 + 1, 1); - KissFFT fft = new KissFFT( 1024 ); - - Gdx.app.log( "Mpg123", "rate: " + decoder.getRate() + ", channels: " + decoder.getNumChannels() + ", length: " + decoder.getLength() ); - - long start = System.nanoTime(); - while( decoder.readSamples( stereoSamples ) > 0 ) - { - AudioTools.convertToMono( stereoSamples, monoSamples, stereoSamples.capacity() ); - fft.spectrum( monoSamples, spectrum ); - } - - Gdx.app.log( "Mpg123", "took " + (System.nanoTime()-start) / 1000000000.0 ); - decoder.dispose(); -// } -// }); -// thread.setPriority(Thread.MAX_PRIORITY); -// thread.start(); +// public void run( ) +// { + String file = null; + if (Gdx.app.getType() == ApplicationType.Android) + file = "/sdcard/audio/schism.mp3"; + else + file = "data/threeofaperfectpair.mp3"; + + Mpg123Decoder decoder = new Mpg123Decoder(file); + ShortBuffer stereoSamples = AudioTools.allocateShortBuffer(1024, decoder.getNumChannels()); + ShortBuffer monoSamples = AudioTools.allocateShortBuffer(1024, 1); + FloatBuffer spectrum = AudioTools.allocateFloatBuffer(1024 / 2 + 1, 1); + KissFFT fft = new KissFFT(1024); + + Gdx.app.log("Mpg123", + "rate: " + decoder.getRate() + ", channels: " + decoder.getNumChannels() + ", length: " + decoder.getLength()); + + long start = System.nanoTime(); + while (decoder.readSamples(stereoSamples) > 0) { + AudioTools.convertToMono(stereoSamples, monoSamples, stereoSamples.capacity()); + fft.spectrum(monoSamples, spectrum); + } + + Gdx.app.log("Mpg123", "took " + (System.nanoTime() - start) / 1000000000.0); + decoder.dispose(); +// } +// }); +// thread.setPriority(Thread.MAX_PRIORITY); +// thread.start(); } - + } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/MultitouchTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/MultitouchTest.java index 053181e69..12101acdf 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/MultitouchTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/MultitouchTest.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -8,101 +9,77 @@ import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.ImmediateModeRenderer; import com.badlogic.gdx.graphics.OrthographicCamera; -public class MultitouchTest implements RenderListener, InputListener -{ +public class MultitouchTest implements RenderListener, InputListener { ImmediateModeRenderer renderer; OrthographicCamera camera; - Color[] colors = { Color.RED, Color.BLUE, Color.GREEN, Color.WHITE }; - - @Override - public void dispose( ) - { + Color[] colors = {Color.RED, Color.BLUE, Color.GREEN, Color.WHITE}; + + @Override public void dispose () { } - @Override - public void render( ) - { - Gdx.graphics.getGL10().glClear( GL10.GL_COLOR_BUFFER_BIT ); - Gdx.graphics.getGL10().glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - camera.setMatrices(); - renderer.begin( GL10.GL_TRIANGLES ); + @Override public void render () { + Gdx.graphics.getGL10().glClear(GL10.GL_COLOR_BUFFER_BIT); + Gdx.graphics.getGL10().glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + camera.setMatrices(); + renderer.begin(GL10.GL_TRIANGLES); int size = Math.max(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()) / 10; - for( int i = 0; i < 10; i++ ) - { - if( Gdx.input.isTouched(i) == false ) - continue; - + for (int i = 0; i < 10; i++) { + if (Gdx.input.isTouched(i) == false) continue; + float x = Gdx.input.getX(i); float y = Gdx.graphics.getHeight() - Gdx.input.getY(i) - 1; Color col = colors[i % colors.length]; - renderer.color( col.r, col.g, col.b, col.a ); - renderer.vertex( x, y + size, 0 ); - renderer.color( col.r, col.g, col.b, col.a ); - renderer.vertex( x + size, y - size, 0 ); - renderer.color( col.r, col.g, col.b, col.a ); - renderer.vertex( x - size, y - size, 0 ); + renderer.color(col.r, col.g, col.b, col.a); + renderer.vertex(x, y + size, 0); + renderer.color(col.r, col.g, col.b, col.a); + renderer.vertex(x + size, y - size, 0); + renderer.color(col.r, col.g, col.b, col.a); + renderer.vertex(x - size, y - size, 0); } - + renderer.end(); } - @Override - public void surfaceChanged( int width, int height) - { - + @Override public void surfaceChanged (int width, int height) { + } - @Override - public void surfaceCreated( ) - { - if( renderer == null ) - { - Gdx.app.log( "Multitouch", "multitouch supported: " + Gdx.input.supportsMultitouch() ); - Gdx.input.addInputListener( this ); // only add this once... - renderer = new ImmediateModeRenderer( ); - camera = new OrthographicCamera( ); - camera.setViewport( Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - camera.getPosition().set( Gdx.graphics.getWidth() / 2.0f, Gdx.graphics.getHeight() / 2.0f, 0 ); + @Override public void surfaceCreated () { + if (renderer == null) { + Gdx.app.log("Multitouch", "multitouch supported: " + Gdx.input.supportsMultitouch()); + Gdx.input.addInputListener(this); // only add this once... + renderer = new ImmediateModeRenderer(); + camera = new OrthographicCamera(); + camera.setViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + camera.getPosition().set(Gdx.graphics.getWidth() / 2.0f, Gdx.graphics.getHeight() / 2.0f, 0); } } - @Override - public boolean keyDown(int keycode) - { + @Override public boolean keyDown (int keycode) { return false; } - @Override - public boolean keyTyped(char character) - { + @Override public boolean keyTyped (char character) { return false; } - @Override - public boolean keyUp(int keycode) - { + @Override public boolean keyUp (int keycode) { return false; } - @Override - public boolean touchDown(int x, int y, int pointer) - { - Gdx.app.log( "Multitouch", "down: " + pointer ); + @Override public boolean touchDown (int x, int y, int pointer) { + Gdx.app.log("Multitouch", "down: " + pointer); return false; } - @Override - public boolean touchDragged(int x, int y, int pointer) - { - Gdx.app.log( "Multitouch", "drag: " + pointer ); + @Override public boolean touchDragged (int x, int y, int pointer) { + Gdx.app.log("Multitouch", "drag: " + pointer); return false; } - @Override - public boolean touchUp(int x, int y, int pointer) - { - Gdx.app.log( "Multitouch", "up: " + pointer ); + @Override public boolean touchUp (int x, int y, int pointer) { + Gdx.app.log("Multitouch", "up: " + pointer); return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/ObjTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/ObjTest.java index ca2349970..ad34bc92a 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/ObjTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/ObjTest.java @@ -1,24 +1,22 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; +import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputListener; import com.badlogic.gdx.RenderListener; -import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.ModelLoader; @@ -27,112 +25,95 @@ import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; -public class ObjTest implements RenderListener, InputListener -{ +public class ObjTest implements RenderListener, InputListener { PerspectiveCamera cam; Mesh mesh; Texture texture; float angleY = 0; float angleX = 0; - float[] lightColor = { 1, 1, 1, 0 }; - float[] lightPosition = { 2, 5, 10, 0 }; + float[] lightColor = {1, 1, 1, 0}; + float[] lightPosition = {2, 5, 10, 0}; float touchStartX = 0; float touchStartY = 0; - + long frameStart; int frames = 0; - @Override - public void surfaceCreated( ) - { - if( mesh == null ) - { - Gdx.input.addInputListener( this ); - - mesh = ModelLoader.loadObj( Gdx.files.readFile( "data/scene.obj", FileType.Internal ), true ); - texture = Gdx.graphics.newTexture( Gdx.files.getFileHandle( "data/villager.png", FileType.Internal), TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); - + @Override public void surfaceCreated () { + if (mesh == null) { + Gdx.input.addInputListener(this); + + mesh = ModelLoader.loadObj(Gdx.files.readFile("data/scene.obj", FileType.Internal), true); + texture = Gdx.graphics.newTexture(Gdx.files.getFileHandle("data/villager.png", FileType.Internal), TextureFilter.MipMap, + TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); + cam = new PerspectiveCamera(); - cam.getPosition().set( 2, 2, 2 ); - cam.getDirection().set( -1, -1, -1 ); + cam.getPosition().set(2, 2, 2); + cam.getDirection().set(-1, -1, -1); } frameStart = System.nanoTime(); } - @Override - public void surfaceChanged( int width, int height) - { - + @Override public void surfaceChanged (int width, int height) { + } - - @Override - public void render( ) - { + + @Override public void render () { GL10 gl = Gdx.graphics.getGL10(); - - gl.glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - gl.glClear( GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT ); - gl.glEnable( GL10.GL_DEPTH_TEST ); - gl.glEnable( GL10.GL_LIGHTING ); - gl.glEnable( GL10.GL_COLOR_MATERIAL ); - gl.glEnable( GL10.GL_TEXTURE_2D ); - - cam.setMatrices( ); - - gl.glEnable( GL10.GL_LIGHT0 ); - gl.glLightfv( GL10.GL_LIGHT0, GL10.GL_DIFFUSE, lightColor, 0 ); - gl.glLightfv( GL10.GL_LIGHT0, GL10.GL_POSITION, lightPosition, 0 ); - - gl.glRotatef(angleY, 0, 1, 0); - gl.glRotatef(angleX, 1, 0, 0 ); + + gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); + gl.glEnable(GL10.GL_DEPTH_TEST); + gl.glEnable(GL10.GL_LIGHTING); + gl.glEnable(GL10.GL_COLOR_MATERIAL); + gl.glEnable(GL10.GL_TEXTURE_2D); + + cam.setMatrices(); + + gl.glEnable(GL10.GL_LIGHT0); + gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_DIFFUSE, lightColor, 0); + gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, lightPosition, 0); + + gl.glRotatef(angleY, 0, 1, 0); + gl.glRotatef(angleX, 1, 0, 0); texture.bind(); - mesh.render( GL10.GL_TRIANGLES ); - - if( System.nanoTime() - frameStart > 1000000000 ) - { - Gdx.app.log( "Obj Test", "fps: " + frames ); + mesh.render(GL10.GL_TRIANGLES); + + if (System.nanoTime() - frameStart > 1000000000) { + Gdx.app.log("Obj Test", "fps: " + frames); frames = 0; frameStart = System.nanoTime(); } - + frames++; } - @Override - public void dispose( ) - { - - } - + @Override public void dispose () { + + } - @Override - public boolean keyDown(int keycode) { + @Override public boolean keyDown (int keycode) { // TODO Auto-generated method stub return false; } - @Override - public boolean keyTyped(char character) { + @Override public boolean keyTyped (char character) { // TODO Auto-generated method stub return false; } - @Override - public boolean keyUp(int keycode) { + @Override public boolean keyUp (int keycode) { // TODO Auto-generated method stub return false; } - @Override - public boolean touchDown(int x, int y, int pointer) { + @Override public boolean touchDown (int x, int y, int pointer) { touchStartX = x; touchStartY = y; return false; } - @Override - public boolean touchDragged(int x, int y, int pointer) - { + @Override public boolean touchDragged (int x, int y, int pointer) { angleY += (x - touchStartX); angleX += (y - touchStartY); touchStartX = x; @@ -140,8 +121,7 @@ public class ObjTest implements RenderListener, InputListener return false; } - @Override - public boolean touchUp(int x, int y, int pointer) { + @Override public boolean touchUp (int x, int y, int pointer) { // TODO Auto-generated method stub return false; } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/PerformanceTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/PerformanceTest.java index 9f2731623..a7fcbadbb 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/PerformanceTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/PerformanceTest.java @@ -1,81 +1,67 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; +import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.RenderListener; -import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.ModelLoader; -public class PerformanceTest implements RenderListener -{ +public class PerformanceTest implements RenderListener { boolean fixed = false; - + Mesh fpMesh; Mesh flMesh; long startTime = System.nanoTime(); int frames = 0; - - @Override - public void dispose( ) - { - + + @Override public void dispose () { + } - @Override - public void render( ) - { - Gdx.graphics.getGL10().glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); + @Override public void render () { + Gdx.graphics.getGL10().glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Mesh m = null; - if( fixed ) + if (fixed) m = fpMesh; - else + else m = flMesh; - - for( int i = 0; i < 10; i++ ) - { - m.render(GL10.GL_TRIANGLES ); + + for (int i = 0; i < 10; i++) { + m.render(GL10.GL_TRIANGLES); } - - if( (System.nanoTime() - startTime ) > 1000000000 ) - { - Gdx.app.log( "Performance", frames + " fps, " + ( m.getNumVertices() / 3 ) * frames * 10 + " tris/s" ); + + if ((System.nanoTime() - startTime) > 1000000000) { + Gdx.app.log("Performance", frames + " fps, " + (m.getNumVertices() / 3) * frames * 10 + " tris/s"); frames = 0; startTime = System.nanoTime(); } frames++; } - @Override - public void surfaceChanged( int width, int height) - { - + @Override public void surfaceChanged (int width, int height) { + } - @Override - public void surfaceCreated( ) - { - if( fpMesh == null ) - { - fpMesh = ModelLoader.loadObj( Gdx.files.readFile( "data/heavysphere.obj", FileType.Internal), false ); - flMesh = ModelLoader.loadObj( Gdx.files.readFile( "data/heavysphere.obj", FileType.Internal), false ); + @Override public void surfaceCreated () { + if (fpMesh == null) { + fpMesh = ModelLoader.loadObj(Gdx.files.readFile("data/heavysphere.obj", FileType.Internal), false); + flMesh = ModelLoader.loadObj(Gdx.files.readFile("data/heavysphere.obj", FileType.Internal), false); } } - + } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/Pong.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/Pong.java index 51a65c7d8..43a30dffb 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/Pong.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/Pong.java @@ -1,42 +1,38 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.RenderListener; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Font; +import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.SpriteBatch; import com.badlogic.gdx.graphics.VertexAttribute; -import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.math.Vector2; /** - * A simple Pong remake showing how easy it is to quickly - * prototype a game with libgdx. + * A simple Pong remake showing how easy it is to quickly prototype a game with libgdx. * * @author mzechner - * + * */ -public class Pong implements RenderListener -{ +public class Pong implements RenderListener { /** the camera **/ private OrthographicCamera camera; /** the MeshRenderer for the paddles **/ @@ -47,7 +43,7 @@ public class Pong implements RenderListener private Font font; /** sprite batch **/ private SpriteBatch spriteBatch; - + /** the position of the two paddles **/ private Vector2 leftPaddle = new Vector2(); private Vector2 rightPaddle = new Vector2(); @@ -56,7 +52,7 @@ public class Pong implements RenderListener private int rightScore = 0; /** the left paddle speed multiplicator, used so that the ai is not perfect **/ private float leftPaddleMulti = 1; - + /** some constants **/ private final int BALL_SPEED = 100; /** the position of the ball **/ @@ -65,32 +61,26 @@ public class Pong implements RenderListener private Vector2 ballDirection = new Vector2(); /** the current ball speed **/ private int ballSpeed = BALL_SPEED; - + /** score string **/ private String score = ""; - + /** - * Here we setup all the resources. A {@link MeshRenderer} - * for the paddles which we use for both, a MeshRenderer - * for the ball and a {@link Text} for rendering the score. + * Here we setup all the resources. A {@link MeshRenderer} for the paddles which we use for both, a MeshRenderer for the ball + * and a {@link Text} for rendering the score. */ - @Override - public void surfaceCreated( ) - { - if( camera == null ) - { - setupGraphics( ); - setupGame( ); + @Override public void surfaceCreated () { + if (camera == null) { + setupGraphics(); + setupGame(); } } - + /** - * This method sets up all the graphics related stuff like the - * Meshes, the camera and the Font + * This method sets up all the graphics related stuff like the Meshes, the camera and the Font * @param app */ - private void setupGraphics( ) - { + private void setupGraphics () { // // We first construct the paddle mesh which consists of // four 2D vertices forming a vertically elongated rectangle @@ -98,29 +88,23 @@ public class Pong implements RenderListener // texture coordinates or indices. Note that we use a fixed // point Mesh here. The paddle has dimensions (10, 60). // - paddleMesh = new Mesh( true, false, 4, 0, new VertexAttribute( Usage.Position, 2, "a_position" ) ); - paddleMesh.setVertices( new float[] { -5, -30, - 5, -30, - 5, 30, - -5, 30 } ); - - // + paddleMesh = new Mesh(true, false, 4, 0, new VertexAttribute(Usage.Position, 2, "a_position")); + paddleMesh.setVertices(new float[] {-5, -30, 5, -30, 5, 30, -5, 30}); + + // // We do the same for the ball which has dimensions (10,10) // - ballMesh = new Mesh( true, false, 4, 0, new VertexAttribute( Usage.Position, 2, "a_position" ) ); - ballMesh.setVertices( new float[] { -5, -5, - 5, -5, - 5, 5, - -5, 5 } ); - + ballMesh = new Mesh(true, false, 4, 0, new VertexAttribute(Usage.Position, 2, "a_position")); + ballMesh.setVertices(new float[] {-5, -5, 5, -5, 5, 5, -5, 5}); + // // We construct a new font from a system font. We assume // Arial is installed on both the desktop and Android. // - font = Gdx.graphics.newFont( "Arial", 30, FontStyle.Plain ); + font = Gdx.graphics.newFont("Arial", 30, FontStyle.Plain); score = "0 : 0"; - spriteBatch = new SpriteBatch( ); - + spriteBatch = new SpriteBatch(); + // // Finally we construct an {@link OrthographicCamera} which // will scale our scene to 480x320 pixels no matter what the @@ -128,194 +112,171 @@ public class Pong implements RenderListener // on devices like the Droid. The screen center will be at (0,0) // so that's the reference frame for our scene. // - camera = new OrthographicCamera( ); - camera.setViewport( 480, 320 ); + camera = new OrthographicCamera(); + camera.setViewport(480, 320); } - + /** - * This sets up the game data like the initial - * paddle positions and the ball position and - * direction. + * This sets up the game data like the initial paddle positions and the ball position and direction. */ - private void setupGame( ) - { - leftPaddle.set( -200, 20 ); - rightPaddle.set( 200, 0 ); - ball.set( 0, 0 ); - ballDirection.set( -1, 0 ); + private void setupGame () { + leftPaddle.set(-200, 20); + rightPaddle.set(200, 0); + ball.set(0, 0); + ballDirection.set(-1, 0); } - - @Override - public void dispose( ) - { - + + @Override public void dispose () { + } - @Override - public void render( ) - { + @Override public void render () { // we update the game state so things move. updateGame(); - + // First we clear the screen GL10 gl = Gdx.graphics.getGL10(); - gl.glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - gl.glClear( GL10.GL_COLOR_BUFFER_BIT ); - + gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + // Next we update the camera and set the camera matrix camera.update(); - gl.glMatrixMode( GL10.GL_PROJECTION ); - gl.glLoadMatrixf( camera.getCombinedMatrix().val, 0 ); - gl.glMatrixMode( GL10.GL_MODELVIEW ); + gl.glMatrixMode(GL10.GL_PROJECTION); + gl.glLoadMatrixf(camera.getCombinedMatrix().val, 0); + gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); - + // Now we render the ball, we remember that we // Defined 4 vertices so we use a triangle fan // We also push and pop the matrix. This is not really // necessary as the model view matrix doesn't contain // anything at this point. gl.glPushMatrix(); - gl.glTranslatef( ball.x, ball.y, 0 ); + gl.glTranslatef(ball.x, ball.y, 0); ballMesh.render(GL10.GL_TRIANGLE_FAN); gl.glPopMatrix(); - + // Rendering the two paddles works analogous gl.glPushMatrix(); - gl.glTranslatef( leftPaddle.x, leftPaddle.y, 0 ); + gl.glTranslatef(leftPaddle.x, leftPaddle.y, 0); paddleMesh.render(GL10.GL_TRIANGLE_FAN); gl.glPopMatrix(); - + gl.glPushMatrix(); - gl.glTranslatef( rightPaddle.x, rightPaddle.y, 0 ); + gl.glTranslatef(rightPaddle.x, rightPaddle.y, 0); paddleMesh.render(GL10.GL_TRIANGLE_FAN); gl.glPopMatrix(); - + // Finally we render the text centered at the top // of the screen. We use the text bounds for this. // For text to be transparent we have to enable blending and texturing. // We could setup blending once but i'm lazy :) spriteBatch.begin(); - spriteBatch.drawText( font, score, Gdx.graphics.getWidth() / 2 - font.getStringWidth(score) / 2, Gdx.graphics.getHeight() - font.getLineHeight(), Color.WHITE ); + spriteBatch.drawText(font, score, Gdx.graphics.getWidth() / 2 - font.getStringWidth(score) / 2, Gdx.graphics.getHeight() + - font.getLineHeight(), Color.WHITE); spriteBatch.end(); } /** - * Updates the game state, moves the ball, - * checks for collisions or whether the ball - * has left the playfield. + * Updates the game state, moves the ball, checks for collisions or whether the ball has left the playfield. * * @param deltaTime the time elapsed since the last frame */ - private void updateGame( ) - { + private void updateGame () { // the delta time so we can do frame independant time based movement float deltaTime = Gdx.graphics.getDeltaTime(); - + // move the ball with a velocity of 50 pixels // per second. The ballDirection is a unit vector // we simply scale by the velocity. - ball.add( ballSpeed * ballDirection.x * deltaTime, ballSpeed * ballDirection.y * deltaTime ); - + ball.add(ballSpeed * ballDirection.x * deltaTime, ballSpeed * ballDirection.y * deltaTime); + // Next we check wheter the ball left the field to // the left or to the right and update the score - if( ball.x < -240 ) - { - ball.set( 0, 0 ); // reset to center - ballSpeed = BALL_SPEED; // reset the ball speed - ballDirection.set( (float)Math.random() + 0.1f, (float)Math.random() ).nor(); // new ball direction, must be unit length - rightScore++; // right paddle scored! + if (ball.x < -240) { + ball.set(0, 0); // reset to center + ballSpeed = BALL_SPEED; // reset the ball speed + ballDirection.set((float)Math.random() + 0.1f, (float)Math.random()).nor(); // new ball direction, must be unit length + rightScore++; // right paddle scored! score = leftScore + " : " + rightScore; // we set the left paddle multiplicator here which governs // how fast the left paddle can follow the ball. - leftPaddleMulti = (float)Math.min( 1, Math.random() + 0.3f ); + leftPaddleMulti = (float)Math.min(1, Math.random() + 0.3f); } - - if( ball.x > 240 ) - { - ball.set( 0, 0 ); // reset to center - ballSpeed = BALL_SPEED; // reset the ball speed - ballDirection.set( (float)Math.random() + 0.1f, (float)Math.random() ).nor(); // new ball direction, must be unit length - leftScore++; // left paddle scored! + + if (ball.x > 240) { + ball.set(0, 0); // reset to center + ballSpeed = BALL_SPEED; // reset the ball speed + ballDirection.set((float)Math.random() + 0.1f, (float)Math.random()).nor(); // new ball direction, must be unit length + leftScore++; // left paddle scored! score = leftScore + " : " + rightScore; // we set the left paddle multiplicator here which governs // how fast the left paddle can follow the ball. - leftPaddleMulti = (float)Math.min( 1, Math.random() + 0.3f ); + leftPaddleMulti = (float)Math.min(1, Math.random() + 0.3f); } - + // if the ball is hitting the bottom or top we // reverse its direction in y so that it bounces - if( ball.y > 160 ) - { + if (ball.y > 160) { ballDirection.y = -ballDirection.y; ball.y = 160; } - - if( ball.y < -160 ) - { + + if (ball.y < -160) { ballDirection.y = -ballDirection.y; ball.y = -160; } - + // if the ball is heading towards the right paddle and // has hit it we reflect it - if( ballDirection.x > 0 && ball.x > rightPaddle.x - 5 && ball.x < rightPaddle.x + 5 && - ball.y > rightPaddle.y - 30 && ball.y < rightPaddle.y + 30 ) - { + if (ballDirection.x > 0 && ball.x > rightPaddle.x - 5 && ball.x < rightPaddle.x + 5 && ball.y > rightPaddle.y - 30 + && ball.y < rightPaddle.y + 30) { ball.x = rightPaddle.x - 6; // set the position of a little so we don't get to this code in the next frame ballDirection.x = -ballDirection.x; float sign = Math.signum(ball.y - rightPaddle.y); - ballDirection.y = sign * (float)Math.abs(ball.y - rightPaddle.y) / 30; // reflect it depending on where the paddle was hit + ballDirection.y = sign * (float)Math.abs(ball.y - rightPaddle.y) / 30; // reflect it depending on where the paddle was +// hit ballDirection.nor(); ballSpeed += 10; // and faster! - if( ballSpeed > 300 ) - ballSpeed = 300; + if (ballSpeed > 300) ballSpeed = 300; } - + // and the same for the left paddle - if( ballDirection.x < 0 && ball.x < leftPaddle.x + 5 && ball.x > leftPaddle.x - 5 && - ball.y > leftPaddle.y - 30 && ball.y < leftPaddle.y + 30 ) - { + if (ballDirection.x < 0 && ball.x < leftPaddle.x + 5 && ball.x > leftPaddle.x - 5 && ball.y > leftPaddle.y - 30 + && ball.y < leftPaddle.y + 30) { ball.x = leftPaddle.x + 6; // set the position of a little so we don't get to this code in the next frame ballDirection.x = -ballDirection.x; - float sign =(float)Math.signum(ball.y - leftPaddle.y); - ballDirection.y = sign * (float)Math.abs(ball.y - leftPaddle.y) / 30; // reflect it depending on where the paddle was hit + float sign = (float)Math.signum(ball.y - leftPaddle.y); + ballDirection.y = sign * (float)Math.abs(ball.y - leftPaddle.y) / 30; // reflect it depending on where the paddle was hit ballDirection.nor(); ballSpeed += 10; // and faster! - if( ballSpeed > 300 ) - ballSpeed = 300; + if (ballSpeed > 300) ballSpeed = 300; // we set the left paddle multiplicator here which governs // how fast the left paddle can follow the ball. - leftPaddleMulti = (float)Math.min( 1, Math.random() + 0.3f ); + leftPaddleMulti = (float)Math.min(1, Math.random() + 0.3f); } - + // Has the user touched the screen? then position the paddle - if( Gdx.input.isTouched() ) - { + if (Gdx.input.isTouched()) { // get the touch coordinates and translate them // to the game coordinate system. float touchX = 480 * (Gdx.input.getX() / (float)Gdx.graphics.getWidth() - 0.5f); float touchY = 320 * (0.5f - Gdx.input.getY() / (float)Gdx.graphics.getHeight()); - - if( touchX > rightPaddle.x ) - rightPaddle.y = touchY; + + if (touchX > rightPaddle.x) rightPaddle.y = touchY; } - + // very very simple ai. moves when the ball is heading towards // the left paddle - if( ballDirection.x < 0 ) - { + if (ballDirection.x < 0) { float dir = (float)Math.signum(ball.y - leftPaddle.y); - leftPaddle.y += dir * deltaTime * (ballSpeed * leftPaddleMulti ); - if( dir > 0 && leftPaddle.y > ball.y ) - leftPaddle.y = ball.y; - if( dir < 0 && leftPaddle.y < ball.y ) - leftPaddle.y = ball.y; + leftPaddle.y += dir * deltaTime * (ballSpeed * leftPaddleMulti); + if (dir > 0 && leftPaddle.y > ball.y) leftPaddle.y = ball.y; + if (dir < 0 && leftPaddle.y < ball.y) leftPaddle.y = ball.y; } } - @Override - public void surfaceChanged( int width, int height) - { - - } + @Override public void surfaceChanged (int width, int height) { + + } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/SimpleTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/SimpleTest.java index c5313743a..be66650c7 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/SimpleTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/SimpleTest.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.ApplicationListener; @@ -21,94 +19,75 @@ import com.badlogic.gdx.InputListener; import com.badlogic.gdx.RenderListener; import com.badlogic.gdx.graphics.GL10; -public class SimpleTest implements RenderListener, InputListener, ApplicationListener -{ +public class SimpleTest implements RenderListener, InputListener, ApplicationListener { float r = 1, g = 0, b = 0; - - @Override - public void surfaceCreated() - { - Gdx.input.addInputListener( this ); - Gdx.app.setApplicationListener( this ); - Gdx.app.log( "Simple Test", "Thread=" + Thread.currentThread().getId() + ", surface created" ); + @Override public void surfaceCreated () { + Gdx.input.addInputListener(this); + Gdx.app.setApplicationListener(this); + Gdx.app.log("Simple Test", "Thread=" + Thread.currentThread().getId() + ", surface created"); } - - @Override - public void render( ) - { + + @Override public void render () { GL10 gl = Gdx.app.getGraphics().getGL10(); - - gl.glClearColor( r, g, b, 1 ); - gl.glClear( GL10.GL_COLOR_BUFFER_BIT ); - + + gl.glClearColor(r, g, b, 1); + gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + } - @Override - public void dispose( ) - { - Gdx.app.log( "Simple Test", "Thread=" + Thread.currentThread().getId() + ", render listener disposed" ); - } - - @Override - public void destroy( ) - { - Gdx.app.log( "Simple Test", "Thread=" + Thread.currentThread().getId() + ", application destroyed" ); + @Override public void dispose () { + Gdx.app.log("Simple Test", "Thread=" + Thread.currentThread().getId() + ", render listener disposed"); } - @Override - public boolean keyDown(int keycode) { + @Override public void destroy () { + Gdx.app.log("Simple Test", "Thread=" + Thread.currentThread().getId() + ", application destroyed"); + } + + @Override public boolean keyDown (int keycode) { // TODO Auto-generated method stub return false; } - @Override - public boolean keyTyped(char character) { + @Override public boolean keyTyped (char character) { // TODO Auto-generated method stub return false; } - @Override - public boolean keyUp(int keycode) { + @Override public boolean keyUp (int keycode) { // TODO Auto-generated method stub return false; } - @Override - public boolean touchDown(int x, int y, int pointer) { + @Override public boolean touchDown (int x, int y, int pointer) { // TODO Auto-generated method stub return false; } - @Override - public boolean touchDragged(int x, int y, int pointer) { + @Override public boolean touchDragged (int x, int y, int pointer) { // TODO Auto-generated method stub return false; } - @Override - public boolean touchUp(int x, int y, int pointer) { + @Override public boolean touchUp (int x, int y, int pointer) { r = (float)Math.random(); g = (float)Math.random(); b = (float)Math.random(); return false; } - @Override - public void pause( ) { + @Override public void pause () { // TODO Auto-generated method stub - + } - @Override - public void resume( ) { + @Override public void resume () { // TODO Auto-generated method stub - + } - @Override - public void surfaceChanged( int width, int height) { + @Override public void surfaceChanged (int width, int height) { // TODO Auto-generated method stub - + } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/SoundTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/SoundTest.java index 1ce119ef8..abafa9400 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/SoundTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/SoundTest.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Files.FileType; @@ -22,89 +20,67 @@ import com.badlogic.gdx.RenderListener; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.audio.Sound; -public class SoundTest implements RenderListener, InputListener -{ +public class SoundTest implements RenderListener, InputListener { Sound sound; Music music; float volume = 1.0f; - @Override - public void dispose( ) - { - + @Override public void dispose () { + } - @Override - public void render( ) - { + @Override public void render () { try { - Thread.sleep( 100 ); + Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } - @Override - public void surfaceChanged(int width, int height) - { - + @Override public void surfaceChanged (int width, int height) { + } - @Override - public void surfaceCreated( ) - { - if( music == null ) - { - Gdx.input.addInputListener( this ); - sound = Gdx.audio.newSound( Gdx.files.getFileHandle( "data/shotgun.wav", FileType.Internal ) ); - - music = Gdx.audio.newMusic( Gdx.files.getFileHandle( "data/cloudconnected.ogg", FileType.Internal ) ); - music.play(); - music.setLooping( true ); + @Override public void surfaceCreated () { + if (music == null) { + Gdx.input.addInputListener(this); + sound = Gdx.audio.newSound(Gdx.files.getFileHandle("data/shotgun.wav", FileType.Internal)); + + music = Gdx.audio.newMusic(Gdx.files.getFileHandle("data/cloudconnected.ogg", FileType.Internal)); + music.play(); + music.setLooping(true); } } - @Override - public boolean keyDown(int keycode) - { + @Override public boolean keyDown (int keycode) { return false; } - @Override - public boolean keyTyped(char character) - { - if( character == '+' ) - volume += 0.1f; - if( character == '-' ) - volume -= 0.1f; - music.setVolume( volume ); - + @Override public boolean keyTyped (char character) { + if (character == '+') volume += 0.1f; + if (character == '-') volume -= 0.1f; + music.setVolume(volume); + return false; } - @Override - public boolean keyUp(int keycode) - { - + @Override public boolean keyUp (int keycode) { + return false; } - @Override - public boolean touchDown(int x, int y, int pointer) { + @Override public boolean touchDown (int x, int y, int pointer) { sound.play(); return false; } - @Override - public boolean touchDragged(int x, int y, int pointer) { + @Override public boolean touchDragged (int x, int y, int pointer) { // TODO Auto-generated method stub return false; } - @Override - public boolean touchUp(int x, int y, int pointer) - { + @Override public boolean touchUp (int x, int y, int pointer) { return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteBatchRotationTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteBatchRotationTest.java index fac210e5f..39c4b5af5 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteBatchRotationTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteBatchRotationTest.java @@ -1,38 +1,35 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.IntBuffer; +import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.RenderListener; -import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Font; +import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.SpriteBatch; import com.badlogic.gdx.graphics.Texture; -import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; -public class SpriteBatchRotationTest implements RenderListener -{ +public class SpriteBatchRotationTest implements RenderListener { SpriteBatch spriteBatch; Texture texture; Font font; @@ -40,75 +37,69 @@ public class SpriteBatchRotationTest implements RenderListener float scale = 1; float vScale = 1; IntBuffer pixelBuffer; - - @Override - public void dispose( ) - { - + + @Override public void dispose () { + } - @Override - public void render( ) - { - Gdx.graphics.getGL10().glClear( GL10.GL_COLOR_BUFFER_BIT ); + @Override public void render () { + Gdx.graphics.getGL10().glClear(GL10.GL_COLOR_BUFFER_BIT); spriteBatch.begin(); - spriteBatch.draw( texture, 16, 10, 16, 16, 32, 32, 1, 1, 0, 0, 0, texture.getWidth(), texture.getHeight(), Color.WHITE, false, false ); - spriteBatch.draw( texture, 64, 10, 32, 32, 0, 0, texture.getWidth(), texture.getHeight(), Color.WHITE, false, false ); - spriteBatch.draw( texture, 112, 10, 0, 0, texture.getWidth(), texture.getHeight(), Color.WHITE ); - - spriteBatch.draw( texture, 16, 58, 16, 16, 32, 32, 1, 1, angle, 0, 0, texture.getWidth(), texture.getHeight(), Color.WHITE, false, false ); - spriteBatch.draw( texture, 64, 58, 16, 16, 32, 32, scale, scale, 0, 0, 0, texture.getWidth(), texture.getHeight(), Color.WHITE, false, false ); - spriteBatch.draw( texture, 112, 58, 16, 16, 32, 32, scale, scale, angle, 0, 0, texture.getWidth(), texture.getHeight(), Color.WHITE, false, false ); - spriteBatch.draw( texture, 160, 58, 0, 0, 32, 32, scale, scale, angle, 0, 0, texture.getWidth(), texture.getHeight(), Color.WHITE, false, false ); + spriteBatch.draw(texture, 16, 10, 16, 16, 32, 32, 1, 1, 0, 0, 0, texture.getWidth(), texture.getHeight(), Color.WHITE, + false, false); + spriteBatch.draw(texture, 64, 10, 32, 32, 0, 0, texture.getWidth(), texture.getHeight(), Color.WHITE, false, false); + spriteBatch.draw(texture, 112, 10, 0, 0, texture.getWidth(), texture.getHeight(), Color.WHITE); + + spriteBatch.draw(texture, 16, 58, 16, 16, 32, 32, 1, 1, angle, 0, 0, texture.getWidth(), texture.getHeight(), Color.WHITE, + false, false); + spriteBatch.draw(texture, 64, 58, 16, 16, 32, 32, scale, scale, 0, 0, 0, texture.getWidth(), texture.getHeight(), + Color.WHITE, false, false); + spriteBatch.draw(texture, 112, 58, 16, 16, 32, 32, scale, scale, angle, 0, 0, texture.getWidth(), texture.getHeight(), + Color.WHITE, false, false); + spriteBatch.draw(texture, 160, 58, 0, 0, 32, 32, scale, scale, angle, 0, 0, texture.getWidth(), texture.getHeight(), + Color.WHITE, false, false); - - spriteBatch.drawText( font, "Test", 208, 10, Color.WHITE ); - spriteBatch.end(); + spriteBatch.drawText(font, "Test", 208, 10, Color.WHITE); + spriteBatch.end(); Gdx.graphics.getGL10().glFlush(); - -// if( false ) -// { -// Gdx.graphics.getGL10().glReadPixels( 16, 10, 1, 1, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, pixelBuffer ); -// if( pixelBuffer.get(0) != 0xff00ff00 ) -// throw new GdxRuntimeException( "not pixel perfect!" ); -// Gdx.graphics.getGL10().glReadPixels( 47, 10, 1, 1, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, pixelBuffer ); -// if( pixelBuffer.get(0) != 0xffff0000 ) -// throw new GdxRuntimeException( "not pixel perfect!" ); -// Gdx.graphics.getGL10().glReadPixels( 16, 41, 1, 1, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, pixelBuffer ); -// if( pixelBuffer.get(0) != 0xff0000ff ) -// throw new GdxRuntimeException( "not pixel perfect!" ); -// } - + +// if( false ) +// { +// Gdx.graphics.getGL10().glReadPixels( 16, 10, 1, 1, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, pixelBuffer ); +// if( pixelBuffer.get(0) != 0xff00ff00 ) +// throw new GdxRuntimeException( "not pixel perfect!" ); +// Gdx.graphics.getGL10().glReadPixels( 47, 10, 1, 1, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, pixelBuffer ); +// if( pixelBuffer.get(0) != 0xffff0000 ) +// throw new GdxRuntimeException( "not pixel perfect!" ); +// Gdx.graphics.getGL10().glReadPixels( 16, 41, 1, 1, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, pixelBuffer ); +// if( pixelBuffer.get(0) != 0xff0000ff ) +// throw new GdxRuntimeException( "not pixel perfect!" ); +// } + angle += 20 * Gdx.graphics.getDeltaTime(); scale += vScale * Gdx.graphics.getDeltaTime(); - if( scale > 2 ) - { + if (scale > 2) { vScale = -vScale; scale = 2; } - if( scale < 0 ) - { + if (scale < 0) { vScale = -vScale; scale = 0; } - + } - @Override - public void surfaceChanged( int width, int height) - { - + @Override public void surfaceChanged (int width, int height) { + } - @Override - public void surfaceCreated( ) - { - if( spriteBatch == null ) - { - spriteBatch = new SpriteBatch( ); - texture = Gdx.graphics.newTexture( Gdx.files.getFileHandle( "data/test.png", FileType.Internal ), TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); - font = Gdx.graphics.newFont( "Arial", 12, FontStyle.Plain ); - ByteBuffer buffer = ByteBuffer.allocateDirect( 4 ); + @Override public void surfaceCreated () { + if (spriteBatch == null) { + spriteBatch = new SpriteBatch(); + texture = Gdx.graphics.newTexture(Gdx.files.getFileHandle("data/test.png", FileType.Internal), TextureFilter.Linear, + TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); + font = Gdx.graphics.newFont("Arial", 12, FontStyle.Plain); + ByteBuffer buffer = ByteBuffer.allocateDirect(4); buffer.order(ByteOrder.nativeOrder()); pixelBuffer = buffer.asIntBuffer(); } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteBatchShaderTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteBatchShaderTest.java index ea680566c..3fae573dc 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteBatchShaderTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteBatchShaderTest.java @@ -1,143 +1,131 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; +import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.RenderListener; -import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Font; +import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.Pixmap; +import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.SpriteBatch; import com.badlogic.gdx.graphics.Texture; -import com.badlogic.gdx.graphics.Font.FontStyle; -import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; -public class SpriteBatchShaderTest implements RenderListener -{ +public class SpriteBatchShaderTest implements RenderListener { int SPRITES = 500; - + long startTime = System.nanoTime(); int frames = 0; - + Texture texture; Texture texture2; Font font; SpriteBatch spriteBatch; - int coords[] = new int[SPRITES*2]; - int coords2[] = new int[SPRITES*2]; - - Color col = new Color( 1, 1, 1, 0.6f ); - + int coords[] = new int[SPRITES * 2]; + int coords2[] = new int[SPRITES * 2]; + + Color col = new Color(1, 1, 1, 0.6f); + Mesh mesh; - float vertices[] = new float[SPRITES * 6 * ( 2 + 2 + 4 )]; - - @Override - public void dispose( ) - { - + float vertices[] = new float[SPRITES * 6 * (2 + 2 + 4)]; + + @Override public void dispose () { + } - @Override - public void render( ) - { + @Override public void render () { GL20 gl = Gdx.graphics.getGL20(); - gl.glClearColor( 0.7f, 0.7f, 0.7f, 1 ); - gl.glClear( GL20.GL_COLOR_BUFFER_BIT ); - + gl.glClearColor(0.7f, 0.7f, 0.7f, 1); + gl.glClear(GL20.GL_COLOR_BUFFER_BIT); + float begin = 0; float end = 0; float draw1 = 0; float draw2 = 0; float drawText = 0; - + long start = System.nanoTime(); - spriteBatch.begin(); - begin = (System.nanoTime()-start)/1000000000.0f; - + spriteBatch.begin(); + begin = (System.nanoTime() - start) / 1000000000.0f; + int len = coords.length; start = System.nanoTime(); - for( int i = 0; i < len; i+=2 ) - spriteBatch.draw( texture, coords[i], coords[i+1], 0, 0, 32, 32, Color.WHITE ); - draw1 = (System.nanoTime()-start)/1000000000.0f; - + for (int i = 0; i < len; i += 2) + spriteBatch.draw(texture, coords[i], coords[i + 1], 0, 0, 32, 32, Color.WHITE); + draw1 = (System.nanoTime() - start) / 1000000000.0f; + start = System.nanoTime(); - for( int i = 0; i < coords2.length; i+=2 ) - spriteBatch.draw( texture2, coords2[i], coords2[i+1], 0, 0, 32, 32, col ); - draw2 = (System.nanoTime()-start)/1000000000.0f; - + for (int i = 0; i < coords2.length; i += 2) + spriteBatch.draw(texture2, coords2[i], coords2[i + 1], 0, 0, 32, 32, col); + draw2 = (System.nanoTime() - start) / 1000000000.0f; + start = System.nanoTime(); - spriteBatch.drawText( font, "Question?", 100, 300, Color.RED ); - spriteBatch.drawText( font, "and another this is a test", 200, 100, Color.WHITE ); - spriteBatch.drawText( font, "all hail and another this is a test", 200, 200, Color.WHITE ); - drawText = (System.nanoTime()-start)/1000000000.0f; - + spriteBatch.drawText(font, "Question?", 100, 300, Color.RED); + spriteBatch.drawText(font, "and another this is a test", 200, 100, Color.WHITE); + spriteBatch.drawText(font, "all hail and another this is a test", 200, 200, Color.WHITE); + drawText = (System.nanoTime() - start) / 1000000000.0f; + start = System.nanoTime(); spriteBatch.end(); - end = (System.nanoTime()-start)/1000000000.0f; - - if( System.nanoTime() - startTime > 1000000000 ) - { - Gdx.app.log( "SpriteBatch", "fps: " + frames + ", render calls: " + spriteBatch.renderCalls + ", " + begin + ", " + draw1 + ", " + draw2 + ", " + drawText + ", " + end ); + end = (System.nanoTime() - start) / 1000000000.0f; + + if (System.nanoTime() - startTime > 1000000000) { + Gdx.app.log("SpriteBatch", "fps: " + frames + ", render calls: " + spriteBatch.renderCalls + ", " + begin + ", " + draw1 + + ", " + draw2 + ", " + drawText + ", " + end); frames = 0; startTime = System.nanoTime(); } frames++; - } + } + + @Override public void surfaceChanged (int width, int height) { - @Override - public void surfaceChanged( int width, int height) - { - } - @Override - public void surfaceCreated( ) - { - if( spriteBatch == null ) - spriteBatch = new SpriteBatch( ); - - Pixmap pixmap = Gdx.graphics.newPixmap( Gdx.files.getFileHandle( "data/badlogicsmall.jpg", FileType.Internal ) ); -// pixmap.setColor( 0, 0, 0, 0 ); -// pixmap.fillCircle( 16, 16, 4 ); - texture = Gdx.graphics.newUnmanagedTexture( 32, 32, Format.RGB565, TextureFilter.Nearest, TextureFilter.Nearest, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); - texture.draw( pixmap, 0, 0); - - pixmap = Gdx.graphics.newPixmap(32, 32, Format.RGB565 ); - pixmap.setColor(1, 1, 0, 0.7f ); + @Override public void surfaceCreated () { + if (spriteBatch == null) spriteBatch = new SpriteBatch(); + + Pixmap pixmap = Gdx.graphics.newPixmap(Gdx.files.getFileHandle("data/badlogicsmall.jpg", FileType.Internal)); +// pixmap.setColor( 0, 0, 0, 0 ); +// pixmap.fillCircle( 16, 16, 4 ); + texture = Gdx.graphics.newUnmanagedTexture(32, 32, Format.RGB565, TextureFilter.Nearest, TextureFilter.Nearest, + TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); + texture.draw(pixmap, 0, 0); + + pixmap = Gdx.graphics.newPixmap(32, 32, Format.RGB565); + pixmap.setColor(1, 1, 0, 0.7f); pixmap.fill(); -// pixmap.setColor( 0, 0, 0, 0 ); -// pixmap.fillCircle( 16, 16, 4 ); -// - texture2 = Gdx.graphics.newUnmanagedTexture( pixmap, TextureFilter.Nearest, TextureFilter.Nearest, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); - - if( font == null ) - font = Gdx.graphics.newFont( "Arial", 32, FontStyle.Plain ); - - for( int i = 0; i < coords.length; i+=2 ) - { +// pixmap.setColor( 0, 0, 0, 0 ); +// pixmap.fillCircle( 16, 16, 4 ); +// + texture2 = Gdx.graphics.newUnmanagedTexture(pixmap, TextureFilter.Nearest, TextureFilter.Nearest, TextureWrap.ClampToEdge, + TextureWrap.ClampToEdge); + + if (font == null) font = Gdx.graphics.newFont("Arial", 32, FontStyle.Plain); + + for (int i = 0; i < coords.length; i += 2) { coords[i] = (int)(Math.random() * Gdx.graphics.getWidth()); - coords[i+1] = (int)(Math.random() * Gdx.graphics.getHeight()); + coords[i + 1] = (int)(Math.random() * Gdx.graphics.getHeight()); coords2[i] = (int)(Math.random() * Gdx.graphics.getWidth()); - coords2[i+1] = (int)(Math.random() * Gdx.graphics.getHeight()); - } + coords2[i + 1] = (int)(Math.random() * Gdx.graphics.getHeight()); + } } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteBatchTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteBatchTest.java index 544858a07..295af79b1 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteBatchTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteBatchTest.java @@ -1,292 +1,262 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; +import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputListener; import com.badlogic.gdx.RenderListener; -import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Font; +import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Pixmap; +import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.Sprite; import com.badlogic.gdx.graphics.SpriteBatch; import com.badlogic.gdx.graphics.Texture; -import com.badlogic.gdx.graphics.Font.FontStyle; -import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; -public class SpriteBatchTest implements RenderListener, InputListener -{ +public class SpriteBatchTest implements RenderListener, InputListener { int SPRITES = 400 / 2; - + long startTime = System.nanoTime(); int frames = 0; - + Texture texture; Texture texture2; Font font; SpriteBatch spriteBatch; - float sprites[] = new float[SPRITES*6]; - float sprites2[] = new float[SPRITES*6]; - Sprite[] sprites3 = new Sprite[SPRITES*2]; + float sprites[] = new float[SPRITES * 6]; + float sprites2[] = new float[SPRITES * 6]; + Sprite[] sprites3 = new Sprite[SPRITES * 2]; float angle = 0; float ROTATION_SPEED = 20; float scale = 1; float SCALE_SPEED = -1; int renderMethod = 0; - - @Override - public void dispose( ) - { - + + @Override public void dispose () { + } - @Override - public void render( ) - { - if( renderMethod == 0 ) - renderNormal( );; - if( renderMethod == 1 ) - renderSprites( ); - } - - private void renderNormal( ) - { + @Override public void render () { + if (renderMethod == 0) renderNormal(); + ; + if (renderMethod == 1) renderSprites(); + } + + private void renderNormal () { GL10 gl = Gdx.graphics.getGL10(); - gl.glClearColor( 0.7f, 0.7f, 0.7f, 1 ); - gl.glClear( GL10.GL_COLOR_BUFFER_BIT ); - + gl.glClearColor(0.7f, 0.7f, 0.7f, 1); + gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + float begin = 0; float end = 0; float draw1 = 0; float draw2 = 0; float drawText = 0; - + angle += ROTATION_SPEED * Gdx.graphics.getDeltaTime(); scale += SCALE_SPEED * Gdx.graphics.getDeltaTime(); - if( scale < 0.5f ) - { + if (scale < 0.5f) { scale = 0.5f; SCALE_SPEED = 1; } - if( scale > 1.0f ) - { + if (scale > 1.0f) { scale = 1.0f; SCALE_SPEED = -1; } - + long start = System.nanoTime(); spriteBatch.begin(); - begin = (System.nanoTime()-start)/1000000000.0f; - + begin = (System.nanoTime() - start) / 1000000000.0f; + start = System.nanoTime(); - for( int i = 0; i < sprites.length; i+=6 ) - spriteBatch.draw( texture, sprites[i], sprites[i+1], 16, 16, 32, 32, scale, scale, angle, 0, 0, 32, 32, Color.WHITE, false, false ); - draw1 = (System.nanoTime()-start)/1000000000.0f; - + for (int i = 0; i < sprites.length; i += 6) + spriteBatch.draw(texture, sprites[i], sprites[i + 1], 16, 16, 32, 32, scale, scale, angle, 0, 0, 32, 32, Color.WHITE, + false, false); + draw1 = (System.nanoTime() - start) / 1000000000.0f; + start = System.nanoTime(); - for( int i = 0; i < sprites2.length; i+=6 ) - spriteBatch.draw( texture2, sprites2[i], sprites2[i+1], 16, 16, 32, 32, scale, scale, angle, 0, 0, 32, 32, Color.WHITE, false, false ); - draw2 = (System.nanoTime()-start)/1000000000.0f; - + for (int i = 0; i < sprites2.length; i += 6) + spriteBatch.draw(texture2, sprites2[i], sprites2[i + 1], 16, 16, 32, 32, scale, scale, angle, 0, 0, 32, 32, Color.WHITE, + false, false); + draw2 = (System.nanoTime() - start) / 1000000000.0f; + start = System.nanoTime(); - spriteBatch.drawText( font, "Question?", 100, 300, Color.RED ); - spriteBatch.drawText( font, "and another this is a test", 200, 100, Color.WHITE ); - spriteBatch.drawText( font, "all hail and another this is a test", 200, 200, Color.WHITE ); - spriteBatch.drawText( font, "normal fps: " + Gdx.graphics.getFramesPerSecond(), 10, 30, Color.RED ); - drawText = (System.nanoTime()-start)/1000000000.0f; - + spriteBatch.drawText(font, "Question?", 100, 300, Color.RED); + spriteBatch.drawText(font, "and another this is a test", 200, 100, Color.WHITE); + spriteBatch.drawText(font, "all hail and another this is a test", 200, 200, Color.WHITE); + spriteBatch.drawText(font, "normal fps: " + Gdx.graphics.getFramesPerSecond(), 10, 30, Color.RED); + drawText = (System.nanoTime() - start) / 1000000000.0f; + start = System.nanoTime(); spriteBatch.end(); - end = (System.nanoTime()-start)/1000000000.0f; - - if( System.nanoTime() - startTime > 1000000000 ) - { -// Gdx.app.log( "SpriteBatch", "fps: " + frames + ", render calls: " + spriteBatch.renderCalls + ", " + begin + ", " + draw1 + ", " + draw2 + ", " + drawText + ", " + end ); + end = (System.nanoTime() - start) / 1000000000.0f; + + if (System.nanoTime() - startTime > 1000000000) { +// Gdx.app.log( "SpriteBatch", "fps: " + frames + ", render calls: " + spriteBatch.renderCalls + ", " + begin + ", " + draw1 + +// ", " + draw2 + ", " + drawText + ", " + end ); frames = 0; startTime = System.nanoTime(); } frames++; } - - private void renderSprites( ) - { + + private void renderSprites () { GL10 gl = Gdx.graphics.getGL10(); - gl.glClearColor( 0.7f, 0.7f, 0.7f, 1 ); - gl.glClear( GL10.GL_COLOR_BUFFER_BIT ); - + gl.glClearColor(0.7f, 0.7f, 0.7f, 1); + gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + float begin = 0; float end = 0; float draw1 = 0; float draw2 = 0; float drawText = 0; - + long start = System.nanoTime(); - spriteBatch.begin(); - begin = (System.nanoTime()-start)/1000000000.0f; - + spriteBatch.begin(); + begin = (System.nanoTime() - start) / 1000000000.0f; + float angleInc = ROTATION_SPEED * Gdx.graphics.getDeltaTime(); scale += SCALE_SPEED * Gdx.graphics.getDeltaTime(); - if( scale < 0.5f ) - { + if (scale < 0.5f) { scale = 0.5f; SCALE_SPEED = 1; } - if( scale > 1.0f ) - { + if (scale > 1.0f) { scale = 1.0f; SCALE_SPEED = -1; } - - start = System.nanoTime(); - for( int i = 0; i < SPRITES; i++ ) - { - if( angleInc != 0) - sprites3[i].rotate( angleInc ); // this is aids - if( scale != 1 ) - sprites3[i].setScale( scale ); // this is aids - sprites3[i].draw( spriteBatch ); + + start = System.nanoTime(); + for (int i = 0; i < SPRITES; i++) { + if (angleInc != 0) sprites3[i].rotate(angleInc); // this is aids + if (scale != 1) sprites3[i].setScale(scale); // this is aids + sprites3[i].draw(spriteBatch); } - draw1 = (System.nanoTime()-start)/1000000000.0f; - - start = System.nanoTime(); - for( int i = SPRITES; i < SPRITES << 1; i++ ) - { - if( angleInc != 0) - sprites3[i].rotate( angleInc ); // this is aids - if( scale != 1 ) - sprites3[i].setScale( scale ); // this is aids - sprites3[i].draw( spriteBatch ); + draw1 = (System.nanoTime() - start) / 1000000000.0f; + + start = System.nanoTime(); + for (int i = SPRITES; i < SPRITES << 1; i++) { + if (angleInc != 0) sprites3[i].rotate(angleInc); // this is aids + if (scale != 1) sprites3[i].setScale(scale); // this is aids + sprites3[i].draw(spriteBatch); } - draw2 = (System.nanoTime()-start)/1000000000.0f; - + draw2 = (System.nanoTime() - start) / 1000000000.0f; + start = System.nanoTime(); - spriteBatch.drawText( font, "Question?", 100, 300, Color.RED ); - spriteBatch.drawText( font, "and another this is a test", 200, 100, Color.WHITE ); - spriteBatch.drawText( font, "all hail and another this is a test", 200, 200, Color.WHITE ); - spriteBatch.drawText( font, "Sprite fps: " + Gdx.graphics.getFramesPerSecond(), 10, 30, Color.RED ); - drawText = (System.nanoTime()-start)/1000000000.0f; - + spriteBatch.drawText(font, "Question?", 100, 300, Color.RED); + spriteBatch.drawText(font, "and another this is a test", 200, 100, Color.WHITE); + spriteBatch.drawText(font, "all hail and another this is a test", 200, 200, Color.WHITE); + spriteBatch.drawText(font, "Sprite fps: " + Gdx.graphics.getFramesPerSecond(), 10, 30, Color.RED); + drawText = (System.nanoTime() - start) / 1000000000.0f; + start = System.nanoTime(); spriteBatch.end(); - end = (System.nanoTime()-start)/1000000000.0f; - - if( System.nanoTime() - startTime > 1000000000 ) - { -// Gdx.app.log( "SpriteBatch", "fps: " + frames + ", render calls: " + spriteBatch.renderCalls + ", " + begin + ", " + draw1 + ", " + draw2 + ", " + drawText + ", " + end ); + end = (System.nanoTime() - start) / 1000000000.0f; + + if (System.nanoTime() - startTime > 1000000000) { +// Gdx.app.log( "SpriteBatch", "fps: " + frames + ", render calls: " + spriteBatch.renderCalls + ", " + begin + ", " + draw1 + +// ", " + draw2 + ", " + drawText + ", " + end ); frames = 0; startTime = System.nanoTime(); } frames++; - } - - @Override - public void surfaceChanged(int width, int height) - { - } - @Override - public void surfaceCreated( ) - { - if( spriteBatch == null ) - spriteBatch = new SpriteBatch( 1000 ); - - Pixmap pixmap = Gdx.graphics.newPixmap( Gdx.files.getFileHandle( "data/badlogicsmall.jpg", FileType.Internal ) ); - texture = Gdx.graphics.newUnmanagedTexture( 32, 32, Format.RGB565, TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); - texture.draw( pixmap, 0, 0); + @Override public void surfaceChanged (int width, int height) { + + } + + @Override public void surfaceCreated () { + if (spriteBatch == null) spriteBatch = new SpriteBatch(1000); + + Pixmap pixmap = Gdx.graphics.newPixmap(Gdx.files.getFileHandle("data/badlogicsmall.jpg", FileType.Internal)); + texture = Gdx.graphics.newUnmanagedTexture(32, 32, Format.RGB565, TextureFilter.Linear, TextureFilter.Linear, + TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); + texture.draw(pixmap, 0, 0); pixmap.dispose(); - - pixmap = Gdx.graphics.newPixmap(32, 32, Format.RGBA8888 ); - pixmap.setColor(1, 1, 0, 0.5f ); + + pixmap = Gdx.graphics.newPixmap(32, 32, Format.RGBA8888); + pixmap.setColor(1, 1, 0, 0.5f); pixmap.fill(); - texture2 = Gdx.graphics.newUnmanagedTexture( pixmap, TextureFilter.Nearest, TextureFilter.Nearest, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); + texture2 = Gdx.graphics.newUnmanagedTexture(pixmap, TextureFilter.Nearest, TextureFilter.Nearest, TextureWrap.ClampToEdge, + TextureWrap.ClampToEdge); pixmap.dispose(); - - font = Gdx.graphics.newFont( "Arial", 32, FontStyle.Plain ); - - for( int i = 0; i < sprites.length; i+=6 ) - { + + font = Gdx.graphics.newFont("Arial", 32, FontStyle.Plain); + + for (int i = 0; i < sprites.length; i += 6) { sprites[i] = (int)(Math.random() * (Gdx.graphics.getWidth() - 32)); - sprites[i+1] = (int)(Math.random() * (Gdx.graphics.getHeight() - 32)); - sprites[i+2] = 0; - sprites[i+3] = 0; - sprites[i+4] = 32; - sprites[i+5] = 32; + sprites[i + 1] = (int)(Math.random() * (Gdx.graphics.getHeight() - 32)); + sprites[i + 2] = 0; + sprites[i + 3] = 0; + sprites[i + 4] = 32; + sprites[i + 5] = 32; sprites2[i] = (int)(Math.random() * (Gdx.graphics.getWidth() - 32)); - sprites2[i+1] = (int)(Math.random() * (Gdx.graphics.getHeight() - 32)); - sprites2[i+2] = 0; - sprites2[i+3] = 0; - sprites2[i+4] = 32; - sprites2[i+5] = 32; - } - - for( int i = 0; i < SPRITES * 2; i++ ) - { + sprites2[i + 1] = (int)(Math.random() * (Gdx.graphics.getHeight() - 32)); + sprites2[i + 2] = 0; + sprites2[i + 3] = 0; + sprites2[i + 4] = 32; + sprites2[i + 5] = 32; + } + + for (int i = 0; i < SPRITES * 2; i++) { int x = (int)(Math.random() * (Gdx.graphics.getWidth() - 32)); - int y = (int)(Math.random() * (Gdx.graphics.getHeight() - 32)); - - if( i >= SPRITES ) - sprites3[i] = new Sprite( texture2, 32, 32 ); + int y = (int)(Math.random() * (Gdx.graphics.getHeight() - 32)); + + if (i >= SPRITES) + sprites3[i] = new Sprite(texture2, 32, 32); else - sprites3[i] = new Sprite( texture, 32, 32 ); + sprites3[i] = new Sprite(texture, 32, 32); sprites3[i].setPosition(x, y); sprites3[i].setOrigin(16, 16); } - - Gdx.input.addInputListener( this ); + + Gdx.input.addInputListener(this); } - @Override - public boolean keyDown(int keycode) { + @Override public boolean keyDown (int keycode) { // TODO Auto-generated method stub return false; } - @Override - public boolean keyTyped(char character) { + @Override public boolean keyTyped (char character) { // TODO Auto-generated method stub return false; } - @Override - public boolean keyUp(int keycode) { + @Override public boolean keyUp (int keycode) { // TODO Auto-generated method stub return false; } - @Override - public boolean touchDown(int x, int y, int pointer) { + @Override public boolean touchDown (int x, int y, int pointer) { // TODO Auto-generated method stub return false; } - @Override - public boolean touchDragged(int x, int y, int pointer) { + @Override public boolean touchDragged (int x, int y, int pointer) { // TODO Auto-generated method stub return false; } - @Override - public boolean touchUp(int x, int y, int pointer) - { - renderMethod = (renderMethod + 1) % 2; + @Override public boolean touchUp (int x, int y, int pointer) { + renderMethod = (renderMethod + 1) % 2; return false; } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/StageTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/StageTest.java index 8d6723651..c7827f072 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/StageTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/StageTest.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.util.ArrayList; @@ -23,10 +21,10 @@ import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputListener; import com.badlogic.gdx.RenderListener; import com.badlogic.gdx.graphics.Font; +import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.ImmediateModeRenderer; import com.badlogic.gdx.graphics.Texture; -import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; import com.badlogic.gdx.graphics.TextureRegion; @@ -37,10 +35,9 @@ import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.actors.Image; import com.badlogic.gdx.scenes.scene2d.actors.Label; -public class StageTest implements RenderListener, InputListener -{ +public class StageTest implements RenderListener, InputListener { private static final int NUM_GROUPS = 5; - private static final int NUM_SPRITES = (int)Math.sqrt(400 / NUM_GROUPS); + private static final int NUM_SPRITES = (int)Math.sqrt(400 / NUM_GROUPS); private static final float SPACING = 5; ImmediateModeRenderer renderer; Stage stage; @@ -48,217 +45,184 @@ public class StageTest implements RenderListener, InputListener Texture texture; Texture uiTexture; Font font; - + boolean rotateSprites = false; boolean scaleSprites = false; float angle; - Vector2 point = new Vector2( ); - List images = new ArrayList( ); + Vector2 point = new Vector2(); + List images = new ArrayList(); float scale = 1; float vScale = 1; - @Override - public void surfaceCreated() - { - if( stage == null ) - { - Gdx.input.addInputListener( this ); - texture = Gdx.graphics.newTexture( Gdx.files.getFileHandle( "data/badlogicsmall.jpg", FileType.Internal ), - TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); - font = Gdx.graphics.newFont( "DroidSans", 12, FontStyle.Plain ); - - stage = new Stage( 480, 320, true ); - + @Override public void surfaceCreated () { + if (stage == null) { + Gdx.input.addInputListener(this); + texture = Gdx.graphics.newTexture(Gdx.files.getFileHandle("data/badlogicsmall.jpg", FileType.Internal), + TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); + font = Gdx.graphics.newFont("DroidSans", 12, FontStyle.Plain); + + stage = new Stage(480, 320, true); + float loc = (NUM_SPRITES * (32 + SPACING) - SPACING) / 2; - for( int i = 0; i < NUM_GROUPS; i++ ) - { - Group group = new Group( "group" + i ); + for (int i = 0; i < NUM_GROUPS; i++) { + Group group = new Group("group" + i); group.x = (float)Math.random() * (stage.width() - NUM_SPRITES * (32 + SPACING)); group.y = (float)Math.random() * (stage.height() - NUM_SPRITES * (32 + SPACING)); group.originX = loc; group.originY = loc; - - fillGroup( group, texture ); - stage.addActor( group ); + + fillGroup(group, texture); + stage.addActor(group); } - - uiTexture = Gdx.graphics.newTexture( Gdx.files.getFileHandle( "data/ui.png", FileType.Internal ), - TextureFilter.Linear, TextureFilter.Linear, - TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); - ui = new Stage( 480, 320, false ); - Image blend = new Image( "blend button", new TextureRegion( uiTexture, 0, 0, 64, 32 ) ); + + uiTexture = Gdx.graphics.newTexture(Gdx.files.getFileHandle("data/ui.png", FileType.Internal), TextureFilter.Linear, + TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); + ui = new Stage(480, 320, false); + Image blend = new Image("blend button", new TextureRegion(uiTexture, 0, 0, 64, 32)); blend.y = ui.height() - 32; - Image rotate = new Image( "rotate button", new TextureRegion( uiTexture, 64, 0, 64, 32 ) ); - rotate.y = blend.y; rotate.x = 64; - Image scale = new Image( "scale button", new TextureRegion( uiTexture, 64, 32, 64, 32 ) ); - scale.y = blend.y; scale.x = 128; - - ui.addActor( blend ); - ui.addActor( rotate ); - ui.addActor( scale ); - - Label fps = new Label( "fps", font, "fps: 0" ); - fps.color.set( 0, 1, 0, 1 ); - ui.addActor( fps ); - - Thread.currentThread().setPriority( Thread.MAX_PRIORITY ); + Image rotate = new Image("rotate button", new TextureRegion(uiTexture, 64, 0, 64, 32)); + rotate.y = blend.y; + rotate.x = 64; + Image scale = new Image("scale button", new TextureRegion(uiTexture, 64, 32, 64, 32)); + scale.y = blend.y; + scale.x = 128; + + ui.addActor(blend); + ui.addActor(rotate); + ui.addActor(scale); + + Label fps = new Label("fps", font, "fps: 0"); + fps.color.set(0, 1, 0, 1); + ui.addActor(fps); + + Thread.currentThread().setPriority(Thread.MAX_PRIORITY); renderer = new ImmediateModeRenderer(); } } - - private void fillGroup( Group group, Texture texture ) - { + + private void fillGroup (Group group, Texture texture) { float advance = 32 + SPACING; - for( int y = 0; y < NUM_SPRITES * advance; y += advance) - for( int x = 0; x < NUM_SPRITES * advance; x += advance ) - { - Image img = new Image( group.name + "-sprite" + x * y, texture ); - img.x = x; - img.y = y; - img.width = 32; - img.height = 32; - group.addActor( img ); - images.add( img ); - } + for (int y = 0; y < NUM_SPRITES * advance; y += advance) + for (int x = 0; x < NUM_SPRITES * advance; x += advance) { + Image img = new Image(group.name + "-sprite" + x * y, texture); + img.x = x; + img.y = y; + img.width = 32; + img.height = 32; + group.addActor(img); + images.add(img); + } } - @Override - public void surfaceChanged(int width, int height) - { - ui.setViewport( 480, 320, false ); + @Override public void surfaceChanged (int width, int height) { + ui.setViewport(480, 320, false); } - @Override - public void render() - { + @Override public void render () { GL10 gl = Gdx.graphics.getGL10(); - gl.glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - gl.glClearColor( 0.2f, 0.2f, 0.2f, 1 ); - gl.glClear( GL10.GL_COLOR_BUFFER_BIT ); - - if( Gdx.input.isTouched() ) - { - stage.toStageCoordinates( Gdx.input.getX(), Gdx.input.getY(), point ); - Actor actor = stage.hit( point.x, point.y ); - - if( actor != null ) - if( actor instanceof Image ) - ((Image)actor).color.set( (float)Math.random(), (float)Math.random(), (float)Math.random(), 0.5f + 0.5f * (float)Math.random() ); + gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + gl.glClearColor(0.2f, 0.2f, 0.2f, 1); + gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + + if (Gdx.input.isTouched()) { + stage.toStageCoordinates(Gdx.input.getX(), Gdx.input.getY(), point); + Actor actor = stage.hit(point.x, point.y); + + if (actor != null) + if (actor instanceof Image) + ((Image)actor).color.set((float)Math.random(), (float)Math.random(), (float)Math.random(), + 0.5f + 0.5f * (float)Math.random()); } - + int len = stage.getGroups().size(); - for( int i = 0; i < len; i++ ) - if( rotateSprites ) + for (int i = 0; i < len; i++) + if (rotateSprites) stage.getGroups().get(i).rotation += Gdx.graphics.getDeltaTime(); else stage.getGroups().get(i).rotation = 0; scale += vScale * Gdx.graphics.getDeltaTime(); - if( scale > 1 ) - { + if (scale > 1) { scale = 1; vScale = -vScale; } - if( scale < 0.5f ) - { + if (scale < 0.5f) { scale = 0.5f; vScale = -vScale; } - + len = images.size(); - for( int i = 0; i < len; i++ ) - { + for (int i = 0; i < len; i++) { Image img = images.get(i); - if( rotateSprites ) + if (rotateSprites) img.rotation -= 40 * Gdx.graphics.getDeltaTime(); else img.rotation = 0; - - if( scaleSprites ) - { + + if (scaleSprites) { img.scaleX = scale; img.scaleY = scale; - } - else - { + } else { img.scaleX = 1; img.scaleY = 1; } } - - stage.render( ); - - Gdx.graphics.getGL10().glPointSize( 4 ); - renderer.begin( GL10.GL_POINTS ); + + stage.render(); + + Gdx.graphics.getGL10().glPointSize(4); + renderer.begin(GL10.GL_POINTS); len = stage.getRoot().getGroups().size(); - for( int i = 0; i < len; i++ ) - { - renderer.color( 1, 0, 0, 1 ); + for (int i = 0; i < len; i++) { + renderer.color(1, 0, 0, 1); Group group = stage.getRoot().getGroups().get(i); - renderer.vertex( group.x + group.originX, group.y + group.originY, 0 ); + renderer.vertex(group.x + group.originX, group.y + group.originY, 0); } renderer.end(); - Gdx.graphics.getGL10().glPointSize( 4 ); + Gdx.graphics.getGL10().glPointSize(4); - ((Label)ui.findActor( "fps" )).text = "fps: " + Gdx.graphics.getFramesPerSecond() + ", actors " + images.size() + ", groups " + stage.getGroups().size(); - ui.render( ); + ((Label)ui.findActor("fps")).text = "fps: " + Gdx.graphics.getFramesPerSecond() + ", actors " + images.size() + ", groups " + + stage.getGroups().size(); + ui.render(); } - @Override - public boolean touchDown(int x, int y, int pointer) - { - boolean touched = ui.touchDown( x, y, pointer ); - if( touched ) - { + @Override public boolean touchDown (int x, int y, int pointer) { + boolean touched = ui.touchDown(x, y, pointer); + if (touched) { Actor hitActor = ui.getLastTouchedChild(); - if( hitActor == null ) - return touched; - if( hitActor.name.startsWith( "blend" ) ) - if( stage.getSpriteBatch().isBlendingEnabled() ) - stage.getSpriteBatch().disableBlending(); - else - stage.getSpriteBatch().enableBlending(); - if( hitActor.name.startsWith( "rotate" ) ) - rotateSprites = !rotateSprites; - if( hitActor.name.startsWith( "scale" ) ) - scaleSprites = !scaleSprites; + if (hitActor == null) return touched; + if (hitActor.name.startsWith("blend")) if (stage.getSpriteBatch().isBlendingEnabled()) + stage.getSpriteBatch().disableBlending(); + else + stage.getSpriteBatch().enableBlending(); + if (hitActor.name.startsWith("rotate")) rotateSprites = !rotateSprites; + if (hitActor.name.startsWith("scale")) scaleSprites = !scaleSprites; } return touched; } - @Override - public boolean touchUp(int x, int y, int pointer) - { - return false; + @Override public boolean touchUp (int x, int y, int pointer) { + return false; } - @Override - public boolean touchDragged(int x, int y, int pointer) - { - return false; + @Override public boolean touchDragged (int x, int y, int pointer) { + return false; } - - @Override - public void dispose() - { - + + @Override public void dispose () { + } - @Override - public boolean keyDown(int keycode) - { + @Override public boolean keyDown (int keycode) { return false; } - @Override - public boolean keyUp(int keycode) { + @Override public boolean keyUp (int keycode) { // TODO Auto-generated method stub return false; } - @Override - public boolean keyTyped(char character) - { + @Override public boolean keyTyped (char character) { return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/TerrainTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/TerrainTest.java index d8e19cba9..f814e9a6f 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/TerrainTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/TerrainTest.java @@ -1,11 +1,12 @@ + package com.badlogic.gdx.tests; import java.util.Random; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; -import com.badlogic.gdx.RenderListener; import com.badlogic.gdx.Input.Keys; +import com.badlogic.gdx.RenderListener; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.ImmediateModeRenderer; @@ -17,192 +18,160 @@ import com.badlogic.gdx.math.Intersector; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.collision.Ray; -public class TerrainTest implements RenderListener -{ +public class TerrainTest implements RenderListener { ImmediateModeRenderer renderer; TerrainChunk chunk; Mesh mesh; PerspectiveCamera camera; - Vector3 intersection = new Vector3( ); + Vector3 intersection = new Vector3(); boolean intersected = false; long lastTime = System.nanoTime(); - - @Override - public void surfaceCreated( ) - { - if( chunk == null ) - { - renderer = new ImmediateModeRenderer( ); - - chunk = new TerrainChunk( 32, 32, 4 ); - + + @Override public void surfaceCreated () { + if (chunk == null) { + renderer = new ImmediateModeRenderer(); + + chunk = new TerrainChunk(32, 32, 4); + Random rand = new Random(); int len = chunk.vertices.length; - for( int i = 3; i < len; i+=4 ) - chunk.vertices[i] = Color.toFloatBits( rand.nextInt(255), rand.nextInt(255), rand.nextInt(255), 255 ); - - mesh = new Mesh( true, false, chunk.vertices.length / 3, chunk.indices.length, - new VertexAttribute( VertexAttributes.Usage.Position, 3, "a_position" ), - new VertexAttribute( VertexAttributes.Usage.ColorPacked, 4, "a_color" ) ); - - mesh.setVertices( chunk.vertices ); - mesh.setIndices( chunk.indices ); - + for (int i = 3; i < len; i += 4) + chunk.vertices[i] = Color.toFloatBits(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255), 255); + + mesh = new Mesh(true, false, chunk.vertices.length / 3, chunk.indices.length, new VertexAttribute( + VertexAttributes.Usage.Position, 3, "a_position"), new VertexAttribute(VertexAttributes.Usage.ColorPacked, 4, + "a_color")); + + mesh.setVertices(chunk.vertices); + mesh.setIndices(chunk.indices); + camera = new PerspectiveCamera(); - camera.getPosition().set( 0, 5, 5 ); - camera.getDirection().set( 0, 0, 0 ).sub( camera.getPosition() ).nor(); - camera.setViewport( Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - camera.setNear( 0.5f ); - camera.setFar( 300 ); - camera.setFov( 67 ); + camera.getPosition().set(0, 5, 5); + camera.getDirection().set(0, 0, 0).sub(camera.getPosition()).nor(); + camera.setViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + camera.setNear(0.5f); + camera.setFar(300); + camera.setFov(67); } } - @Override - public void surfaceChanged( int width, int height) - { - + @Override public void surfaceChanged (int width, int height) { + } - @Override - public void render( ) - { + @Override public void render () { GL10 gl = Gdx.graphics.getGL10(); - gl.glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - gl.glEnable( GL10.GL_DEPTH_TEST ); - gl.glClear( GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT ); - - camera.setMatrices( ); - gl.glColor4f( 1, 1, 1, 1 ); - mesh.render( GL10.GL_TRIANGLES ); - - if( intersected ) - { - gl.glPointSize( 10 ); - renderer.begin( GL10.GL_POINTS ); - renderer.color( 1, 0, 0, 1 ); - renderer.vertex( intersection.x, intersection.y, intersection.z ); + gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + gl.glEnable(GL10.GL_DEPTH_TEST); + gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); + + camera.setMatrices(); + gl.glColor4f(1, 1, 1, 1); + mesh.render(GL10.GL_TRIANGLES); + + if (intersected) { + gl.glPointSize(10); + renderer.begin(GL10.GL_POINTS); + renderer.color(1, 0, 0, 1); + renderer.vertex(intersection.x, intersection.y, intersection.z); renderer.end(); } - - - handleInput( Gdx.input, Gdx.graphics.getDeltaTime() ); - - if( System.nanoTime() - lastTime > 1000000000 ) - { - Gdx.app.log( "TerrainTest", "fps: " + Gdx.graphics.getFramesPerSecond() ); + + handleInput(Gdx.input, Gdx.graphics.getDeltaTime()); + + if (System.nanoTime() - lastTime > 1000000000) { + Gdx.app.log("TerrainTest", "fps: " + Gdx.graphics.getFramesPerSecond()); lastTime = System.nanoTime(); } } - - private void handleInput( Input input, float delta ) - { - if( input.isTouched() ) - { - Ray ray = camera.getPickRay( input.getX(), input.getY() ); - if( Intersector.intersectRayTriangles(ray, chunk.vertices, chunk.indices, 4, intersection ) ) - intersected = true; - } - else - { + + private void handleInput (Input input, float delta) { + if (input.isTouched()) { + Ray ray = camera.getPickRay(input.getX(), input.getY()); + if (Intersector.intersectRayTriangles(ray, chunk.vertices, chunk.indices, 4, intersection)) intersected = true; + } else { intersected = false; } - - if( input.isKeyPressed( Keys.KEYCODE_W ) ) - camera.getPosition().z -= delta; - if( input.isKeyPressed( Keys.KEYCODE_S ) ) - camera.getPosition().z += delta; - if( input.isKeyPressed( Keys.KEYCODE_A ) ) - camera.getPosition().x -= delta; - if( input.isKeyPressed( Keys.KEYCODE_D ) ) - camera.getPosition().x += delta; - if( input.isKeyPressed( Keys.KEYCODE_Q ) ) - camera.getPosition().y += delta; - if( input.isKeyPressed( Keys.KEYCODE_E ) ) - camera.getPosition().y -= delta; + + if (input.isKeyPressed(Keys.KEYCODE_W)) camera.getPosition().z -= delta; + if (input.isKeyPressed(Keys.KEYCODE_S)) camera.getPosition().z += delta; + if (input.isKeyPressed(Keys.KEYCODE_A)) camera.getPosition().x -= delta; + if (input.isKeyPressed(Keys.KEYCODE_D)) camera.getPosition().x += delta; + if (input.isKeyPressed(Keys.KEYCODE_Q)) camera.getPosition().y += delta; + if (input.isKeyPressed(Keys.KEYCODE_E)) camera.getPosition().y -= delta; } - @Override - public void dispose( ) - { - + @Override public void dispose () { + } - - final static class TerrainChunk - { + + final static class TerrainChunk { public final byte[] heightMap; public final short width; public final short height; public final float[] vertices; public final short[] indices; public final int vertexSize; - - public TerrainChunk( int width, int height, int vertexSize ) - { - if( (width + 1) * (height + 1) > Short.MAX_VALUE ) - throw new IllegalArgumentException( "Chunk size too big, (width + 1)*(height+1) must be <= 32767" ); - + + public TerrainChunk (int width, int height, int vertexSize) { + if ((width + 1) * (height + 1) > Short.MAX_VALUE) + throw new IllegalArgumentException("Chunk size too big, (width + 1)*(height+1) must be <= 32767"); + this.heightMap = new byte[(width + 1) * (height + 1)]; this.width = (short)width; this.height = (short)height; this.vertices = new float[heightMap.length * vertexSize]; this.indices = new short[width * height * 6]; this.vertexSize = vertexSize; - - buildIndices( ); - buildVertices( ); + + buildIndices(); + buildVertices(); } - - public void buildVertices( ) - { + + public void buildVertices () { int heightPitch = height + 1; int widthPitch = width + 1; - + int idx = 0; int hIdx = 0; int inc = vertexSize - 3; - - for( int z = 0; z < heightPitch; z++ ) - { - for( int x = 0; x < widthPitch; x++ ) - { + + for (int z = 0; z < heightPitch; z++) { + for (int x = 0; x < widthPitch; x++) { vertices[idx++] = x; vertices[idx++] = heightMap[hIdx++]; vertices[idx++] = z; - idx+=inc; + idx += inc; } } } - - private void buildIndices( ) - { + + private void buildIndices () { int idx = 0; short pitch = (short)(width + 1); short i1 = 0; short i2 = 1; short i3 = (short)(1 + pitch); short i4 = pitch; - + short row = 0; - - for( int z = 0; z < height; z++ ) - { - for( int x = 0; x < width; x++ ) - { + + for (int z = 0; z < height; z++) { + for (int x = 0; x < width; x++) { indices[idx++] = i1; indices[idx++] = i2; indices[idx++] = i3; - + indices[idx++] = i3; indices[idx++] = i4; indices[idx++] = i1; - + i1++; i2++; i3++; i4++; } - + row += pitch; i1 = row; i2 = (short)(row + 1); diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/TextTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/TextTest.java index 7ec667acb..c059e2630 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/TextTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/TextTest.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -23,44 +21,34 @@ import com.badlogic.gdx.graphics.Font.FontStyle; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.SpriteBatch; -public class TextTest implements RenderListener -{ +public class TextTest implements RenderListener { SpriteBatch spriteBatch; - Font font; - + Font font; - @Override - public void surfaceCreated( ) - { - if( font == null ) - { - spriteBatch = new SpriteBatch( ); - font = Gdx.graphics.newFont( "Arial", 32, FontStyle.Italic ); + @Override public void surfaceCreated () { + if (font == null) { + spriteBatch = new SpriteBatch(); + font = Gdx.graphics.newFont("Arial", 32, FontStyle.Italic); } } - - @Override - public void render( ) - { - Gdx.graphics.getGL10().glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - Gdx.graphics.getGL10().glClearColor( 0.7f, 0.7f, 0.7f, 1 ); - Gdx.graphics.getGL10().glClear(GL10.GL_COLOR_BUFFER_BIT ); - + + @Override public void render () { + Gdx.graphics.getGL10().glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + Gdx.graphics.getGL10().glClearColor(0.7f, 0.7f, 0.7f, 1); + Gdx.graphics.getGL10().glClear(GL10.GL_COLOR_BUFFER_BIT); + spriteBatch.begin(); - spriteBatch.draw( font.getTexture(), 0, 100, font.getTexture().getWidth(), font.getTexture().getHeight(), 0, 0, font.getTexture().getWidth(), font.getTexture().getHeight(), Color.WHITE, false, true ); - spriteBatch.drawText( font, "this is a test", 100, 100, Color.RED ); + spriteBatch.draw(font.getTexture(), 0, 100, font.getTexture().getWidth(), font.getTexture().getHeight(), 0, 0, font + .getTexture().getWidth(), font.getTexture().getHeight(), Color.WHITE, false, true); + spriteBatch.drawText(font, "this is a test", 100, 100, Color.RED); spriteBatch.end(); } - @Override - public void dispose( ) - { - + @Override public void dispose () { + } - - @Override - public void surfaceChanged( int width, int height) - { - + + @Override public void surfaceChanged (int width, int height) { + } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/TextureRenderTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/TextureRenderTest.java index c66c61e35..1ab44e35b 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/TextureRenderTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/TextureRenderTest.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.util.ArrayList; @@ -31,163 +29,148 @@ import com.badlogic.gdx.graphics.VertexAttributes; public class TextureRenderTest implements RenderListener { - private OrthographicCamera camera; - private Mesh mesh; - private Texture texture; - - private ArrayList rects = new ArrayList(); - Color color = new Color(Color.GREEN); - - - @Override - public void surfaceCreated( ) { - camera = new OrthographicCamera( ); - camera.setViewport(480, 320); - camera.getPosition().set(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0); - - Pixmap pixmap = Gdx.graphics.newPixmap(Gdx.files.getFileHandle("data/badlogic.jpg", Files.FileType.Internal)); - texture = Gdx.graphics.newUnmanagedTexture(pixmap, Texture.TextureFilter.Linear, Texture.TextureFilter.Linear, Texture.TextureWrap.ClampToEdge, Texture.TextureWrap.ClampToEdge ); - - - float invTexWidth = 1.0f / texture.getWidth(); - float invTexHeight = 1.0f / texture.getHeight(); - - rects = createRects(); - - if( this.mesh == null ) - this.mesh = new Mesh( false, false, 6 * 4 * rects.size(), 0, - new VertexAttribute(VertexAttributes.Usage.Position, 2, "a_position"), - new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoord")); - - - final float[] vertices = new float[rects.size() * 6 * 4]; - int idx = 0; + private OrthographicCamera camera; + private Mesh mesh; + private Texture texture; - for (int i = 0; i < rects.size(); i++) { - SimpleRect rect = rects.get(i); + private ArrayList rects = new ArrayList(); + Color color = new Color(Color.GREEN); - float u = rect.x * invTexWidth; - float v = rect.y * invTexHeight; - float u2 = (rect.x + rect.width) * invTexWidth; - float v2 = (rect.y + rect.height) * invTexHeight; - float fx = rect.x; - float fy = rect.y; - float fx2 = (rect.x + rect.width); - float fy2 = (rect.y -rect.height); + @Override public void surfaceCreated () { + camera = new OrthographicCamera(); + camera.setViewport(480, 320); + camera.getPosition().set(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0); - vertices[idx++] = fx; - vertices[idx++] = fy; - vertices[idx++] = u; - vertices[idx++] = v; + Pixmap pixmap = Gdx.graphics.newPixmap(Gdx.files.getFileHandle("data/badlogic.jpg", Files.FileType.Internal)); + texture = Gdx.graphics.newUnmanagedTexture(pixmap, Texture.TextureFilter.Linear, Texture.TextureFilter.Linear, + Texture.TextureWrap.ClampToEdge, Texture.TextureWrap.ClampToEdge); - vertices[idx++] = fx; - vertices[idx++] = fy2; - vertices[idx++] = u; - vertices[idx++] = v2; + float invTexWidth = 1.0f / texture.getWidth(); + float invTexHeight = 1.0f / texture.getHeight(); - vertices[idx++] = fx2; - vertices[idx++] = fy2; - vertices[idx++] = u2; - vertices[idx++] = v2; + rects = createRects(); - vertices[idx++] = fx2; - vertices[idx++] = fy2; - vertices[idx++] = u2; - vertices[idx++] = v2; + if (this.mesh == null) + this.mesh = new Mesh(false, false, 6 * 4 * rects.size(), 0, new VertexAttribute(VertexAttributes.Usage.Position, 2, + "a_position"), new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoord")); - vertices[idx++] = fx2; - vertices[idx++] = fy; - vertices[idx++] = u2; - vertices[idx++] = v; + final float[] vertices = new float[rects.size() * 6 * 4]; + int idx = 0; - vertices[idx++] = fx; - vertices[idx++] = fy; - vertices[idx++] = u; - vertices[idx++] = v; + for (int i = 0; i < rects.size(); i++) { + SimpleRect rect = rects.get(i); + float u = rect.x * invTexWidth; + float v = rect.y * invTexHeight; + float u2 = (rect.x + rect.width) * invTexWidth; + float v2 = (rect.y + rect.height) * invTexHeight; + float fx = rect.x; + float fy = rect.y; + float fx2 = (rect.x + rect.width); + float fy2 = (rect.y - rect.height); - } - this.mesh.setVertices(vertices); + vertices[idx++] = fx; + vertices[idx++] = fy; + vertices[idx++] = u; + vertices[idx++] = v; - } + vertices[idx++] = fx; + vertices[idx++] = fy2; + vertices[idx++] = u; + vertices[idx++] = v2; - @Override - public void surfaceChanged(int width, int height) { + vertices[idx++] = fx2; + vertices[idx++] = fy2; + vertices[idx++] = u2; + vertices[idx++] = v2; - } + vertices[idx++] = fx2; + vertices[idx++] = fy2; + vertices[idx++] = u2; + vertices[idx++] = v2; - @Override - public void render( ) { + vertices[idx++] = fx2; + vertices[idx++] = fy; + vertices[idx++] = u2; + vertices[idx++] = v; - GL10 gl = Gdx.graphics.getGL10(); - gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); - gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - gl.glEnable(GL10.GL_TEXTURE_2D); + vertices[idx++] = fx; + vertices[idx++] = fy; + vertices[idx++] = u; + vertices[idx++] = v; - camera.update(); + } + this.mesh.setVertices(vertices); + } + @Override public void surfaceChanged (int width, int height) { - gl.glMatrixMode(GL10.GL_PROJECTION); - gl.glLoadMatrixf(camera.getCombinedMatrix().val, 0); - gl.glMatrixMode(GL10.GL_MODELVIEW); - gl.glLoadIdentity(); + } - gl.glEnable(GL10.GL_BLEND); - gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); + @Override public void render () { + GL10 gl = Gdx.graphics.getGL10(); + gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + gl.glEnable(GL10.GL_TEXTURE_2D); - gl.glColor4f(color.r, color.g, color.b, color.a); - - gl.glColor4f(Color.WHITE.r, Color.WHITE.g, Color.WHITE.b, 0.5F); + camera.update(); - texture.bind(); + gl.glMatrixMode(GL10.GL_PROJECTION); + gl.glLoadMatrixf(camera.getCombinedMatrix().val, 0); + gl.glMatrixMode(GL10.GL_MODELVIEW); + gl.glLoadIdentity(); + gl.glEnable(GL10.GL_BLEND); + gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); - for (int i = 0; i < rects.size(); i++) { - SimpleRect rect = rects.get(i); - gl.glPushMatrix(); + gl.glColor4f(color.r, color.g, color.b, color.a); -// float x = (rect.index + 1) * 60F; - gl.glTranslatef(100, 100F, 0F); + gl.glColor4f(Color.WHITE.r, Color.WHITE.g, Color.WHITE.b, 0.5F); - mesh.render(GL10.GL_TRIANGLES, rect.index * 24, 24); + texture.bind(); - gl.glPopMatrix(); - } + for (int i = 0; i < rects.size(); i++) { + SimpleRect rect = rects.get(i); + gl.glPushMatrix(); +// float x = (rect.index + 1) * 60F; + gl.glTranslatef(100, 100F, 0F); - } + mesh.render(GL10.GL_TRIANGLES, rect.index * 24, 24); - @Override - public void dispose( ) { + gl.glPopMatrix(); + } - } + } - private ArrayList createRects() { - ArrayList l = new ArrayList(); - l.add(new SimpleRect(0, 10, 0, 50, 50)); - l.add(new SimpleRect(1, 60, 0, 50, 50)); - l.add(new SimpleRect(2, 110, 0, 50, 50)); - return l; - } + @Override public void dispose () { + } - private static class SimpleRect { - public int index; - public float x; - public float y; - public float height; - public float width; + private ArrayList createRects () { + ArrayList l = new ArrayList(); + l.add(new SimpleRect(0, 10, 0, 50, 50)); + l.add(new SimpleRect(1, 60, 0, 50, 50)); + l.add(new SimpleRect(2, 110, 0, 50, 50)); + return l; + } - private SimpleRect(int index, float x, float y, float width, float height) { - this.index = index; - this.x = x; - this.y = y; - this.height = height; - this.width = width; - } - } + private static class SimpleRect { + public int index; + public float x; + public float y; + public float height; + public float width; + private SimpleRect (int index, float x, float y, float width, float height) { + this.index = index; + this.x = x; + this.y = y; + this.height = height; + this.width = width; + } + } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/UITest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/UITest.java index e18a24b9b..fcc9c1d87 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/UITest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/UITest.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Files.FileType; @@ -30,161 +31,129 @@ import com.badlogic.gdx.scenes.scene2d.actors.Image; import com.badlogic.gdx.scenes.scene2d.actors.LinearGroup; import com.badlogic.gdx.scenes.scene2d.actors.LinearGroup.LinearGroupLayout; -public class UITest implements RenderListener, InputListener -{ +public class UITest implements RenderListener, InputListener { Texture uiTexture; Texture badlogic; TextureAtlas atlas; Stage ui; - - @Override - public void surfaceCreated() - { - if( uiTexture == null ) - { - Gdx.input.addInputListener( this ); - - uiTexture = Gdx.graphics.newTexture( Gdx.files.getFileHandle( "data/ui.png", FileType.Internal ), - TextureFilter.Linear, TextureFilter.Linear, - TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); - - badlogic = Gdx.graphics.newTexture( Gdx.files.getFileHandle( "data/badlogic.jpg", FileType.Internal ), - TextureFilter.MipMap, TextureFilter.Linear, - TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); - - ui = new Stage( 480, 320, false ); - atlas = new TextureAtlas( uiTexture ); - atlas.addRegion( "blend", 0, 0, 64, 32 ); - atlas.addRegion( "blendDown", -1, -1, 64, 32 ); - atlas.addRegion( "rotate", 64, 0, 64, 32 ); - atlas.addRegion( "rotateDown", 63, -1, 64, 32 ); - atlas.addRegion( "scale", 64, 32, 64, 32 ); - atlas.addRegion( "scaleDown", 63, 31, 64, 32 ); - atlas.addRegion( "button", 0, 64, 64, 32 ); - atlas.addRegion( "buttonDown", -1, 63, 64, 32 ); - - Image img1 = new Image( "image1", new TextureRegion( badlogic, 0, 0, 256, 256 ) ); - img1.width = img1.height = 64; img1.originX = img1.originY = 32; - img1.action( Sequence.$( - FadeOut.$(1), - FadeIn.$(1), - Delay.$( MoveTo.$( 100, 100, 1 ), 2 ), - ScaleTo.$( 0.5f, 0.5f, 1 ), - FadeOut.$( 0.5f ), - Delay.$( - Parallel.$( - RotateTo.$( 360, 1 ), - FadeIn.$( 1 ), - ScaleTo.$( 1, 1, 1 )) - , 1 ) - ) - ); - ui.addActor( img1 ); - - Image img2 = new Image( "image2", new TextureRegion( badlogic, 0, 0, 256, 256 ) ); - img2.width = img2.height = 64; img2.originX = img2.originY = 32; - img2.action( Repeat.$( Sequence.$( - MoveBy.$( 50, 0, 1 ), - MoveBy.$( 0, 50, 1 ), - MoveBy.$(-50, 0, 1 ), - MoveBy.$( 0, -50, 1 ) - ), 3 ) ); - ui.addActor( img2 ); - - Button button = new Button( "button", atlas.getRegion( "button" ), atlas.getRegion( "buttonDown" ) ); - button.action( Forever.$(RotateBy.$( 360, 4 )) ); - ui.addActor( button ); - - LinearGroup linear = new LinearGroup( "linear", 64, 32 * 3, LinearGroupLayout.Vertical ); - linear.x = 200; linear.y = 150; linear.scaleX = linear.scaleY = 0; - linear.addActor( new Button( "blend", atlas.getRegion( "blend" ), atlas.getRegion( "blendDown" ) ) ); - linear.addActor( new Button( "scale", atlas.getRegion( "scale" ), atlas.getRegion( "scaleDown" ) ) ); - linear.addActor( new Button( "rotate", atlas.getRegion( "rotate" ), atlas.getRegion( "rotateDown" ) ) ); - linear.action( Parallel.$( ScaleTo.$( 1, 1, 2 ), RotateTo.$( 720, 2 ) ) ); - ui.addActor( linear ); - - LinearGroup linearh = new LinearGroup( "linearh", 64 * 3, 32, LinearGroupLayout.Horizontal ); - linearh.x = 500; linearh.y = 10; - linearh.addActor( new Button( "blendh", atlas.getRegion( "blend" ), atlas.getRegion( "blendDown" ) ) ); - linearh.addActor( new Button( "scaleh", atlas.getRegion( "scale" ), atlas.getRegion( "scaleDown" ) ) ); - linearh.addActor( new Button( "rotateh", atlas.getRegion( "rotate" ), atlas.getRegion( "rotateDown" ) ) ); - linearh.action( MoveTo.$(100, 10, 1.5f) ); - ui.addActor( linearh ); - -// Group.enableDebugging( "data/debug.png" ); + + @Override public void surfaceCreated () { + if (uiTexture == null) { + Gdx.input.addInputListener(this); + + uiTexture = Gdx.graphics.newTexture(Gdx.files.getFileHandle("data/ui.png", FileType.Internal), TextureFilter.Linear, + TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); + + badlogic = Gdx.graphics.newTexture(Gdx.files.getFileHandle("data/badlogic.jpg", FileType.Internal), + TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); + + ui = new Stage(480, 320, false); + atlas = new TextureAtlas(uiTexture); + atlas.addRegion("blend", 0, 0, 64, 32); + atlas.addRegion("blendDown", -1, -1, 64, 32); + atlas.addRegion("rotate", 64, 0, 64, 32); + atlas.addRegion("rotateDown", 63, -1, 64, 32); + atlas.addRegion("scale", 64, 32, 64, 32); + atlas.addRegion("scaleDown", 63, 31, 64, 32); + atlas.addRegion("button", 0, 64, 64, 32); + atlas.addRegion("buttonDown", -1, 63, 64, 32); + + Image img1 = new Image("image1", new TextureRegion(badlogic, 0, 0, 256, 256)); + img1.width = img1.height = 64; + img1.originX = img1.originY = 32; + img1.action(Sequence.$(FadeOut.$(1), FadeIn.$(1), Delay.$(MoveTo.$(100, 100, 1), 2), ScaleTo.$(0.5f, 0.5f, 1), + FadeOut.$(0.5f), Delay.$(Parallel.$(RotateTo.$(360, 1), FadeIn.$(1), ScaleTo.$(1, 1, 1)), 1))); + ui.addActor(img1); + + Image img2 = new Image("image2", new TextureRegion(badlogic, 0, 0, 256, 256)); + img2.width = img2.height = 64; + img2.originX = img2.originY = 32; + img2.action(Repeat.$(Sequence.$(MoveBy.$(50, 0, 1), MoveBy.$(0, 50, 1), MoveBy.$(-50, 0, 1), MoveBy.$(0, -50, 1)), 3)); + ui.addActor(img2); + + Button button = new Button("button", atlas.getRegion("button"), atlas.getRegion("buttonDown")); + button.action(Forever.$(RotateBy.$(360, 4))); + ui.addActor(button); + + LinearGroup linear = new LinearGroup("linear", 64, 32 * 3, LinearGroupLayout.Vertical); + linear.x = 200; + linear.y = 150; + linear.scaleX = linear.scaleY = 0; + linear.addActor(new Button("blend", atlas.getRegion("blend"), atlas.getRegion("blendDown"))); + linear.addActor(new Button("scale", atlas.getRegion("scale"), atlas.getRegion("scaleDown"))); + linear.addActor(new Button("rotate", atlas.getRegion("rotate"), atlas.getRegion("rotateDown"))); + linear.action(Parallel.$(ScaleTo.$(1, 1, 2), RotateTo.$(720, 2))); + ui.addActor(linear); + + LinearGroup linearh = new LinearGroup("linearh", 64 * 3, 32, LinearGroupLayout.Horizontal); + linearh.x = 500; + linearh.y = 10; + linearh.addActor(new Button("blendh", atlas.getRegion("blend"), atlas.getRegion("blendDown"))); + linearh.addActor(new Button("scaleh", atlas.getRegion("scale"), atlas.getRegion("scaleDown"))); + linearh.addActor(new Button("rotateh", atlas.getRegion("rotate"), atlas.getRegion("rotateDown"))); + linearh.action(MoveTo.$(100, 10, 1.5f)); + ui.addActor(linearh); + +// Group.enableDebugging( "data/debug.png" ); } } - @Override - public void surfaceChanged(int width, int height) - { - + @Override public void surfaceChanged (int width, int height) { + } - @Override - public void render() - { + @Override public void render () { GL10 gl = Gdx.graphics.getGL10(); - gl.glClear( GL10.GL_COLOR_BUFFER_BIT ); - ui.act( Gdx.graphics.getDeltaTime() ); + gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + ui.act(Gdx.graphics.getDeltaTime()); ui.render(); } - @Override - public void dispose() - { - + @Override public void dispose () { + } - @Override - public boolean keyDown(int keycode) { + @Override public boolean keyDown (int keycode) { // TODO Auto-generated method stub return false; } - @Override - public boolean keyUp(int keycode) { + @Override public boolean keyUp (int keycode) { // TODO Auto-generated method stub return false; } - @Override - public boolean keyTyped(char character) { + @Override public boolean keyTyped (char character) { // TODO Auto-generated method stub return false; } - @Override - public boolean touchDown(int x, int y, int pointer) { - ui.touchDown( x, y, pointer ); + @Override public boolean touchDown (int x, int y, int pointer) { + ui.touchDown(x, y, pointer); return false; } - Vector2 point = new Vector2( ); - @Override - public boolean touchUp(int x, int y, int pointer) { - if( !ui.touchUp( x, y, pointer ) ) - { - Actor actor = ui.findActor( "image1" ); - if( actor != null ) - { - ui.toStageCoordinates( x, y, point ); + Vector2 point = new Vector2(); + + @Override public boolean touchUp (int x, int y, int pointer) { + if (!ui.touchUp(x, y, pointer)) { + Actor actor = ui.findActor("image1"); + if (actor != null) { + ui.toStageCoordinates(x, y, point); actor.clearActions(); - actor.action( MoveTo.$( point.x, point.y, 2 ) ); - actor.action( RotateBy.$( 90, 2 ) ); - if( actor.scaleX == 1.0f ) - actor.action( ScaleTo.$( 0.5f, 0.5f, 2 ) ); + actor.action(MoveTo.$(point.x, point.y, 2)); + actor.action(RotateBy.$(90, 2)); + if (actor.scaleX == 1.0f) + actor.action(ScaleTo.$(0.5f, 0.5f, 2)); else - actor.action( ScaleTo.$( 1f, 1f, 2 ) ); + actor.action(ScaleTo.$(1f, 1f, 2)); } } return false; } - @Override - public boolean touchDragged(int x, int y, int pointer) - { - ui.touchDragged( x, y, pointer ); + @Override public boolean touchDragged (int x, int y, int pointer) { + ui.touchDragged(x, y, pointer); return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/VertexArrayTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/VertexArrayTest.java index 6a250db0c..a7de90e8a 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/VertexArrayTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/VertexArrayTest.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.nio.ByteBuffer; @@ -24,67 +22,54 @@ import com.badlogic.gdx.Gdx; import com.badlogic.gdx.RenderListener; import com.badlogic.gdx.graphics.GL10; -public class VertexArrayTest implements RenderListener -{ +public class VertexArrayTest implements RenderListener { FloatBuffer vertices; ShortBuffer indices; - final int BYTES_PER_VERTEX = (3+4)*4; - - @Override - public void dispose( ) - { - + final int BYTES_PER_VERTEX = (3 + 4) * 4; + + @Override public void dispose () { + } - @Override - public void render( ) - { + @Override public void render () { GL10 gl = Gdx.graphics.getGL10(); - gl.glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - gl.glClearColor( 0.7f, 0.7f, 0.7f, 1 ); - gl.glClear( GL10.GL_COLOR_BUFFER_BIT ); - - gl.glEnableClientState(GL10.GL_COLOR_ARRAY); + gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + gl.glClearColor(0.7f, 0.7f, 0.7f, 1); + gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + + gl.glEnableClientState(GL10.GL_COLOR_ARRAY); vertices.position(3); - gl.glColorPointer(4, GL10.GL_FLOAT, BYTES_PER_VERTEX, vertices ); - + gl.glColorPointer(4, GL10.GL_FLOAT, BYTES_PER_VERTEX, vertices); + gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); vertices.position(0); - gl.glVertexPointer( 3, GL10.GL_FLOAT, BYTES_PER_VERTEX, vertices ); - - gl.glDrawElements( GL10.GL_TRIANGLES, 3, GL10.GL_UNSIGNED_SHORT, indices); + gl.glVertexPointer(3, GL10.GL_FLOAT, BYTES_PER_VERTEX, vertices); + + gl.glDrawElements(GL10.GL_TRIANGLES, 3, GL10.GL_UNSIGNED_SHORT, indices); } - @Override - public void surfaceCreated( ) - { - ByteBuffer buffer = ByteBuffer.allocateDirect( BYTES_PER_VERTEX * 3 ); + @Override public void surfaceCreated () { + ByteBuffer buffer = ByteBuffer.allocateDirect(BYTES_PER_VERTEX * 3); buffer.order(ByteOrder.nativeOrder()); - vertices = buffer.asFloatBuffer(); - - float[] verts = { - -0.5f, -0.5f, 0, - 1, 0, 0, 0, - - 0.5f, -0.5f, 0, - 0, 1, 0, 0, - - 0, 0.5f, 0, - 0, 0, 1, 0 - }; + vertices = buffer.asFloatBuffer(); + + float[] verts = {-0.5f, -0.5f, 0, 1, 0, 0, 0, + + 0.5f, -0.5f, 0, 0, 1, 0, 0, + + 0, 0.5f, 0, 0, 0, 1, 0}; vertices.put(verts); vertices.flip(); - - buffer = ByteBuffer.allocateDirect( 3 * 2 ); + + buffer = ByteBuffer.allocateDirect(3 * 2); buffer.order(ByteOrder.nativeOrder()); indices = buffer.asShortBuffer(); - indices.put( new short[ ] { 0, 1, 2 } ); + indices.put(new short[] {0, 1, 2}); indices.flip(); } - @Override - public void surfaceChanged( int width, int height) { + @Override public void surfaceChanged (int width, int height) { // TODO Auto-generated method stub - + } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/VertexBufferObjectTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/VertexBufferObjectTest.java index de8d0ca16..0eb2dfada 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/VertexBufferObjectTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/VertexBufferObjectTest.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.nio.FloatBuffer; @@ -23,71 +21,58 @@ import com.badlogic.gdx.RenderListener; import com.badlogic.gdx.graphics.GL11; import com.badlogic.gdx.utils.BufferUtils; -public class VertexBufferObjectTest implements RenderListener -{ +public class VertexBufferObjectTest implements RenderListener { int vboHandle; - int vboIndexHandle; + int vboIndexHandle; + + @Override public void dispose () { - @Override - public void dispose( ) - { - } - @Override - public void render( ) - { + @Override public void render () { GL11 gl = Gdx.graphics.getGL11(); - - gl.glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - gl.glClearColor( 0.7f, 0.7f, 0.7f, 1 ); - gl.glClear( GL11.GL_COLOR_BUFFER_BIT ); - - gl.glColor4f( 1, 1, 1, 1 ); - gl.glBindBuffer( GL11.GL_ARRAY_BUFFER, vboHandle ); - gl.glBindBuffer( GL11.GL_ELEMENT_ARRAY_BUFFER, vboIndexHandle ); - gl.glEnableClientState( GL11.GL_VERTEX_ARRAY ); - gl.glVertexPointer( 3, GL11.GL_FLOAT, 7 * 4, 0 ); - gl.glEnableClientState( GL11.GL_COLOR_ARRAY ); - gl.glColorPointer( 4, GL11.GL_FLOAT, 7 * 4, 3 * 4 ); - gl.glDrawArrays( GL11.GL_TRIANGLES, 0, 3 ); - gl.glDrawElements( GL11.GL_TRIANGLES, 3, GL11.GL_UNSIGNED_SHORT, 0 ); + + gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + gl.glClearColor(0.7f, 0.7f, 0.7f, 1); + gl.glClear(GL11.GL_COLOR_BUFFER_BIT); + + gl.glColor4f(1, 1, 1, 1); + gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, vboHandle); + gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, vboIndexHandle); + gl.glEnableClientState(GL11.GL_VERTEX_ARRAY); + gl.glVertexPointer(3, GL11.GL_FLOAT, 7 * 4, 0); + gl.glEnableClientState(GL11.GL_COLOR_ARRAY); + gl.glColorPointer(4, GL11.GL_FLOAT, 7 * 4, 3 * 4); + gl.glDrawArrays(GL11.GL_TRIANGLES, 0, 3); + gl.glDrawElements(GL11.GL_TRIANGLES, 3, GL11.GL_UNSIGNED_SHORT, 0); } - @Override - public void surfaceCreated( ) - { - - FloatBuffer vertices = BufferUtils.newFloatBuffer( 3 * 7 ); - vertices.put( new float[] { - -0.5f, -0.5f, 0, 1, 0, 0, 1, - 0.5f, -0.5f, 0, 0, 1, 0, 1, - 0.0f, 0.5f, 0, 0, 0, 1, 1 - }); + @Override public void surfaceCreated () { + + FloatBuffer vertices = BufferUtils.newFloatBuffer(3 * 7); + vertices.put(new float[] {-0.5f, -0.5f, 0, 1, 0, 0, 1, 0.5f, -0.5f, 0, 0, 1, 0, 1, 0.0f, 0.5f, 0, 0, 0, 1, 1}); vertices.flip(); - + GL11 gl = Gdx.graphics.getGL11(); int[] handle = new int[1]; - gl.glGenBuffers( 1, handle, 0 ); + gl.glGenBuffers(1, handle, 0); vboHandle = handle[0]; - gl.glBindBuffer( GL11.GL_ARRAY_BUFFER, vboHandle ); - gl.glBufferData( GL11.GL_ARRAY_BUFFER, 3 * 7 * 4, vertices, GL11.GL_STATIC_DRAW ); - gl.glBindBuffer( GL11.GL_ARRAY_BUFFER, 0 ); - - ShortBuffer indices = BufferUtils.newShortBuffer( 3 ); - indices.put( new short[ ] { 0, 1, 2 } ); + gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, vboHandle); + gl.glBufferData(GL11.GL_ARRAY_BUFFER, 3 * 7 * 4, vertices, GL11.GL_STATIC_DRAW); + gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0); + + ShortBuffer indices = BufferUtils.newShortBuffer(3); + indices.put(new short[] {0, 1, 2}); indices.flip(); - gl.glGenBuffers( 1, handle, 0 ); + gl.glGenBuffers(1, handle, 0); vboIndexHandle = handle[0]; - gl.glBindBuffer( GL11.GL_ELEMENT_ARRAY_BUFFER, vboIndexHandle ); - gl.glBufferData( GL11.GL_ELEMENT_ARRAY_BUFFER, 3 * 2, indices, GL11.GL_STATIC_DRAW ); - gl.glBindBuffer( GL11.GL_ELEMENT_ARRAY_BUFFER, 0 ); + gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, vboIndexHandle); + gl.glBufferData(GL11.GL_ELEMENT_ARRAY_BUFFER, 3 * 2, indices, GL11.GL_STATIC_DRAW); + gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0); } - - @Override - public void surfaceChanged(int width, int height) { + @Override public void surfaceChanged (int width, int height) { // TODO Auto-generated method stub - + } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/VorbisTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/VorbisTest.java index 636945d33..7a30642bb 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/VorbisTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/VorbisTest.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.nio.ShortBuffer; @@ -23,46 +21,41 @@ import com.badlogic.gdx.RenderListener; import com.badlogic.gdx.audio.analysis.AudioTools; import com.badlogic.gdx.audio.io.VorbisDecoder; -public class VorbisTest implements RenderListener -{ +public class VorbisTest implements RenderListener { - @Override - public void dispose( ) { + @Override public void dispose () { // TODO Auto-generated method stub - + } - @Override - public void render( ) { + @Override public void render () { // TODO Auto-generated method stub - + } - @Override - public void surfaceChanged(int width, int height) { + @Override public void surfaceChanged (int width, int height) { // TODO Auto-generated method stub - + } - @Override - public void surfaceCreated( ) - { + @Override public void surfaceCreated () { VorbisDecoder decoder = null; - if( Gdx.app.getType() == ApplicationType.Android ) - decoder = new VorbisDecoder( "/sdcard/audio/schism.ogg" ); + if (Gdx.app.getType() == ApplicationType.Android) + decoder = new VorbisDecoder("/sdcard/audio/schism.ogg"); else - decoder = new VorbisDecoder( "data/cloudconnected.ogg" ); - Gdx.app.log( "Vorbis", "channels: "+ decoder.getNumChannels() + ", rate: " + decoder.getRate() + ", length: " + decoder.getLength() );; - - ShortBuffer samplesBuffer = AudioTools.allocateShortBuffer( 1024, 2 ); - + decoder = new VorbisDecoder("data/cloudconnected.ogg"); + Gdx.app.log("Vorbis", + "channels: " + decoder.getNumChannels() + ", rate: " + decoder.getRate() + ", length: " + decoder.getLength()); + ; + + ShortBuffer samplesBuffer = AudioTools.allocateShortBuffer(1024, 2); + long start = System.nanoTime(); - while( decoder.readSamples( samplesBuffer ) > 0 ) - { - + while (decoder.readSamples(samplesBuffer) > 0) { + } - Gdx.app.log( "Vorbis", "took " + (System.nanoTime()-start)/1000000000.0 ); - decoder.dispose(); + Gdx.app.log("Vorbis", "took " + (System.nanoTime() - start) / 1000000000.0); + decoder.dispose(); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/WaterRipples.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/WaterRipples.java index 4ea3ca553..a77ad2039 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/WaterRipples.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/WaterRipples.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.tests; import java.util.Random; @@ -23,8 +24,7 @@ import com.badlogic.gdx.math.Plane; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.collision.Ray; -public class WaterRipples implements RenderListener, InputListener -{ +public class WaterRipples implements RenderListener, InputListener { static final short WIDTH = 50; static final short HEIGHT = 50; static final float INV_WIDTH = 1.0f / WIDTH; @@ -33,8 +33,7 @@ public class WaterRipples implements RenderListener, InputListener static final float DISPLACEMENT = -10; static final float TICK = 0.033f; static final int RADIUS = 3; - - + float accum; boolean initialized = false; PerspectiveCamera camera; @@ -42,90 +41,78 @@ public class WaterRipples implements RenderListener, InputListener Font font; Mesh mesh; Texture texture; - Plane plane = new Plane( new Vector3(), new Vector3( 1, 0, 0 ), new Vector3( 0, 1, 0 ) ); - Vector3 point = new Vector3( ); + Plane plane = new Plane(new Vector3(), new Vector3(1, 0, 0), new Vector3(0, 1, 0)); + Vector3 point = new Vector3(); float[][] last; float[][] curr; float[][] intp; float[] vertices; - - @Override - public void surfaceCreated() - { - - if( !initialized ) - { - camera = new PerspectiveCamera( ); - camera.getPosition().set( ( WIDTH ) / 2.0f, ( HEIGHT ) / 2.0f, WIDTH / 2.0f ); - camera.setViewport( Gdx.graphics.getWidth(), Gdx.graphics.getWidth() ); - camera.setFov( 90 ); - camera.setNear( 0.1f ); - camera.setFar( 1000 ); - last = new float[WIDTH+1][HEIGHT+1]; - curr = new float[WIDTH+1][HEIGHT+1]; - intp = new float[WIDTH+1][HEIGHT+1]; - vertices = new float[(WIDTH+1)*(HEIGHT+1)*5]; - mesh = new Mesh( false, false, (WIDTH + 1) * (HEIGHT + 1), WIDTH * HEIGHT * 6, - new VertexAttribute( VertexAttributes.Usage.Position, 3, "a_Position" ), - new VertexAttribute( VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoords" ) ); - texture = Gdx.graphics.newTexture( Gdx.files.getFileHandle( "data/stones.jpg", FileType.Internal ), - TextureFilter.Linear, TextureFilter.Linear, - TextureWrap.ClampToEdge, TextureWrap.ClampToEdge ); - - createIndices( ); - updateVertices( curr ); + + @Override public void surfaceCreated () { + + if (!initialized) { + camera = new PerspectiveCamera(); + camera.getPosition().set((WIDTH) / 2.0f, (HEIGHT) / 2.0f, WIDTH / 2.0f); + camera.setViewport(Gdx.graphics.getWidth(), Gdx.graphics.getWidth()); + camera.setFov(90); + camera.setNear(0.1f); + camera.setFar(1000); + last = new float[WIDTH + 1][HEIGHT + 1]; + curr = new float[WIDTH + 1][HEIGHT + 1]; + intp = new float[WIDTH + 1][HEIGHT + 1]; + vertices = new float[(WIDTH + 1) * (HEIGHT + 1) * 5]; + mesh = new Mesh(false, false, (WIDTH + 1) * (HEIGHT + 1), WIDTH * HEIGHT * 6, new VertexAttribute( + VertexAttributes.Usage.Position, 3, "a_Position"), new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, + "a_texCoords")); + texture = Gdx.graphics.newTexture(Gdx.files.getFileHandle("data/stones.jpg", FileType.Internal), TextureFilter.Linear, + TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); + + createIndices(); + updateVertices(curr); initialized = true; - + batch = new SpriteBatch(); - font = Gdx.graphics.newFont( "Arial", 12, FontStyle.Plain ); - - Gdx.input.addInputListener( this ); + font = Gdx.graphics.newFont("Arial", 12, FontStyle.Plain); + + Gdx.input.addInputListener(this); } } - - private void createIndices( ) - { - short[] indices = new short[WIDTH*HEIGHT*6]; + + private void createIndices () { + short[] indices = new short[WIDTH * HEIGHT * 6]; int idx = 0; short vidx = 0; - for( int y = 0; y < HEIGHT; y++ ) - { + for (int y = 0; y < HEIGHT; y++) { vidx = (short)(y * (WIDTH + 1)); - - for( int x = 0; x < WIDTH; x++ ) - { + + for (int x = 0; x < WIDTH; x++) { indices[idx++] = vidx; indices[idx++] = (short)(vidx + 1); indices[idx++] = (short)(vidx + WIDTH + 1); - + indices[idx++] = (short)(vidx + 1); indices[idx++] = (short)(vidx + WIDTH + 2); indices[idx++] = (short)(vidx + WIDTH + 1); - + vidx++; } } - - mesh.setIndices( indices ); + + mesh.setIndices(indices); } - - private void updateVertices( float[][] curr ) - { + + private void updateVertices (float[][] curr) { int idx = 0; - for( int y = 0; y <= HEIGHT; y++ ) - { - for( int x = 0; x <= WIDTH; x++ ) - { + for (int y = 0; y <= HEIGHT; y++) { + for (int x = 0; x <= WIDTH; x++) { float xOffset = 0; float yOffset = 0; - - if( x > 0 && x < WIDTH && y > 0 && y < HEIGHT ) - { - xOffset = (curr[x-1][y] - curr[x+1][y]); - yOffset = (curr[x][y-1] - curr[x][y+1]); + + if (x > 0 && x < WIDTH && y > 0 && y < HEIGHT) { + xOffset = (curr[x - 1][y] - curr[x + 1][y]); + yOffset = (curr[x][y - 1] - curr[x][y + 1]); } - vertices[idx++] = x; vertices[idx++] = y; vertices[idx++] = 0; @@ -133,157 +120,126 @@ public class WaterRipples implements RenderListener, InputListener vertices[idx++] = (y + yOffset) * INV_HEIGHT; } } - mesh.setVertices( vertices ); + mesh.setVertices(vertices); } - - private void updateWater( ) - { - for( int y = 0; y < HEIGHT + 1; y++ ) - { - for( int x = 0; x < WIDTH + 1; x++ ) - { - if( x > 0 && x < WIDTH && y > 0 && y < HEIGHT ) - { - curr[x][y] = (last[x-1][y]+ - last[x+1][y]+ - last[x][y+1]+ - last[x][y-1]) / 4 - curr[x][y]; + + private void updateWater () { + for (int y = 0; y < HEIGHT + 1; y++) { + for (int x = 0; x < WIDTH + 1; x++) { + if (x > 0 && x < WIDTH && y > 0 && y < HEIGHT) { + curr[x][y] = (last[x - 1][y] + last[x + 1][y] + last[x][y + 1] + last[x][y - 1]) / 4 - curr[x][y]; } curr[x][y] *= DAMPING; } } } - - private void interpolateWater( float alpha ) - { - for( int y = 0; y < HEIGHT; y++ ) - { - for( int x = 0; x < WIDTH; x++ ) - { - intp[x][y] = ( alpha * last[x][y] + (1-alpha)*curr[x][y] ); + + private void interpolateWater (float alpha) { + for (int y = 0; y < HEIGHT; y++) { + for (int x = 0; x < WIDTH; x++) { + intp[x][y] = (alpha * last[x][y] + (1 - alpha) * curr[x][y]); } } } - - private void touchWater( Vector3 point ) - { - for( int y = Math.max(0,(int)point.y-RADIUS); y < Math.min( HEIGHT, (int)point.y+RADIUS); y++ ) - { - for( int x = Math.max(0,(int)point.x-RADIUS); x < Math.min( WIDTH, (int)point.x+RADIUS); x++ ) - { - float val = curr[x][y] + DISPLACEMENT * Math.max(0, (float)Math.cos( Math.PI / 2 * Math.sqrt(point.dst2(x, y, 0)) / RADIUS )); - if( val < DISPLACEMENT ) + + private void touchWater (Vector3 point) { + for (int y = Math.max(0, (int)point.y - RADIUS); y < Math.min(HEIGHT, (int)point.y + RADIUS); y++) { + for (int x = Math.max(0, (int)point.x - RADIUS); x < Math.min(WIDTH, (int)point.x + RADIUS); x++) { + float val = curr[x][y] + DISPLACEMENT + * Math.max(0, (float)Math.cos(Math.PI / 2 * Math.sqrt(point.dst2(x, y, 0)) / RADIUS)); + if (val < DISPLACEMENT) val = DISPLACEMENT; - else - if( val > -DISPLACEMENT ) - val = -DISPLACEMENT; + else if (val > -DISPLACEMENT) val = -DISPLACEMENT; curr[x][y] = val; } } } - + long lastTick = System.nanoTime(); Random rand = new Random(); - - @Override - public void render() - { + + @Override public void render () { GL10 gl = Gdx.graphics.getGL10(); - gl.glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); - gl.glClear( GL10.GL_COLOR_BUFFER_BIT ); - + gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + camera.update(); - gl.glMatrixMode( GL10.GL_PROJECTION ); - gl.glLoadMatrixf( camera.getCombinedMatrix().val, 0 ); - gl.glMatrixMode( GL10.GL_MODELVIEW ); - - accum += Gdx.graphics.getDeltaTime(); - while( accum > TICK ) - { - for( int i = 0; i < 5; i++ ) - { - if( Gdx.input.isTouched( i ) ) - { - Ray ray = camera.getPickRay( Gdx.input.getX(i), (int)(Gdx.input.getY(i) / (float)Gdx.graphics.getHeight() * Gdx.graphics.getWidth())); - Intersector.intersectRayPlane( ray, plane, point ); - touchWater( point ); + gl.glMatrixMode(GL10.GL_PROJECTION); + gl.glLoadMatrixf(camera.getCombinedMatrix().val, 0); + gl.glMatrixMode(GL10.GL_MODELVIEW); + + accum += Gdx.graphics.getDeltaTime(); + while (accum > TICK) { + for (int i = 0; i < 5; i++) { + if (Gdx.input.isTouched(i)) { + Ray ray = camera.getPickRay(Gdx.input.getX(i), + (int)(Gdx.input.getY(i) / (float)Gdx.graphics.getHeight() * Gdx.graphics.getWidth())); + Intersector.intersectRayPlane(ray, plane, point); + touchWater(point); } } - + updateWater(); float[][] tmp = curr; curr = last; last = tmp; - accum -= TICK; + accum -= TICK; } - + float alpha = accum / TICK; - interpolateWater( alpha ); - - updateVertices( intp ); - - gl.glEnable( GL10.GL_TEXTURE_2D ); + interpolateWater(alpha); + + updateVertices(intp); + + gl.glEnable(GL10.GL_TEXTURE_2D); texture.bind(); - mesh.render( GL10.GL_TRIANGLES ); - - - batch.begin( ); - batch.drawText( font, "fps: " + Gdx.graphics.getFramesPerSecond(), 10, 20, Color.WHITE ); + mesh.render(GL10.GL_TRIANGLES); + + batch.begin(); + batch.drawText(font, "fps: " + Gdx.graphics.getFramesPerSecond(), 10, 20, Color.WHITE); batch.end(); } - @Override - public void dispose() - { - + @Override public void dispose () { + } - @Override - public boolean keyDown(int keycode) { + @Override public boolean keyDown (int keycode) { // TODO Auto-generated method stub return false; } - @Override - public boolean keyUp(int keycode) { + @Override public boolean keyUp (int keycode) { // TODO Auto-generated method stub return false; } - @Override - public boolean keyTyped(char character) { + @Override public boolean keyTyped (char character) { // TODO Auto-generated method stub return false; } - @Override - public boolean touchDown(int x, int y, int pointer) - { -// Ray ray = camera.getPickRay( x, (int)(y / (float)Gdx.graphics.getHeight() * Gdx.graphics.getWidth())); -// Intersector.intersectRayPlane( ray, plane, point ); -// touchWater( point ); + @Override public boolean touchDown (int x, int y, int pointer) { +// Ray ray = camera.getPickRay( x, (int)(y / (float)Gdx.graphics.getHeight() * Gdx.graphics.getWidth())); +// Intersector.intersectRayPlane( ray, plane, point ); +// touchWater( point ); return false; } - @Override - public boolean touchUp(int x, int y, int pointer) { + @Override public boolean touchUp (int x, int y, int pointer) { // TODO Auto-generated method stub return false; } - @Override - public boolean touchDragged(int x, int y, int pointer) - { -// Ray ray = camera.getPickRay( x, (int)(y / (float)Gdx.graphics.getHeight() * Gdx.graphics.getWidth())); -// Intersector.intersectRayPlane( ray, plane, point ); -// touchWater( point ); - return false; + @Override public boolean touchDragged (int x, int y, int pointer) { +// Ray ray = camera.getPickRay( x, (int)(y / (float)Gdx.graphics.getHeight() * Gdx.graphics.getWidth())); +// Intersector.intersectRayPlane( ray, plane, point ); +// touchWater( point ); + return false; } - - @Override - public void surfaceChanged(int width, int height) - { - + + @Override public void surfaceChanged (int width, int height) { + } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/ApplyForce.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/ApplyForce.java index 82641333d..6b365d425 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/ApplyForce.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/ApplyForce.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.box2d; import com.badlogic.gdx.Gdx; @@ -21,163 +19,154 @@ import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; +import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.Transform; import com.badlogic.gdx.physics.box2d.World; -import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.joints.FrictionJointDef; -public class ApplyForce extends Box2DTest -{ +public class ApplyForce extends Box2DTest { Body m_body; - - @Override - protected void createWorld(World world) - { - world.setGravity( new Vector2( 0, 0 ) ); - + + @Override protected void createWorld (World world) { + world.setGravity(new Vector2(0, 0)); + float k_restitution = 0.4f; Body ground; - + { - BodyDef bd = new BodyDef( ); - bd.position.set( 0, 20 ); - ground = world.createBody( bd ); - - PolygonShape shape = new PolygonShape( ); - - FixtureDef sd = new FixtureDef( ); + BodyDef bd = new BodyDef(); + bd.position.set(0, 20); + ground = world.createBody(bd); + + PolygonShape shape = new PolygonShape(); + + FixtureDef sd = new FixtureDef(); sd.shape = shape; sd.density = 0; sd.restitution = k_restitution; - - shape.setAsEdge( new Vector2( -20, -20 ), new Vector2( -20, 20 ) ); + + shape.setAsEdge(new Vector2(-20, -20), new Vector2(-20, 20)); ground.createFixture(sd); - - shape.setAsEdge( new Vector2( 20, -20 ), new Vector2( 20, 20 ) ); + + shape.setAsEdge(new Vector2(20, -20), new Vector2(20, 20)); ground.createFixture(sd); - - shape.setAsEdge( new Vector2( -20, 20 ), new Vector2( 20, 20 ) ); + + shape.setAsEdge(new Vector2(-20, 20), new Vector2(20, 20)); ground.createFixture(sd); - - shape.setAsEdge( new Vector2( -20, -20 ), new Vector2( 20, -20 ) ); + + shape.setAsEdge(new Vector2(-20, -20), new Vector2(20, -20)); ground.createFixture(sd); - + shape.dispose(); } - + { - Transform xf1 = new Transform( new Vector2(), 0.3524f * (float)Math.PI ); - xf1.setPosition( xf1.mul( new Vector2( 1, 0 ) ) ); - + Transform xf1 = new Transform(new Vector2(), 0.3524f * (float)Math.PI); + xf1.setPosition(xf1.mul(new Vector2(1, 0))); + Vector2[] vertices = new Vector2[3]; - vertices[0] = xf1.mul( new Vector2( -1, 0 ) ); - vertices[1] = xf1.mul( new Vector2( 1, 0 ) ); - vertices[2] = xf1.mul( new Vector2( 0, 0.5f ) ); - - PolygonShape poly1 = new PolygonShape( ); - poly1.set( vertices ); - - FixtureDef sd1 = new FixtureDef( ); + vertices[0] = xf1.mul(new Vector2(-1, 0)); + vertices[1] = xf1.mul(new Vector2(1, 0)); + vertices[2] = xf1.mul(new Vector2(0, 0.5f)); + + PolygonShape poly1 = new PolygonShape(); + poly1.set(vertices); + + FixtureDef sd1 = new FixtureDef(); sd1.shape = poly1; sd1.density = 4.0f; - - Transform xf2 = new Transform( new Vector2(), -0.3524f * (float)Math.PI); - xf2.setPosition( xf2.mul( new Vector2( -1, 0 ) ) ); - - vertices[0] = xf2.mul( new Vector2( -1, 0 ) ); - vertices[1] = xf2.mul( new Vector2( 1, 0 ) ); - vertices[2] = xf2.mul( new Vector2( 0, 0.5f ) ); - - PolygonShape poly2 = new PolygonShape( ); - poly2.set( vertices ); - - FixtureDef sd2 = new FixtureDef( ); + + Transform xf2 = new Transform(new Vector2(), -0.3524f * (float)Math.PI); + xf2.setPosition(xf2.mul(new Vector2(-1, 0))); + + vertices[0] = xf2.mul(new Vector2(-1, 0)); + vertices[1] = xf2.mul(new Vector2(1, 0)); + vertices[2] = xf2.mul(new Vector2(0, 0.5f)); + + PolygonShape poly2 = new PolygonShape(); + poly2.set(vertices); + + FixtureDef sd2 = new FixtureDef(); sd2.shape = poly2; sd2.density = 2.0f; - - BodyDef bd = new BodyDef( ); + + BodyDef bd = new BodyDef(); bd.type = BodyType.DynamicBody; bd.angularDamping = 5.0f; bd.linearDamping = 0.1f; - - bd.position.set( 0, 2 ); + + bd.position.set(0, 2); bd.angle = (float)Math.PI; bd.allowSleep = false; - m_body = world.createBody( bd ); - m_body.createFixture( sd1 ); - m_body.createFixture( sd2 ); + m_body = world.createBody(bd); + m_body.createFixture(sd1); + m_body.createFixture(sd2); poly1.dispose(); poly2.dispose(); } - + { - PolygonShape shape = new PolygonShape( ); - shape.setAsBox( 0.5f, 0.5f ); - - FixtureDef fd = new FixtureDef( ); + PolygonShape shape = new PolygonShape(); + shape.setAsBox(0.5f, 0.5f); + + FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.density = 1.0f; fd.friction = 0.3f; - - for( int i = 0; i < 10; i++ ) - { - BodyDef bd = new BodyDef( ); + + for (int i = 0; i < 10; i++) { + BodyDef bd = new BodyDef(); bd.type = BodyType.DynamicBody; - - bd.position.set( 0, 5 + 1.54f * i ); - Body body = world.createBody( bd ); - - body.createFixture( fd ); - + + bd.position.set(0, 5 + 1.54f * i); + Body body = world.createBody(bd); + + body.createFixture(fd); + float gravity = 10.0f; float I = body.getInertia(); float mass = body.getMass(); - - float radius = (float)Math.sqrt( 2 * I / mass ); - + + float radius = (float)Math.sqrt(2 * I / mass); + FrictionJointDef jd = new FrictionJointDef(); - jd.localAnchorA.set( 0, 0 ); - jd.localAnchorB.set( 0, 0 ); + jd.localAnchorA.set(0, 0); + jd.localAnchorB.set(0, 0); jd.bodyA = ground; jd.bodyB = body; jd.collideConnected = true; jd.maxForce = mass * gravity; jd.maxTorque = mass * radius * gravity; - - world.createJoint( jd ); + + world.createJoint(jd); } - + shape.dispose(); } } - private final Vector2 tmp = new Vector2( ); - public boolean keyDown( int keyCode ) - { - if( keyCode == Keys.KEYCODE_W ) - { - Vector2 f = m_body.getWorldVector( tmp.set( 0, -200 ) ); - Vector2 p = m_body.getWorldPoint( tmp.set( 0, 2 ) ); - m_body.applyForce( f, p ); + private final Vector2 tmp = new Vector2(); + + public boolean keyDown (int keyCode) { + if (keyCode == Keys.KEYCODE_W) { + Vector2 f = m_body.getWorldVector(tmp.set(0, -200)); + Vector2 p = m_body.getWorldPoint(tmp.set(0, 2)); + m_body.applyForce(f, p); } - if( keyCode == Keys.KEYCODE_A ) - m_body.applyTorque( 50 ); - if( keyCode == Keys.KEYCODE_D ) - m_body.applyTorque( -50 ); - + if (keyCode == Keys.KEYCODE_A) m_body.applyTorque(50); + if (keyCode == Keys.KEYCODE_D) m_body.applyTorque(-50); + return false; } - - public void render( ) - { - super.render( ); - - if( renderer.batch != null ) - { + + public void render () { + super.render(); + + if (renderer.batch != null) { renderer.batch.begin(); - renderer.batch.drawText( renderer.font, "Keys (w), (a), (d) to fly", 0, Gdx.app.getGraphics().getHeight(), Color.WHITE); + renderer.batch.drawText(renderer.font, "Keys (w), (a), (d) to fly", 0, Gdx.app.getGraphics().getHeight(), Color.WHITE); renderer.batch.end(); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/BodyTypes.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/BodyTypes.java index d1d77811e..691ea53da 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/BodyTypes.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/BodyTypes.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.box2d; import com.badlogic.gdx.Gdx; @@ -21,145 +19,133 @@ import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; +import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; -import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.joints.PrismaticJointDef; import com.badlogic.gdx.physics.box2d.joints.RevoluteJointDef; -public class BodyTypes extends Box2DTest -{ +public class BodyTypes extends Box2DTest { Body m_attachment; Body m_platform; float m_speed; - - @Override - protected void createWorld(World world) - { + + @Override protected void createWorld (World world) { Body ground; - + { - BodyDef bd = new BodyDef( ); - ground = world.createBody( bd ); - + BodyDef bd = new BodyDef(); + ground = world.createBody(bd); + PolygonShape shape = new PolygonShape(); - shape.setAsEdge( new Vector2( -20, 0 ), new Vector2( 20, 0 ) ); - + shape.setAsEdge(new Vector2(-20, 0), new Vector2(20, 0)); + FixtureDef fd = new FixtureDef(); fd.shape = shape; - ground.createFixture( fd ); + ground.createFixture(fd); shape.dispose(); } - + { BodyDef bd = new BodyDef(); bd.type = BodyType.DynamicBody; - bd.position.set( 0, 3.0f ); - m_attachment = world.createBody( bd ); - + bd.position.set(0, 3.0f); + m_attachment = world.createBody(bd); + PolygonShape shape = new PolygonShape(); - shape.setAsBox( 0.5f, 2.0f ); - m_attachment.createFixture( shape, 2.0f ); + shape.setAsBox(0.5f, 2.0f); + m_attachment.createFixture(shape, 2.0f); shape.dispose(); } - + { - BodyDef bd = new BodyDef( ); + BodyDef bd = new BodyDef(); bd.type = BodyType.DynamicBody; - bd.position.set( -4.0f, 5.0f ); - m_platform = world.createBody( bd ); - - PolygonShape shape = new PolygonShape( ); - shape.setAsBox( 0.5f, 4.0f, new Vector2( 4.0f, 0 ), 0.5f * (float)Math.PI ); - - FixtureDef fd = new FixtureDef( ); + bd.position.set(-4.0f, 5.0f); + m_platform = world.createBody(bd); + + PolygonShape shape = new PolygonShape(); + shape.setAsBox(0.5f, 4.0f, new Vector2(4.0f, 0), 0.5f * (float)Math.PI); + + FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.friction = 0.6f; fd.density = 2.0f; - - m_platform.createFixture( fd ); + + m_platform.createFixture(fd); shape.dispose(); - + RevoluteJointDef rjd = new RevoluteJointDef(); - rjd.initialize( m_attachment, m_platform, new Vector2( 0, 5.0f ) ); + rjd.initialize(m_attachment, m_platform, new Vector2(0, 5.0f)); rjd.maxMotorTorque = 50.0f; rjd.enableMotor = true; - world.createJoint( rjd ); - + world.createJoint(rjd); + PrismaticJointDef pjd = new PrismaticJointDef(); - pjd.initialize( ground, m_platform, new Vector2( 0, 5.0f ), new Vector2( 1, 0 ) ); - + pjd.initialize(ground, m_platform, new Vector2(0, 5.0f), new Vector2(1, 0)); + pjd.maxMotorForce = 1000.0f; pjd.enableMotor = true; pjd.lowerTranslation = -10f; pjd.upperTranslation = 10.0f; pjd.enableLimit = true; - - world.createJoint( pjd ); - + + world.createJoint(pjd); + m_speed = 3.0f; } - + { BodyDef bd = new BodyDef(); bd.type = BodyType.DynamicBody; - bd.position.set( 0, 8.0f ); - Body body = world.createBody( bd ); - - PolygonShape shape = new PolygonShape( ); - shape.setAsBox( 0.75f, 0.75f ); - - FixtureDef fd = new FixtureDef( ); + bd.position.set(0, 8.0f); + Body body = world.createBody(bd); + + PolygonShape shape = new PolygonShape(); + shape.setAsBox(0.75f, 0.75f); + + FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.friction = 0.6f; fd.density = 2.0f; - - body.createFixture( fd ); + + body.createFixture(fd); shape.dispose(); } } - - private final Vector2 tmp = new Vector2( ); - @Override - public boolean keyDown( int keyCode ) - { - if( keyCode == Keys.KEYCODE_D ) - m_platform.setType( BodyType.DynamicBody ); - if( keyCode == Keys.KEYCODE_S ) - m_platform.setType( BodyType.StaticBody ); - if( keyCode == Keys.KEYCODE_K ) - { - m_platform.setType( BodyType.KinematicBody ); - m_platform.setLinearVelocity( tmp.set( -m_speed, 0 ) ); - m_platform.setAngularVelocity( 0 ); + + private final Vector2 tmp = new Vector2(); + + @Override public boolean keyDown (int keyCode) { + if (keyCode == Keys.KEYCODE_D) m_platform.setType(BodyType.DynamicBody); + if (keyCode == Keys.KEYCODE_S) m_platform.setType(BodyType.StaticBody); + if (keyCode == Keys.KEYCODE_K) { + m_platform.setType(BodyType.KinematicBody); + m_platform.setLinearVelocity(tmp.set(-m_speed, 0)); + m_platform.setAngularVelocity(0); } - + return false; } - - @Override - public void render( ) - { - if( m_platform.getType() == BodyType.KinematicBody ) - { + + @Override public void render () { + if (m_platform.getType() == BodyType.KinematicBody) { Vector2 p = m_platform.getTransform().getPosition(); Vector2 v = m_platform.getLinearVelocity(); - - if( (p.x < -10 && v.x < 0 ) || - (p.x > 10 && v.x > 0 ) ) - { + + if ((p.x < -10 && v.x < 0) || (p.x > 10 && v.x > 0)) { v.x = -v.x; m_platform.setLinearVelocity(v); } } - - super.render( ); - - if( renderer.batch != null ) - { + + super.render(); + + if (renderer.batch != null) { renderer.batch.begin(); - renderer.batch.drawText( renderer.font, "Keys: (d) dynamic, (s) static, (k) kinematic", 0, Gdx.app.getGraphics().getHeight(), Color.WHITE ); + renderer.batch.drawText(renderer.font, "Keys: (d) dynamic, (s) static, (k) kinematic", 0, Gdx.app.getGraphics() + .getHeight(), Color.WHITE); renderer.batch.end(); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/Box2DTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/Box2DTest.java index 58bd99ed4..443aeae30 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/Box2DTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/Box2DTest.java @@ -1,20 +1,17 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ -package com.badlogic.gdx.tests.box2d; +package com.badlogic.gdx.tests.box2d; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputListener; @@ -24,204 +21,181 @@ import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; +import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer; import com.badlogic.gdx.physics.box2d.Fixture; import com.badlogic.gdx.physics.box2d.QueryCallback; import com.badlogic.gdx.physics.box2d.World; -import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.joints.MouseJoint; import com.badlogic.gdx.physics.box2d.joints.MouseJointDef; /** - * Base class for all Box2D Testbed tests, all subclasses - * must implement the createWorld() method. + * Base class for all Box2D Testbed tests, all subclasses must implement the createWorld() method. * * @author badlogicgames@gmail.com - * + * */ -public abstract class Box2DTest implements RenderListener, InputListener -{ +public abstract class Box2DTest implements RenderListener, InputListener { /** the camera **/ protected OrthographicCamera camera; - + /** the renderer **/ protected Box2DDebugRenderer renderer; - + /** our box2D world **/ - protected World world; - + protected World world; + /** ground body to connect the mouse joint to **/ protected Body groundBody; - + /** our mouse joint **/ protected MouseJoint mouseJoint = null; - + /** a hit body **/ - protected Body hitBody = null; + protected Body hitBody = null; + + protected abstract void createWorld (World world); - protected abstract void createWorld( World world ); - /** temp vector **/ protected Vector2 tmp = new Vector2(); - - @Override - public void render() - { + + @Override public void render () { // update the world with a fixed time step - world.step( Gdx.app.getGraphics().getDeltaTime(), 8, 3 ); - + world.step(Gdx.app.getGraphics().getDeltaTime(), 8, 3); + // clear the screen and setup the projection matrix - GL10 gl = Gdx.app.getGraphics().getGL10(); - gl.glClear( GL10.GL_COLOR_BUFFER_BIT ); - camera.setMatrices( ); - + GL10 gl = Gdx.app.getGraphics().getGL10(); + gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + camera.setMatrices(); + // render the world using the debug renderer - renderer.render( world ); + renderer.render(world); } - @Override - public void surfaceChanged(int width, int height) { + @Override public void surfaceChanged (int width, int height) { // TODO Auto-generated method stub - + } - @Override - public void surfaceCreated( ) - { - // setup the camera. In Box2D we operate on a + @Override public void surfaceCreated () { + // setup the camera. In Box2D we operate on a // meter scale, pixels won't do it. So we use // an orthographic camera with a viewport of // 48 meters in width and 32 meters in height. - // We also position the camera so that it + // We also position the camera so that it // looks at (0,16) (that's where the middle of the // screen will be located). - camera = new OrthographicCamera( ); - camera.setViewport( 48, 32 ); - camera.getPosition().set( 0, 15, 0 ); - + camera = new OrthographicCamera(); + camera.setViewport(48, 32); + camera.getPosition().set(0, 15, 0); + // create the debug renderer - renderer = new Box2DDebugRenderer( ); - + renderer = new Box2DDebugRenderer(); + // create the world - world = new World( new Vector2( 0, -10 ), true ); - + world = new World(new Vector2(0, -10), true); + // we also need an invisible zero size ground body // to which we can connect the mouse joint BodyDef bodyDef = new BodyDef(); groundBody = world.createBody(bodyDef); - + // finally we register ourself as an InputListener so we // can manipulate our world - Gdx.input.addInputListener( this ); - + Gdx.input.addInputListener(this); + // call abstract method to populate the world - createWorld( world ); + createWorld(world); } - - @Override - public void dispose( ) - { - Gdx.input.removeInputListener( this ); - + + @Override public void dispose () { + Gdx.input.removeInputListener(this); + renderer.dispose(); world.dispose(); - + renderer = null; world = null; mouseJoint = null; - hitBody = null; + hitBody = null; } - @Override - public boolean keyDown(int keycode) { + @Override public boolean keyDown (int keycode) { // TODO Auto-generated method stub return false; } - @Override - public boolean keyTyped(char character) { + @Override public boolean keyTyped (char character) { // TODO Auto-generated method stub return false; } - @Override - public boolean keyUp(int keycode) { + @Override public boolean keyUp (int keycode) { // TODO Auto-generated method stub return false; } /** we instantiate this vector and the callback here so we don't irritate the GC **/ - Vector2 testPoint = new Vector2( ); - QueryCallback callback = new QueryCallback() { - @Override - public boolean reportFixture(Fixture fixture) - { + Vector2 testPoint = new Vector2(); + QueryCallback callback = new QueryCallback() { + @Override public boolean reportFixture (Fixture fixture) { // if the hit point is inside the fixture of the body // we report it - if( fixture.testPoint( testPoint ) ) - { + if (fixture.testPoint(testPoint)) { hitBody = fixture.getBody(); return false; - } - else + } else return true; } }; - @Override - public boolean touchDown(int x, int y, int pointer) - { + + @Override public boolean touchDown (int x, int y, int pointer) { // translate the mouse coordinates to world coordinates - camera.getScreenToWorld( x, y, testPoint ); - // ask the world which bodies are within the given + camera.getScreenToWorld(x, y, testPoint); + // ask the world which bodies are within the given // bounding box around the mouse pointer hitBody = null; - world.QueryAABB( callback, testPoint.x - 0.0001f, testPoint.y - 0.0001f, testPoint.x + 0.0001f, testPoint.y + 0.0001f ); - - if( hitBody == groundBody ) - hitBody = null; - + world.QueryAABB(callback, testPoint.x - 0.0001f, testPoint.y - 0.0001f, testPoint.x + 0.0001f, testPoint.y + 0.0001f); + + if (hitBody == groundBody) hitBody = null; + // ignore kinematic bodies, they don't work with the mouse joint - if( hitBody != null && hitBody.getType() == BodyType.KinematicBody ) - return false; - + if (hitBody != null && hitBody.getType() == BodyType.KinematicBody) return false; + // if we hit something we create a new mouse joint - // and attach it to the hit body. - if( hitBody != null) - { + // and attach it to the hit body. + if (hitBody != null) { MouseJointDef def = new MouseJointDef(); def.bodyA = groundBody; def.bodyB = hitBody; def.collideConnected = true; - def.target.set( testPoint ); + def.target.set(testPoint); def.maxForce = 1000.0f * hitBody.getMass(); - - mouseJoint = (MouseJoint)world.createJoint( def ); + + mouseJoint = (MouseJoint)world.createJoint(def); hitBody.setAwake(true); } - + return false; } /** another temporary vector **/ - Vector2 target = new Vector2( ); - @Override - public boolean touchDragged(int x, int y, int pointer) { + Vector2 target = new Vector2(); + + @Override public boolean touchDragged (int x, int y, int pointer) { // if a mouse joint exists we simply update // the target of the joint based on the new // mouse coordinates - if( mouseJoint != null ) - { - camera.getScreenToWorld( x, y, target ); - mouseJoint.setTarget( target ); + if (mouseJoint != null) { + camera.getScreenToWorld(x, y, target); + mouseJoint.setTarget(target); } - return false; + return false; } - @Override - public boolean touchUp(int x, int y, int pointer) { + @Override public boolean touchUp (int x, int y, int pointer) { // if a mouse joint exists we simply destroy it - if( mouseJoint != null ) - { + if (mouseJoint != null) { world.destroyJoint(mouseJoint); mouseJoint = null; } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/Bridge.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/Bridge.java index 2c7a1622c..f2cb050c6 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/Bridge.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/Bridge.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.box2d; import com.badlogic.gdx.math.Vector2; @@ -25,96 +23,90 @@ import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; import com.badlogic.gdx.physics.box2d.joints.RevoluteJointDef; -public class Bridge extends Box2DTest -{ +public class Bridge extends Box2DTest { int e_count = 30; - @Override - protected void createWorld(World world) - { + @Override protected void createWorld (World world) { Body ground; { BodyDef bd = new BodyDef(); ground = world.createBody(bd); - - PolygonShape shape = new PolygonShape( ); - shape.setAsEdge( new Vector2( -40, 0 ), new Vector2( 40.0f, 0 ) ); - - ground.createFixture( shape, 0 ); + + PolygonShape shape = new PolygonShape(); + shape.setAsEdge(new Vector2(-40, 0), new Vector2(40.0f, 0)); + + ground.createFixture(shape, 0); shape.dispose(); } - + { - PolygonShape shape = new PolygonShape( ); - shape.setAsBox( 0.5f, 0.125f ); + PolygonShape shape = new PolygonShape(); + shape.setAsBox(0.5f, 0.125f); FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.density = 20.0f; fd.friction = 0.2f; - + RevoluteJointDef jd = new RevoluteJointDef(); - + Body prevBody = ground; - - for( int i = 0; i < e_count; i++ ) - { + + for (int i = 0; i < e_count; i++) { BodyDef bd = new BodyDef(); bd.type = BodyType.DynamicBody; - bd.position.set( -14.5f + 1.0f * i, 5.0f ); - Body body = world.createBody( bd ); - body.createFixture( fd ); - - Vector2 anchor = new Vector2( -15.0f + 1.0f * i, 5.0f ); - jd.initialize(prevBody, body, anchor ); - world.createJoint( jd ); + bd.position.set(-14.5f + 1.0f * i, 5.0f); + Body body = world.createBody(bd); + body.createFixture(fd); + + Vector2 anchor = new Vector2(-15.0f + 1.0f * i, 5.0f); + jd.initialize(prevBody, body, anchor); + world.createJoint(jd); prevBody = body; } - - Vector2 anchor = new Vector2( -15.0f + 1.0f * e_count, 5.0f ); - jd.initialize( prevBody, ground, anchor); - world.createJoint( jd ); + + Vector2 anchor = new Vector2(-15.0f + 1.0f * e_count, 5.0f); + jd.initialize(prevBody, ground, anchor); + world.createJoint(jd); shape.dispose(); } - - for( int i = 0; i < 2; i++ ) - { + + for (int i = 0; i < 2; i++) { Vector2[] vertices = new Vector2[3]; - vertices[0] = new Vector2( -0.5f, 0 ); - vertices[1] = new Vector2( 0.5f, 0 ); - vertices[2] = new Vector2( 0, 1.5f ); - - PolygonShape shape = new PolygonShape( ); - shape.set( vertices ); - + vertices[0] = new Vector2(-0.5f, 0); + vertices[1] = new Vector2(0.5f, 0); + vertices[2] = new Vector2(0, 1.5f); + + PolygonShape shape = new PolygonShape(); + shape.set(vertices); + FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.density = 1.0f; - + BodyDef bd = new BodyDef(); bd.type = BodyType.DynamicBody; - bd.position.set( -8.0f + 8.0f * i, 12.0f ); - Body body = world.createBody( bd ); - body.createFixture( fd ); - + bd.position.set(-8.0f + 8.0f * i, 12.0f); + Body body = world.createBody(bd); + body.createFixture(fd); + shape.dispose(); } - - for( int i = 0; i < 3; i++ ) - { - CircleShape shape = new CircleShape( ); - shape.setRadius( 0.5f ); - + + for (int i = 0; i < 3; i++) { + CircleShape shape = new CircleShape(); + shape.setRadius(0.5f); + FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.density = 1.0f; - - BodyDef bd = new BodyDef( ); + + BodyDef bd = new BodyDef(); bd.type = BodyType.DynamicBody; - bd.position.set( -6.0f + 6.0f * i, 10.0f ); - - Body body = world.createBody( bd ); - body.createFixture( fd ); - + bd.position.set(-6.0f + 6.0f * i, 10.0f); + + Body body = world.createBody(bd); + body.createFixture(fd); + shape.dispose(); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/Cantilever.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/Cantilever.java index c9ddff1dc..afc5526a5 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/Cantilever.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/Cantilever.java @@ -1,209 +1,196 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.box2d; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; +import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.CircleShape; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; -import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.joints.WeldJointDef; -public class Cantilever extends Box2DTest -{ +public class Cantilever extends Box2DTest { Body m_middle; final int e_count = 8; - @Override - protected void createWorld(World world) - { + @Override protected void createWorld (World world) { Body ground; { BodyDef bd = new BodyDef(); - ground = world.createBody( bd ); - - PolygonShape shape = new PolygonShape( ); - shape.setAsEdge( new Vector2( -40, 0 ), new Vector2( 40, 0 ) ); - ground.createFixture( shape, 0 ); + ground = world.createBody(bd); + + PolygonShape shape = new PolygonShape(); + shape.setAsEdge(new Vector2(-40, 0), new Vector2(40, 0)); + ground.createFixture(shape, 0); shape.dispose(); } - + { PolygonShape shape = new PolygonShape(); - shape.setAsBox( 0.5f, 0.125f ); - + shape.setAsBox(0.5f, 0.125f); + FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.density = 20.0f; - + WeldJointDef jd = new WeldJointDef(); - + Body prevBody = ground; - for( int i = 0; i < e_count; i++ ) - { - BodyDef bd = new BodyDef( ); + for (int i = 0; i < e_count; i++) { + BodyDef bd = new BodyDef(); bd.type = BodyType.DynamicBody; - bd.position.set( -14.5f + 1.0f * i, 5.0f ); - Body body = world.createBody( bd ); - body.createFixture( fd ); - - Vector2 anchor = new Vector2( -15.0f + 1 * i, 5.0f ); - jd.initialize( prevBody, body, anchor); - world.createJoint( jd ); + bd.position.set(-14.5f + 1.0f * i, 5.0f); + Body body = world.createBody(bd); + body.createFixture(fd); + + Vector2 anchor = new Vector2(-15.0f + 1 * i, 5.0f); + jd.initialize(prevBody, body, anchor); + world.createJoint(jd); prevBody = body; } - + shape.dispose(); } - + { PolygonShape shape = new PolygonShape(); - shape.setAsBox( 0.5f, 0.125f ); - + shape.setAsBox(0.5f, 0.125f); + FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.density = 20.0f; - + WeldJointDef jd = new WeldJointDef(); - + Body prevBody = ground; - for( int i = 0; i < e_count; i++ ) - { - BodyDef bd = new BodyDef( ); + for (int i = 0; i < e_count; i++) { + BodyDef bd = new BodyDef(); bd.type = BodyType.DynamicBody; - bd.position.set( -14.5f + 1.0f * i, 15.0f ); + bd.position.set(-14.5f + 1.0f * i, 15.0f); bd.inertiaScale = 10.0f; - Body body = world.createBody( bd ); - body.createFixture( fd ); - - Vector2 anchor = new Vector2( -15.0f + 1.0f * i, 15.0f ); - jd.initialize( prevBody, body, anchor ); - world.createJoint( jd ); - + Body body = world.createBody(bd); + body.createFixture(fd); + + Vector2 anchor = new Vector2(-15.0f + 1.0f * i, 15.0f); + jd.initialize(prevBody, body, anchor); + world.createJoint(jd); + prevBody = body; } - + shape.dispose(); } - + { PolygonShape shape = new PolygonShape(); - shape.setAsBox( 0.5f, 0.125f ); - - FixtureDef fd = new FixtureDef( ); + shape.setAsBox(0.5f, 0.125f); + + FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.density = 20.0f; - + WeldJointDef jd = new WeldJointDef(); - + Body prevBody = ground; - for( int i = 0; i < e_count; i++ ) - { - BodyDef bd = new BodyDef( ); + for (int i = 0; i < e_count; i++) { + BodyDef bd = new BodyDef(); bd.type = BodyType.DynamicBody; - bd.position.set( -4.5f + 1.0f * i, 5.0f ); - Body body = world.createBody( bd ); - body.createFixture( fd ); - - if( i > 0 ) - { - Vector2 anchor = new Vector2(-5.0f + 1.0f * i, 5.0f ); - jd.initialize( prevBody, body, anchor ); - world.createJoint( jd ); + bd.position.set(-4.5f + 1.0f * i, 5.0f); + Body body = world.createBody(bd); + body.createFixture(fd); + + if (i > 0) { + Vector2 anchor = new Vector2(-5.0f + 1.0f * i, 5.0f); + jd.initialize(prevBody, body, anchor); + world.createJoint(jd); } - + prevBody = body; } - + shape.dispose(); } - + { PolygonShape shape = new PolygonShape(); - shape.setAsBox( 0.5f, 0.125f ); - - FixtureDef fd = new FixtureDef( ); + shape.setAsBox(0.5f, 0.125f); + + FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.density = 20.0f; - + WeldJointDef jd = new WeldJointDef(); - + Body prevBody = ground; - for( int i = 0; i < e_count; i++ ) - { - BodyDef bd = new BodyDef( ); + for (int i = 0; i < e_count; i++) { + BodyDef bd = new BodyDef(); bd.type = BodyType.DynamicBody; - bd.position.set( 5.5f + 1.0f * i, 10.0f ); + bd.position.set(5.5f + 1.0f * i, 10.0f); bd.inertiaScale = 10.0f; - Body body = world.createBody( bd ); - body.createFixture( fd ); - - if( i > 0 ) - { - Vector2 anchor = new Vector2(5.0f + 1.0f * i, 10.0f ); - jd.initialize( prevBody, body, anchor ); - world.createJoint( jd ); + Body body = world.createBody(bd); + body.createFixture(fd); + + if (i > 0) { + Vector2 anchor = new Vector2(5.0f + 1.0f * i, 10.0f); + jd.initialize(prevBody, body, anchor); + world.createJoint(jd); } - + prevBody = body; } - + shape.dispose(); } - - for( int i = 0; i < 2; i++ ) - { + + for (int i = 0; i < 2; i++) { Vector2[] vertices = new Vector2[3]; - vertices[0] = new Vector2( -0.5f, 0 ); - vertices[1] = new Vector2( 0.5f, 0 ); - vertices[2] = new Vector2( 0, 1.5f ); - - PolygonShape shape = new PolygonShape( ); - shape.set( vertices ); - - FixtureDef fd = new FixtureDef( ); + vertices[0] = new Vector2(-0.5f, 0); + vertices[1] = new Vector2(0.5f, 0); + vertices[2] = new Vector2(0, 1.5f); + + PolygonShape shape = new PolygonShape(); + shape.set(vertices); + + FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.density = 1.0f; - - BodyDef bd = new BodyDef( ); + + BodyDef bd = new BodyDef(); bd.type = BodyType.DynamicBody; - bd.position.set( -8.0f + 8.0f * i, 12.0f ); - Body body = world.createBody( bd ); + bd.position.set(-8.0f + 8.0f * i, 12.0f); + Body body = world.createBody(bd); body.createFixture(fd); - + shape.dispose(); } - - for( int i = 0; i < 2; i++ ) - { + + for (int i = 0; i < 2; i++) { CircleShape shape = new CircleShape(); - shape.setRadius( 0.5f ); - + shape.setRadius(0.5f); + FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.density = 1.0f; - + BodyDef bd = new BodyDef(); bd.type = BodyType.DynamicBody; - bd.position.set( -6.0f + 6.0f * i, 10.0f ); - Body body = world.createBody( bd ); - body.createFixture( fd ); + bd.position.set(-6.0f + 6.0f * i, 10.0f); + Body body = world.createBody(bd); + body.createFixture(fd); shape.dispose(); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/Chain.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/Chain.java index d22bd0c77..a303dbc04 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/Chain.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/Chain.java @@ -1,77 +1,71 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.box2d; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; +import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; -import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.joints.RevoluteJointDef; -public class Chain extends Box2DTest -{ +public class Chain extends Box2DTest { - @Override - protected void createWorld(World world) - { + @Override protected void createWorld (World world) { Body ground; - + { BodyDef bd = new BodyDef(); - ground = world.createBody( bd ); - + ground = world.createBody(bd); + PolygonShape shape = new PolygonShape(); - shape.setAsEdge( new Vector2( -40, 0 ), new Vector2( 40, 0 ) ); - - ground.createFixture( shape, 0.0f ); + shape.setAsEdge(new Vector2(-40, 0), new Vector2(40, 0)); + + ground.createFixture(shape, 0.0f); shape.dispose(); } - + { - PolygonShape shape = new PolygonShape( ); - shape.setAsBox( 0.6f, 0.125f ); - - FixtureDef fd = new FixtureDef( ); + PolygonShape shape = new PolygonShape(); + shape.setAsBox(0.6f, 0.125f); + + FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.density = 20.0f; fd.friction = 0.2f; - - RevoluteJointDef jd = new RevoluteJointDef( ); + + RevoluteJointDef jd = new RevoluteJointDef(); jd.collideConnected = false; - + float y = 25.0f; Body prevBody = ground; - - for( int i = 0; i < 30; i++ ) - { + + for (int i = 0; i < 30; i++) { BodyDef bd = new BodyDef(); bd.type = BodyType.DynamicBody; - bd.position.set( 0.5f + i, y ); + bd.position.set(0.5f + i, y); Body body = world.createBody(bd); body.createFixture(fd); - - Vector2 anchor = new Vector2( i, y ); - jd.initialize( prevBody, body, anchor ); - world.createJoint( jd ); + + Vector2 anchor = new Vector2(i, y); + jd.initialize(prevBody, body, anchor); + world.createJoint(jd); prevBody = body; } - + shape.dispose(); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/CharacterCollision.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/CharacterCollision.java index 60cc9e06e..5450777cc 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/CharacterCollision.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/CharacterCollision.java @@ -1,155 +1,149 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.box2d; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; +import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.CircleShape; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; -import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; -public class CharacterCollision extends Box2DTest -{ +public class CharacterCollision extends Box2DTest { - @Override - protected void createWorld(World world) - { + @Override protected void createWorld (World world) { { BodyDef bd = new BodyDef(); - Body ground = world.createBody( bd ); - + Body ground = world.createBody(bd); + PolygonShape shape = new PolygonShape(); - shape.setAsEdge( new Vector2( -20, 0 ), new Vector2( 20, 0 ) ); - ground.createFixture( shape, 0); + shape.setAsEdge(new Vector2(-20, 0), new Vector2(20, 0)); + ground.createFixture(shape, 0); shape.dispose(); } - + { BodyDef bd = new BodyDef(); - Body ground = world.createBody( bd ); - - PolygonShape shape = new PolygonShape( ); - shape.setRadius( 0 ); - shape.setAsEdge( new Vector2( -8, 1 ), new Vector2( -6, 1 ) ); - ground.createFixture( shape, 0 ); - shape.setAsEdge( new Vector2( -6, 1 ), new Vector2( -4, 1 ) ); - ground.createFixture( shape, 0 ); - shape.setAsEdge( new Vector2( -4, 1 ), new Vector2( -2, 1 ) ); - ground.createFixture(shape, 0 ); + Body ground = world.createBody(bd); + + PolygonShape shape = new PolygonShape(); + shape.setRadius(0); + shape.setAsEdge(new Vector2(-8, 1), new Vector2(-6, 1)); + ground.createFixture(shape, 0); + shape.setAsEdge(new Vector2(-6, 1), new Vector2(-4, 1)); + ground.createFixture(shape, 0); + shape.setAsEdge(new Vector2(-4, 1), new Vector2(-2, 1)); + ground.createFixture(shape, 0); shape.dispose(); } - + { - BodyDef bd = new BodyDef( ); - Body ground = world.createBody( bd ); - - PolygonShape shape = new PolygonShape( ); - shape.setAsBox( 1, 1, new Vector2( 4, 3 ), 0 ); - ground.createFixture( shape, 0); - shape.setAsBox( 1, 1, new Vector2( 6, 3 ), 0 ); - ground.createFixture( shape, 0 ); - shape.setAsBox( 1, 1, new Vector2( 8, 3 ), 0); - ground.createFixture( shape, 0 ); + BodyDef bd = new BodyDef(); + Body ground = world.createBody(bd); + + PolygonShape shape = new PolygonShape(); + shape.setAsBox(1, 1, new Vector2(4, 3), 0); + ground.createFixture(shape, 0); + shape.setAsBox(1, 1, new Vector2(6, 3), 0); + ground.createFixture(shape, 0); + shape.setAsBox(1, 1, new Vector2(8, 3), 0); + ground.createFixture(shape, 0); shape.dispose(); } - + { - BodyDef bd = new BodyDef( ); - Body ground = world.createBody( bd ); - - PolygonShape shape = new PolygonShape( ); - float d = 2 * 2 * 0.005f; - shape.setRadius( 0 ); - shape.setAsEdge( new Vector2( -1 + d, 3 ), new Vector2( 1 - d, 3 ) ); - ground.createFixture( shape, 0 ); - shape.setAsEdge( new Vector2( 1, 3 + d ), new Vector2( 1, 5 - d ) ); - ground.createFixture( shape, 0 ); - shape.setAsEdge( new Vector2( 1 - d, 5 ), new Vector2( -1 + d, 5 ) ); - ground.createFixture(shape, 0 ); - shape.setAsEdge( new Vector2( -1, 5 - d), new Vector2( -1, 3 + d ) ); - ground.createFixture(shape, 0 ); - shape.dispose(); + BodyDef bd = new BodyDef(); + Body ground = world.createBody(bd); + + PolygonShape shape = new PolygonShape(); + float d = 2 * 2 * 0.005f; + shape.setRadius(0); + shape.setAsEdge(new Vector2(-1 + d, 3), new Vector2(1 - d, 3)); + ground.createFixture(shape, 0); + shape.setAsEdge(new Vector2(1, 3 + d), new Vector2(1, 5 - d)); + ground.createFixture(shape, 0); + shape.setAsEdge(new Vector2(1 - d, 5), new Vector2(-1 + d, 5)); + ground.createFixture(shape, 0); + shape.setAsEdge(new Vector2(-1, 5 - d), new Vector2(-1, 3 + d)); + ground.createFixture(shape, 0); + shape.dispose(); } - + { - BodyDef bd = new BodyDef( ); - bd.position.set( -3, 5 ); + BodyDef bd = new BodyDef(); + bd.position.set(-3, 5); bd.type = BodyType.DynamicBody; bd.fixedRotation = true; bd.allowSleep = false; - - Body body = world.createBody( bd ); - + + Body body = world.createBody(bd); + PolygonShape shape = new PolygonShape(); - shape.setAsBox( 0.5f, 0.5f ); - - FixtureDef fd = new FixtureDef( ); + shape.setAsBox(0.5f, 0.5f); + + FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.density = 20.0f; - body.createFixture( fd ); + body.createFixture(fd); shape.dispose(); } - + { - BodyDef bd = new BodyDef( ); - bd.position.set( -5, 5 ); + BodyDef bd = new BodyDef(); + bd.position.set(-5, 5); bd.type = BodyType.DynamicBody; bd.fixedRotation = true; bd.allowSleep = false; - - Body body = world.createBody( bd ); - + + Body body = world.createBody(bd); + float angle = 0; float delta = (float)Math.PI / 3; Vector2[] vertices = new Vector2[6]; - for( int i = 0; i < 6; i++ ) - { - vertices[i] = new Vector2( 0.5f * (float)Math.cos( angle ), 0.5f * (float)Math.sin( angle ) ); + for (int i = 0; i < 6; i++) { + vertices[i] = new Vector2(0.5f * (float)Math.cos(angle), 0.5f * (float)Math.sin(angle)); angle += delta; } - - PolygonShape shape = new PolygonShape( ); - shape.set( vertices ); - - FixtureDef fd = new FixtureDef( ); + + PolygonShape shape = new PolygonShape(); + shape.set(vertices); + + FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.density = 20.0f; - body.createFixture( fd ); + body.createFixture(fd); shape.dispose(); } - + { - BodyDef bd = new BodyDef( ); - bd.position.set( 3, 5 ); + BodyDef bd = new BodyDef(); + bd.position.set(3, 5); bd.type = BodyType.DynamicBody; bd.fixedRotation = true; bd.allowSleep = false; - - Body body = world.createBody( bd ); - + + Body body = world.createBody(bd); + CircleShape shape = new CircleShape(); - shape.setRadius( 0.5f ); - - FixtureDef fd = new FixtureDef( ); + shape.setRadius(0.5f); + + FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.density = 20.0f; - body.createFixture( fd ); + body.createFixture(fd); shape.dispose(); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/CollisionFiltering.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/CollisionFiltering.java index 734e0b8e7..20f288089 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/CollisionFiltering.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/CollisionFiltering.java @@ -1,37 +1,33 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.box2d; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; +import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.CircleShape; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; -import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.joints.PrismaticJointDef; -public class CollisionFiltering extends Box2DTest -{ +public class CollisionFiltering extends Box2DTest { private final static short k_smallGroup = 1; private final static short k_largeGroup = -1; - @SuppressWarnings("unused") - private final static short k_defaultCategory = 0x0001; + @SuppressWarnings("unused") private final static short k_defaultCategory = 0x0001; private final static short k_triangleCategory = 0x0002; private final static short k_boxCategory = 0x0004; private final static short k_circleCategory = 0x0008; @@ -40,132 +36,128 @@ public class CollisionFiltering extends Box2DTest private final static short k_boxMask = -1 ^ k_triangleCategory; private final static short k_circleMask = -1; - - @Override - protected void createWorld(World world) - { + @Override protected void createWorld (World world) { { - PolygonShape shape = new PolygonShape( ); - shape.setAsEdge( new Vector2( -40.0f, 0 ), new Vector2( 40, 0 ) ); - - FixtureDef fd = new FixtureDef( ); + PolygonShape shape = new PolygonShape(); + shape.setAsEdge(new Vector2(-40.0f, 0), new Vector2(40, 0)); + + FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.friction = 0.3f; - + BodyDef bd = new BodyDef(); - Body ground = world.createBody( bd ); - ground.createFixture( fd ); + Body ground = world.createBody(bd); + ground.createFixture(fd); shape.dispose(); } - + Vector2[] vertices = new Vector2[3]; - vertices[0] = new Vector2( -1, 0 ); - vertices[1] = new Vector2(1, 0 ); - vertices[2] = new Vector2(0, 2 ); - PolygonShape polygon = new PolygonShape( ); - polygon.set( vertices ); - - FixtureDef triangleShapeDef = new FixtureDef( ); + vertices[0] = new Vector2(-1, 0); + vertices[1] = new Vector2(1, 0); + vertices[2] = new Vector2(0, 2); + PolygonShape polygon = new PolygonShape(); + polygon.set(vertices); + + FixtureDef triangleShapeDef = new FixtureDef(); triangleShapeDef.shape = polygon; triangleShapeDef.density = 1.0f; - + triangleShapeDef.filter.groupIndex = k_smallGroup; triangleShapeDef.filter.categoryBits = k_triangleCategory; triangleShapeDef.filter.maskBits = k_triangleMask; - - BodyDef triangleBodyDef = new BodyDef( ); + + BodyDef triangleBodyDef = new BodyDef(); triangleBodyDef.type = BodyType.DynamicBody; - triangleBodyDef.position.set( -5, 2 ); - - Body body1 = world.createBody( triangleBodyDef ); - body1.createFixture( triangleShapeDef ); - + triangleBodyDef.position.set(-5, 2); + + Body body1 = world.createBody(triangleBodyDef); + body1.createFixture(triangleShapeDef); + vertices[0].mul(2); vertices[1].mul(2); vertices[2].mul(2); - - polygon.set(vertices ); + + polygon.set(vertices); triangleShapeDef.filter.groupIndex = k_largeGroup; - triangleBodyDef.position.set( -5, 6 ); + triangleBodyDef.position.set(-5, 6); triangleBodyDef.fixedRotation = true; - - Body body2 = world.createBody( triangleBodyDef ); - body2.createFixture( triangleShapeDef ); - + + Body body2 = world.createBody(triangleBodyDef); + body2.createFixture(triangleShapeDef); + { - BodyDef bd = new BodyDef( ); + BodyDef bd = new BodyDef(); bd.type = BodyType.DynamicBody; - bd.position.set( -5, 10 ); - Body body = world.createBody( bd ); - - PolygonShape p = new PolygonShape( ); - p.setAsBox( 0.5f, 1.0f ); - body.createFixture( p, 1 ); - + bd.position.set(-5, 10); + Body body = world.createBody(bd); + + PolygonShape p = new PolygonShape(); + p.setAsBox(0.5f, 1.0f); + body.createFixture(p, 1); + PrismaticJointDef jd = new PrismaticJointDef(); jd.bodyA = body2; jd.bodyB = body; jd.enableLimit = true; - jd.localAnchorA.set( 0, 4 ); + jd.localAnchorA.set(0, 4); jd.localAnchorB.set(0, 0); - jd.localAxis1.set( 0, 1 ); + jd.localAxis1.set(0, 1); jd.lowerTranslation = -1; jd.upperTranslation = 1; - - world.createJoint( jd ); - + + world.createJoint(jd); + p.dispose(); } - - polygon.setAsBox( 1, 0.5f ); - FixtureDef boxShapeDef = new FixtureDef( ); + + polygon.setAsBox(1, 0.5f); + FixtureDef boxShapeDef = new FixtureDef(); boxShapeDef.shape = polygon; boxShapeDef.density = 1; boxShapeDef.restitution = 0.1f; - - boxShapeDef.filter.groupIndex = k_smallGroup; - boxShapeDef.filter.categoryBits = k_boxCategory; - boxShapeDef.filter.maskBits = k_boxMask; - - BodyDef boxBodyDef = new BodyDef(); - boxBodyDef.type = BodyType.DynamicBody; - boxBodyDef.position.set( 0, 2 ); - - Body body3 = world.createBody( boxBodyDef ); - body3.createFixture(boxShapeDef); - - polygon.setAsBox( 2, 1 ); - boxShapeDef.filter.groupIndex = k_largeGroup; - boxBodyDef.position.set( 0, 6 ); - - Body body4 = world.createBody( boxBodyDef ); - body4.createFixture(boxShapeDef ); - - CircleShape circle = new CircleShape(); - circle.setRadius( 1 ); - - FixtureDef circleShapeDef = new FixtureDef( ); - circleShapeDef.shape = circle; - circleShapeDef.density = 1.0f; - - - circleShapeDef.filter.groupIndex = k_smallGroup; - circleShapeDef.filter.categoryBits = k_circleCategory; - circleShapeDef.filter.maskBits = k_circleMask; - - BodyDef circleBodyDef = new BodyDef( ); - circleBodyDef.type = BodyType.DynamicBody; - circleBodyDef.position.set( 5, 2 ); - - Body body5 = world.createBody( circleBodyDef ); - body5.createFixture(circleShapeDef); - - circle.setRadius( 2 ); - circleShapeDef.filter.groupIndex = k_largeGroup; - circleBodyDef.position.set( 5, 6 ); - - Body body6 = world.createBody( circleBodyDef ); - body6.createFixture( circleShapeDef ); + + boxShapeDef.filter.groupIndex = k_smallGroup; + boxShapeDef.filter.categoryBits = k_boxCategory; + boxShapeDef.filter.maskBits = k_boxMask; + + BodyDef boxBodyDef = new BodyDef(); + boxBodyDef.type = BodyType.DynamicBody; + boxBodyDef.position.set(0, 2); + + Body body3 = world.createBody(boxBodyDef); + body3.createFixture(boxShapeDef); + + polygon.setAsBox(2, 1); + boxShapeDef.filter.groupIndex = k_largeGroup; + boxBodyDef.position.set(0, 6); + + Body body4 = world.createBody(boxBodyDef); + body4.createFixture(boxShapeDef); + + CircleShape circle = new CircleShape(); + circle.setRadius(1); + + FixtureDef circleShapeDef = new FixtureDef(); + circleShapeDef.shape = circle; + circleShapeDef.density = 1.0f; + + circleShapeDef.filter.groupIndex = k_smallGroup; + circleShapeDef.filter.categoryBits = k_circleCategory; + circleShapeDef.filter.maskBits = k_circleMask; + + BodyDef circleBodyDef = new BodyDef(); + circleBodyDef.type = BodyType.DynamicBody; + circleBodyDef.position.set(5, 2); + + Body body5 = world.createBody(circleBodyDef); + body5.createFixture(circleShapeDef); + + circle.setRadius(2); + circleShapeDef.filter.groupIndex = k_largeGroup; + circleBodyDef.position.set(5, 6); + + Body body6 = world.createBody(circleBodyDef); + body6.createFixture(circleShapeDef); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/ContinuousTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/ContinuousTest.java index 89dc66acb..0b0004921 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/ContinuousTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/ContinuousTest.java @@ -1,83 +1,74 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.box2d; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; +import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; -import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; -public class ContinuousTest extends Box2DTest -{ +public class ContinuousTest extends Box2DTest { int m_stepCount = 0; Body m_body; - float m_angularVelocity; - - @Override - protected void createWorld(World world) - { + float m_angularVelocity; + + @Override protected void createWorld (World world) { { - BodyDef bd = new BodyDef( ); - bd.position.set( 0, 0 ); - Body body = world.createBody( bd ); - - PolygonShape shape = new PolygonShape( ); - shape.setAsEdge( new Vector2( -10, 0 ), new Vector2( 10, 0 ) ); - body.createFixture( shape, 0 ); - - shape.setAsBox( 0.2f, 1.0f, new Vector2( 0.5f, 1.0f ), 0 ); - body.createFixture( shape, 0); + BodyDef bd = new BodyDef(); + bd.position.set(0, 0); + Body body = world.createBody(bd); + + PolygonShape shape = new PolygonShape(); + shape.setAsEdge(new Vector2(-10, 0), new Vector2(10, 0)); + body.createFixture(shape, 0); + + shape.setAsBox(0.2f, 1.0f, new Vector2(0.5f, 1.0f), 0); + body.createFixture(shape, 0); shape.dispose(); } - + { - BodyDef bd = new BodyDef( ); + BodyDef bd = new BodyDef(); bd.type = BodyType.DynamicBody; - bd.position.set( 0, 20 ); - - PolygonShape shape = new PolygonShape( ); - shape.setAsBox( 2, 0.1f ); - - m_body = world.createBody( bd ); - m_body.createFixture( shape, 1 ); - + bd.position.set(0, 20); + + PolygonShape shape = new PolygonShape(); + shape.setAsBox(2, 0.1f); + + m_body = world.createBody(bd); + m_body.createFixture(shape, 1); + m_angularVelocity = 33.468121f; - m_body.setLinearVelocity( new Vector2( 0, -100 ) ); - m_body.setAngularVelocity( m_angularVelocity ); + m_body.setLinearVelocity(new Vector2(0, -100)); + m_body.setAngularVelocity(m_angularVelocity); shape.dispose(); - } + } } - - private void launch( ) - { - m_body.setTransform( new Vector2( 0, 20 ), 0 ); + + private void launch () { + m_body.setTransform(new Vector2(0, 20), 0); m_angularVelocity = (float)Math.random() * 100 - 50; - m_body.setLinearVelocity( new Vector2( 0, -100 ) ); - m_body.setAngularVelocity( m_angularVelocity ); + m_body.setLinearVelocity(new Vector2(0, -100)); + m_body.setAngularVelocity(m_angularVelocity); } - public void render( ) - { - super.render( ); - - + public void render () { + super.render(); + m_stepCount++; - if( m_stepCount % 60 == 0 ) - launch( ); + if (m_stepCount % 60 == 0) launch(); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/DebugRendererTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/DebugRendererTest.java index 318b4e16c..9ae6fbd27 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/DebugRendererTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/DebugRendererTest.java @@ -1,56 +1,54 @@ + package com.badlogic.gdx.tests.box2d; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; +import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; -import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; -public class DebugRendererTest extends Box2DTest -{ +public class DebugRendererTest extends Box2DTest { - @Override - protected void createWorld(World world) - { + @Override protected void createWorld (World world) { { - PolygonShape shape = new PolygonShape( ); - shape.setAsEdge( new Vector2( -40.0f, 0 ), new Vector2( 40, 0 ) ); - - FixtureDef fd = new FixtureDef( ); + PolygonShape shape = new PolygonShape(); + shape.setAsEdge(new Vector2(-40.0f, 0), new Vector2(40, 0)); + + FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.friction = 0.3f; - + BodyDef bd = new BodyDef(); - Body ground = world.createBody( bd ); - ground.createFixture( fd ); + Body ground = world.createBody(bd); + ground.createFixture(fd); shape.dispose(); } - + { - PolygonShape shape = new PolygonShape( ); - shape.setAsBox(1, 2f ); - - BodyDef def = new BodyDef( ); + PolygonShape shape = new PolygonShape(); + shape.setAsBox(1, 2f); + + BodyDef def = new BodyDef(); def.position.y = 10; def.angle = (float)Math.toRadians(90); def.type = BodyType.DynamicBody; - - Body body = world.createBody( def ); - body.createFixture( shape, 1 ); - - def = new BodyDef( ); + + Body body = world.createBody(def); + body.createFixture(shape, 1); + + def = new BodyDef(); def.position.x = 10; def.position.y = 10; def.angle = 0; def.type = BodyType.DynamicBody; - - body = world.createBody( def ); - body.createFixture( shape, 1 ); - + + body = world.createBody(def); + body.createFixture(shape, 1); + shape.dispose(); } - + } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/OneSidedPlatform.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/OneSidedPlatform.java index e3bcb87e3..9ad79eae2 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/OneSidedPlatform.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/OneSidedPlatform.java @@ -1,104 +1,91 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.box2d; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; +import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.CircleShape; import com.badlogic.gdx.physics.box2d.ContactFilter; import com.badlogic.gdx.physics.box2d.Fixture; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; -import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; -public class OneSidedPlatform extends Box2DTest -{ - enum State - { - Unknown, - Above, - Below +public class OneSidedPlatform extends Box2DTest { + enum State { + Unknown, Above, Below } - + Fixture m_platform; Fixture m_character; float m_bottom; float m_top; float m_radius; State m_state; - - @Override - protected void createWorld(World world) - { + + @Override protected void createWorld (World world) { { - BodyDef bd = new BodyDef( ); - Body ground = world.createBody( bd ); - - PolygonShape shape = new PolygonShape( ); - shape.setAsEdge( new Vector2( -20.0f, 0 ), new Vector2( 20.0f, 0f ) ); - ground.createFixture( shape, 0); + BodyDef bd = new BodyDef(); + Body ground = world.createBody(bd); + + PolygonShape shape = new PolygonShape(); + shape.setAsEdge(new Vector2(-20.0f, 0), new Vector2(20.0f, 0f)); + ground.createFixture(shape, 0); shape.dispose(); } - + { - BodyDef bd = new BodyDef( ); - bd.position.set( 0, 10 ); - Body body = world.createBody( bd ); - - PolygonShape shape = new PolygonShape( ); - shape.setAsBox( 3, 0.5f ); - m_platform = body.createFixture( shape, 0 ); + BodyDef bd = new BodyDef(); + bd.position.set(0, 10); + Body body = world.createBody(bd); + + PolygonShape shape = new PolygonShape(); + shape.setAsBox(3, 0.5f); + m_platform = body.createFixture(shape, 0); m_bottom = 10.0f - 0.5f; m_top = 10.0f + 0.5f; } - + { - BodyDef bd = new BodyDef( ); + BodyDef bd = new BodyDef(); bd.type = BodyType.DynamicBody; - bd.position.set( 0, 12 ); - Body body = world.createBody( bd ); - + bd.position.set(0, 12); + Body body = world.createBody(bd); + m_radius = 0.5f; CircleShape shape = new CircleShape(); - shape.setRadius( m_radius ); - m_character = body.createFixture( shape, 20.0f ); + shape.setRadius(m_radius); + m_character = body.createFixture(shape, 20.0f); shape.dispose(); - + m_state = State.Unknown; - } - - world.setContactFilter( new ContactFilter( ) { + } + + world.setContactFilter(new ContactFilter() { - @Override - public boolean shouldCollide(Fixture fixtureA, Fixture fixtureB) - { - if( ( fixtureA == m_platform && fixtureB == m_character ) || - ( fixtureA == m_platform && fixtureB == m_character ) ) - { + @Override public boolean shouldCollide (Fixture fixtureA, Fixture fixtureB) { + if ((fixtureA == m_platform && fixtureB == m_character) || (fixtureA == m_platform && fixtureB == m_character)) { Vector2 position = m_character.getBody().getPosition(); - if( position.y < m_top + m_radius - 3.0f * 0.005f ) + if (position.y < m_top + m_radius - 3.0f * 0.005f) return false; else return true; - } - else + } else return true; } - + }); } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/Prismatic.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/Prismatic.java index 3f2280a72..4fdbc1b74 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/Prismatic.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/Prismatic.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.box2d; import com.badlogic.gdx.Gdx; @@ -27,76 +25,69 @@ import com.badlogic.gdx.physics.box2d.World; import com.badlogic.gdx.physics.box2d.joints.PrismaticJoint; import com.badlogic.gdx.physics.box2d.joints.PrismaticJointDef; -public class Prismatic extends Box2DTest -{ +public class Prismatic extends Box2DTest { PrismaticJoint m_joint; - - @Override - protected void createWorld(World world) - { + + @Override protected void createWorld (World world) { Body ground; - + { - BodyDef bd = new BodyDef( ); - ground = world.createBody( bd ); + BodyDef bd = new BodyDef(); + ground = world.createBody(bd); PolygonShape shape = new PolygonShape(); - shape.setAsEdge( new Vector2( -40, 0 ), new Vector2( 40, 0 ) ); - ground.createFixture( shape, 0 ); + shape.setAsEdge(new Vector2(-40, 0), new Vector2(40, 0)); + ground.createFixture(shape, 0); shape.dispose(); } - + { - PolygonShape shape = new PolygonShape( ); - shape.setAsBox( 2, 5 ); - + PolygonShape shape = new PolygonShape(); + shape.setAsBox(2, 5); + BodyDef bd = new BodyDef(); bd.type = BodyType.DynamicBody; - bd.position.set( -10, 10 ); + bd.position.set(-10, 10); bd.angle = 0.5f * (float)Math.PI; bd.allowSleep = false; - - Body body = world.createBody( bd ); - body.createFixture( shape, 5.0f ); - + + Body body = world.createBody(bd); + body.createFixture(shape, 5.0f); + PrismaticJointDef pjd = new PrismaticJointDef(); - - Vector2 axis = new Vector2( 2, 1 ); + + Vector2 axis = new Vector2(2, 1); axis.nor(); - pjd.initialize( ground, body, new Vector2( 0, 0 ), axis ); - + pjd.initialize(ground, body, new Vector2(0, 0), axis); + pjd.motorSpeed = 10.0f; pjd.maxMotorForce = 10000.0f; pjd.enableMotor = true; pjd.lowerTranslation = 0; pjd.upperTranslation = 20.0f; pjd.enableLimit = true; - - m_joint = (PrismaticJoint)world.createJoint( pjd ); + + m_joint = (PrismaticJoint)world.createJoint(pjd); } } - - public boolean keyDown( int keyCode ) - { - if( keyCode == Keys.KEYCODE_L ) - m_joint.enableLimit( !m_joint.isLimitEnabled() ); - if( keyCode == Keys.KEYCODE_M ) - m_joint.enableMotor( !m_joint.isMotorEnabled() ); - if( keyCode == Keys.KEYCODE_S ) - m_joint.setMotorSpeed( -m_joint.getMotorSpeed() ); - + + public boolean keyDown (int keyCode) { + if (keyCode == Keys.KEYCODE_L) m_joint.enableLimit(!m_joint.isLimitEnabled()); + if (keyCode == Keys.KEYCODE_M) m_joint.enableMotor(!m_joint.isMotorEnabled()); + if (keyCode == Keys.KEYCODE_S) m_joint.setMotorSpeed(-m_joint.getMotorSpeed()); + return false; - + } - - public void render( ) - { - super.render( ); - - if( renderer.batch != null ) - { + + public void render () { + super.render(); + + if (renderer.batch != null) { renderer.batch.begin(); - renderer.batch.drawText( renderer.font, "Keys: (l) limits, (m) motors, (s) speed", 0, Gdx.app.getGraphics().getHeight(), Color.WHITE ); - renderer.batch.drawText( renderer.font, "Motor Force = " + m_joint.getMotorForce(), 0, Gdx.app.getGraphics().getHeight() - 15, Color.WHITE ); + renderer.batch.drawText(renderer.font, "Keys: (l) limits, (m) motors, (s) speed", 0, Gdx.app.getGraphics().getHeight(), + Color.WHITE); + renderer.batch.drawText(renderer.font, "Motor Force = " + m_joint.getMotorForce(), 0, + Gdx.app.getGraphics().getHeight() - 15, Color.WHITE); renderer.batch.end(); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/Pyramid.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/Pyramid.java index aed1d5683..9a9a3dfc9 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/Pyramid.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/Pyramid.java @@ -1,70 +1,63 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.box2d; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; +import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; -import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; -public class Pyramid extends Box2DTest -{ - @Override - protected void createWorld(World world) - { +public class Pyramid extends Box2DTest { + @Override protected void createWorld (World world) { { - BodyDef bd = new BodyDef( ); + BodyDef bd = new BodyDef(); Body ground = world.createBody(bd); - - PolygonShape shape = new PolygonShape( ); - shape.setAsEdge( new Vector2( -40, 0), new Vector2( 40, 0 ) ); - ground.createFixture( shape, 0.0f ); + + PolygonShape shape = new PolygonShape(); + shape.setAsEdge(new Vector2(-40, 0), new Vector2(40, 0)); + ground.createFixture(shape, 0.0f); shape.dispose(); } - + { float a = 0.5f; PolygonShape shape = new PolygonShape(); - shape.setAsBox( a, a ); - - Vector2 x = new Vector2( -7.0f, 0.75f ); + shape.setAsBox(a, a); + + Vector2 x = new Vector2(-7.0f, 0.75f); Vector2 y = new Vector2(); - Vector2 deltaX = new Vector2( 0.5625f, 1.25f ); - Vector2 deltaY = new Vector2( 1.125f, 0.0f ); - - for( int i = 0; i < 20; i++ ) - { - y.set( x ); - - for( int j = i; j < 20; j++ ) - { - BodyDef bd = new BodyDef( ); + Vector2 deltaX = new Vector2(0.5625f, 1.25f); + Vector2 deltaY = new Vector2(1.125f, 0.0f); + + for (int i = 0; i < 20; i++) { + y.set(x); + + for (int j = i; j < 20; j++) { + BodyDef bd = new BodyDef(); bd.type = BodyType.DynamicBody; - bd.position.set( y ); - Body body = world.createBody( bd ); - body.createFixture( shape, 5.0f ); - - y.add( deltaY ); + bd.position.set(y); + Body body = world.createBody(bd); + body.createFixture(shape, 5.0f); + + y.add(deltaY); } - - x.add( deltaX ); + + x.add(deltaX); } - + } } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/SimpleTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/SimpleTest.java index deaedb979..9ce82bf1b 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/SimpleTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/SimpleTest.java @@ -1,94 +1,87 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.box2d; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; +import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.CircleShape; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; -import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; -public class SimpleTest extends Box2DTest -{ - @Override - protected void createWorld(World world) - { +public class SimpleTest extends Box2DTest { + @Override protected void createWorld (World world) { // next we create a static ground platform. This platform // is not moveable and will not react to any influences from // outside. It will however influence other bodies. First we // create a PolygonShape that holds the form of the platform. // it will be 100 meters wide and 2 meters high, centered // around the origin - PolygonShape groundPoly = new PolygonShape( ); - groundPoly.setAsBox( 50, 1 ); - + PolygonShape groundPoly = new PolygonShape(); + groundPoly.setAsBox(50, 1); + // next we create the body for the ground platform. It's // simply a static body. BodyDef groundBodyDef = new BodyDef(); groundBodyDef.type = BodyType.StaticBody; - groundBody = world.createBody( groundBodyDef ); - + groundBody = world.createBody(groundBodyDef); + // finally we add a fixture to the body using the polygon // defined above. Note that we have to dispose PolygonShapes // and CircleShapes once they are no longer used. This is the // only time you have to care explicitely for memomry managment. - groundBody.createFixture( groundPoly, 10 ); + groundBody.createFixture(groundPoly, 10); groundPoly.dispose(); - + // next we create 50 boxes at random locations above the ground // body. First we create a nice polygon representing a box 2 meters // wide and high. - PolygonShape boxPoly = new PolygonShape( ); - boxPoly.setAsBox( 1, 1 ); - + PolygonShape boxPoly = new PolygonShape(); + boxPoly.setAsBox(1, 1); + // next we create the 50 box bodies using the PolygonShape we just // defined. This process is similar to the one we used for the ground // body. Note that we reuse the polygon for each body fixture. - for( int i = 0; i < 20; i++ ) - { - // Create the BodyDef, set a random position above the + for (int i = 0; i < 20; i++) { + // Create the BodyDef, set a random position above the // ground and create a new body - BodyDef boxBodyDef = new BodyDef( ); + BodyDef boxBodyDef = new BodyDef(); boxBodyDef.type = BodyType.DynamicBody; boxBodyDef.position.x = -24 + (float)(Math.random() * 48); - boxBodyDef.position.y = 10 + (float)(Math.random() * 100); - Body boxBody = world.createBody( boxBodyDef ); - + boxBodyDef.position.y = 10 + (float)(Math.random() * 100); + Body boxBody = world.createBody(boxBodyDef); + // add the boxPoly shape as a fixture - boxBody.createFixture( boxPoly, 10 ); + boxBody.createFixture(boxPoly, 10); } - + // we are done, all that's left is disposing the boxPoly boxPoly.dispose(); - + // next we add a few more circles - CircleShape circleShape = new CircleShape( ); - circleShape.setRadius( 1 ); - - for( int i = 0; i < 10; i++ ) - { - BodyDef circleBodyDef = new BodyDef( ); + CircleShape circleShape = new CircleShape(); + circleShape.setRadius(1); + + for (int i = 0; i < 10; i++) { + BodyDef circleBodyDef = new BodyDef(); circleBodyDef.type = BodyType.DynamicBody; circleBodyDef.position.x = -24 + (float)(Math.random() * 48); - circleBodyDef.position.y = 10 + (float)(Math.random() * 100); - Body circleBody = world.createBody( circleBodyDef ); - + circleBodyDef.position.y = 10 + (float)(Math.random() * 100); + Body circleBody = world.createBody(circleBodyDef); + // add the boxPoly shape as a fixture - circleBody.createFixture( circleShape, 10 ); + circleBody.createFixture(circleShape, 10); } circleShape.dispose(); } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/SphereStack.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/SphereStack.java index 80269f8fa..11d398d33 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/SphereStack.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/SphereStack.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.box2d; import com.badlogic.gdx.math.Vector2; @@ -23,40 +21,35 @@ import com.badlogic.gdx.physics.box2d.CircleShape; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; -public class SphereStack extends Box2DTest -{ +public class SphereStack extends Box2DTest { int e_count = 10; - - - @Override - protected void createWorld(World world) - { + + @Override protected void createWorld (World world) { { BodyDef bd = new BodyDef(); - Body ground = world.createBody( bd ); - + Body ground = world.createBody(bd); + PolygonShape shape = new PolygonShape(); - shape.setAsEdge( new Vector2( -40, 0 ), new Vector2( 40, 0 ) ); - ground.createFixture( shape, 0 ); + shape.setAsEdge(new Vector2(-40, 0), new Vector2(40, 0)); + ground.createFixture(shape, 0); shape.dispose(); } - + { CircleShape shape = new CircleShape(); - shape.setRadius( 1.0f ); - - for( int i = 0; i < e_count; i++ ) - { - BodyDef bd = new BodyDef( ); + shape.setRadius(1.0f); + + for (int i = 0; i < e_count; i++) { + BodyDef bd = new BodyDef(); bd.type = BodyType.DynamicBody; - bd.position.set( 0, 4.0f + 3.0f * i ); - Body body = world.createBody( bd ); - body.createFixture( shape, 1.0f ); + bd.position.set(0, 4.0f + 3.0f * i); + Body body = world.createBody(bd); + body.createFixture(shape, 1.0f); } - + shape.dispose(); } - + } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/TestCollection.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/TestCollection.java index 2c299b759..8be34a7d4 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/TestCollection.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/TestCollection.java @@ -1,109 +1,89 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.box2d; import com.badlogic.gdx.Application; import com.badlogic.gdx.Gdx; +import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.InputListener; import com.badlogic.gdx.RenderListener; -import com.badlogic.gdx.Input.Keys; -public class TestCollection implements RenderListener, InputListener -{ - private final Box2DTest[] tests = { new DebugRendererTest(), new CollisionFiltering(), new Chain(), new Bridge(), new SphereStack(), new Cantilever(), new ApplyForce(), new ContinuousTest(), new Prismatic(), new CharacterCollision(), new BodyTypes(), new SimpleTest(), new Pyramid( ), new OneSidedPlatform(), new VerticalStack(), - new VaryingRestitution() - }; - +public class TestCollection implements RenderListener, InputListener { + private final Box2DTest[] tests = {new DebugRendererTest(), new CollisionFiltering(), new Chain(), new Bridge(), + new SphereStack(), new Cantilever(), new ApplyForce(), new ContinuousTest(), new Prismatic(), new CharacterCollision(), + new BodyTypes(), new SimpleTest(), new Pyramid(), new OneSidedPlatform(), new VerticalStack(), new VaryingRestitution()}; + private int testIndex = 0; - + private Application app = null; - @Override - public void dispose() { + @Override public void dispose () { // TODO Auto-generated method stub - + } - @Override - public void render() - { + @Override public void render () { tests[testIndex].render(); } - @Override - public void surfaceChanged(int width, int height) - { + @Override public void surfaceChanged (int width, int height) { } - @Override - public void surfaceCreated() - { - if( this.app == null ) - { + @Override public void surfaceCreated () { + if (this.app == null) { this.app = Gdx.app; Box2DTest test = tests[testIndex]; - test.surfaceCreated( ); - app.getInput().addInputListener( this ); + test.surfaceCreated(); + app.getInput().addInputListener(this); } } - @Override - public boolean keyDown(int keycode) - { - if( keycode == Keys.KEYCODE_SPACE ) - { - app.log( "TestCollection", "disposing test '" + tests[testIndex].getClass().getName() ); - tests[testIndex].dispose( ); + @Override public boolean keyDown (int keycode) { + if (keycode == Keys.KEYCODE_SPACE) { + app.log("TestCollection", "disposing test '" + tests[testIndex].getClass().getName()); + tests[testIndex].dispose(); testIndex++; - if( testIndex >= tests.length ) - testIndex = 0; + if (testIndex >= tests.length) testIndex = 0; Box2DTest test = tests[testIndex]; - test.surfaceCreated( ); - app.log( "TestCollection", "created test '" + tests[testIndex].getClass().getName() ); + test.surfaceCreated(); + app.log("TestCollection", "created test '" + tests[testIndex].getClass().getName()); } - + return false; } - @Override - public boolean keyTyped(char character) { + @Override public boolean keyTyped (char character) { // TODO Auto-generated method stub return false; } - @Override - public boolean keyUp(int keycode) { + @Override public boolean keyUp (int keycode) { // TODO Auto-generated method stub return false; } - @Override - public boolean touchDown(int x, int y, int pointer) { + @Override public boolean touchDown (int x, int y, int pointer) { // TODO Auto-generated method stub return false; } - @Override - public boolean touchDragged(int x, int y, int pointer) { + @Override public boolean touchDragged (int x, int y, int pointer) { // TODO Auto-generated method stub return false; } - @Override - public boolean touchUp(int x, int y, int pointer) { + @Override public boolean touchUp (int x, int y, int pointer) { // TODO Auto-generated method stub return false; } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/VaryingRestitution.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/VaryingRestitution.java index 82b2fd7f5..c834c1066 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/VaryingRestitution.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/VaryingRestitution.java @@ -1,65 +1,59 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.box2d; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; +import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.CircleShape; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; -import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; -public class VaryingRestitution extends Box2DTest -{ - @Override - protected void createWorld(World world) - { +public class VaryingRestitution extends Box2DTest { + @Override protected void createWorld (World world) { { - BodyDef bd = new BodyDef( ); + BodyDef bd = new BodyDef(); Body ground = world.createBody(bd); - - PolygonShape shape = new PolygonShape( ); - shape.setAsEdge( new Vector2( -40, 0), new Vector2( 40, 0 ) ); - ground.createFixture( shape, 0.0f ); + + PolygonShape shape = new PolygonShape(); + shape.setAsEdge(new Vector2(-40, 0), new Vector2(40, 0)); + ground.createFixture(shape, 0.0f); shape.dispose(); } - + { - CircleShape shape = new CircleShape( ); - shape.setRadius( 1 ); - + CircleShape shape = new CircleShape(); + shape.setRadius(1); + FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.density = 1.0f; - - float restitution[] = { 0, 0.1f, 0.3f, 0.5f, 0.75f, 0.9f, 1.0f }; - - for( int i = 0; i < restitution.length; i++ ) - { + + float restitution[] = {0, 0.1f, 0.3f, 0.5f, 0.75f, 0.9f, 1.0f}; + + for (int i = 0; i < restitution.length; i++) { BodyDef bd = new BodyDef(); bd.type = BodyType.DynamicBody; - bd.position.set( -10.0f + 3.0f * i, 20.0f ); - - Body body = world.createBody( bd ); + bd.position.set(-10.0f + 3.0f * i, 20.0f); + + Body body = world.createBody(bd); fd.restitution = restitution[i]; - body.createFixture( fd ); + body.createFixture(fd); } - + shape.dispose(); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/VerticalStack.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/VerticalStack.java index 4cb428ddf..5a3be2371 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/VerticalStack.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/VerticalStack.java @@ -1,18 +1,16 @@ /******************************************************************************* * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.box2d; import com.badlogic.gdx.Gdx; @@ -21,115 +19,105 @@ import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; +import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.CircleShape; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; -import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; -public class VerticalStack extends Box2DTest -{ +public class VerticalStack extends Box2DTest { static final int e_columnCount = 5; static final int e_rowCount = 16; Body m_bullet; Body[] m_bodies = new Body[e_rowCount * e_columnCount]; int[] m_indices = new int[e_rowCount * e_columnCount]; - - @Override - protected void createWorld(World world) - { + + @Override protected void createWorld (World world) { { - BodyDef bd = new BodyDef( ); + BodyDef bd = new BodyDef(); Body ground = world.createBody(bd); - - PolygonShape shape = new PolygonShape( ); - shape.setAsEdge( new Vector2( -40, 0), new Vector2( 40, 0 ) ); - ground.createFixture( shape, 0.0f ); - - shape.setAsEdge( new Vector2( 20, 0 ), new Vector2( 20, 20 ) ); - ground.createFixture( shape, 0 ); + + PolygonShape shape = new PolygonShape(); + shape.setAsEdge(new Vector2(-40, 0), new Vector2(40, 0)); + ground.createFixture(shape, 0.0f); + + shape.setAsEdge(new Vector2(20, 0), new Vector2(20, 20)); + ground.createFixture(shape, 0); shape.dispose(); } - - float xs[] = {0, -10, -5, 5, 10 }; - - for( int j = 0; j < e_columnCount; j++ ) - { + + float xs[] = {0, -10, -5, 5, 10}; + + for (int j = 0; j < e_columnCount; j++) { PolygonShape shape = new PolygonShape(); - shape.setAsBox( 0.5f, 0.5f ); - + shape.setAsBox(0.5f, 0.5f); + FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.density = 1.0f; fd.friction = 0.3f; - - for( int i = 0; i < e_rowCount; i++ ) - { + + for (int i = 0; i < e_rowCount; i++) { BodyDef bd = new BodyDef(); bd.type = BodyType.DynamicBody; - + int n = j * e_rowCount + i; m_indices[n] = n; - + float x = 0; - bd.position.set( xs[j] + x, 0.752f + 1.54f * i ); + bd.position.set(xs[j] + x, 0.752f + 1.54f * i); Body body = world.createBody(bd); - body.setUserData( n ); - + body.setUserData(n); + m_bodies[n] = body; body.createFixture(fd); } - + shape.dispose(); } - + m_bullet = null; } - @Override - public boolean keyDown( int keyCode ) - { - if( keyCode == Input.Keys.KEYCODE_COMMA ) - { - if( m_bullet != null ) - { - world.destroyBody( m_bullet ); + @Override public boolean keyDown (int keyCode) { + if (keyCode == Input.Keys.KEYCODE_COMMA) { + if (m_bullet != null) { + world.destroyBody(m_bullet); m_bullet = null; } - + { CircleShape shape = new CircleShape(); - shape.setRadius( 0.25f ); - + shape.setRadius(0.25f); + FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.density = 20.0f; fd.restitution = 0.05f; - - BodyDef bd = new BodyDef( ); + + BodyDef bd = new BodyDef(); bd.type = BodyType.DynamicBody; bd.bullet = true; - bd.position.set( -31, 5 ); - - m_bullet = world.createBody( bd ); - m_bullet.createFixture( fd ); - - m_bullet.setLinearVelocity( new Vector2( 400, 0 ) ); + bd.position.set(-31, 5); + + m_bullet = world.createBody(bd); + m_bullet.createFixture(fd); + + m_bullet.setLinearVelocity(new Vector2(400, 0)); } } - + return false; } - - public void render( ) - { - super.render( ); - - if( renderer.batch != null ) - { + + public void render () { + super.render(); + + if (renderer.batch != null) { renderer.batch.begin(); - renderer.batch.drawText( renderer.font, "Press: (,) to launch a bullet", 0, Gdx.app.getGraphics().getHeight(), Color.WHITE); + renderer.batch.drawText(renderer.font, "Press: (,) to launch a bullet", 0, Gdx.app.getGraphics().getHeight(), + Color.WHITE); renderer.batch.end(); } } -- 2.11.0